When to use type.length-1; and type.length(); in java

user2888585 picture user2888585 · Oct 21, 2013 · Viewed 48.3k times · Source

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.

Answer

dtgee picture dtgee · Oct 21, 2013

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