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 ;)