I'm little bit confused when do I really need to use that length-1. I know that is when we don't want to have out of bound error. For instance I wrote this simple array:
int [] oldArray = {1, 5, 6, 10, 25, 17};
for(int i = 0; i < oldArray.length; i++){
It does not give me any error. Any examples when -1 is actually useful? Thank you in advance.
An attempt to refer to an array element with an index outside the range from zero to A. length-1 causes an ArrayIndexOutOfBoundsException. Arrays in Java are objects, so an array variable can only refer to an array; it does not contain the array. The value of an array variable can also be null.
The key difference between Java's length variable and Java's length() method is that the Java length variable describes the size of an array, while Java's length() method tells you how many characters a text String contains.
Java String length() Method The length() method returns the length of a specified string.
ArrayList doesn't have length() method, the size() method of ArrayList provides the number of objects available in the collection. Array has length property which provides the length or capacity of the Array. It is the total space allocated during the initialization of the array.
You want to use oldArray.length
usually in a for loop call, because as in your example,
for(int i = 0; i < oldArray.length; i++) {
//Executes from i = 0 to i = oldArray.length - 1 (inclusive)
}
Notice how i
goes from 0
up until oldArray.length - 1
, but stops exacty at oldArray.length
(and doesn't execute). Since arrays start at position 0
instead of 1
, old.Array.length is a perfect fit for the number that i
should stop at. If arrays started at position 1
instead, for loops would look something like this:
for(int i = 1; i <= oldArray.length; i++) {
//Executes from i = 1 to i = oldArray.length (inclusive)
}
oldArray.length - 1
is usually to access the last element:
int[] oldArray = {1,2,3,4,5};
int lastElement = oldArray.length - 1; // 4
oldArray[lastElement] // returns last element, 5
Although this is usually when you would use length - 1
vs length
, there are many other cases where you would also want one over the other, and thus there is no real specific answer. But don't worry, keep coding, you'll get this hang of this soon ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With