Charles
Charles

Reputation: 161

Reverse for-loop - explanation wanted

I've been programing in java for a while now but I'm just getting back to the basics and try to actually understand what is going on.

The syntax for reversing a string using a for-loop that decrements instead of incrementing is

for (int i = string.length() - 1; i >= 0; i--)

But I don't really understand why I have to put " - 1 " after .length()? Here's my code.

public static void main(String[] args) {
    // TODO Auto-generated method stub
    reverseVertical("laptop");
}

private static void reverseVertical(String string) {
    // TODO Auto-generated method stub

    for (int i = string.length() - 1; i >= 0; i--) {
        System.out.println(string.charAt(i));
    }

}

What is the logic behind the " - 1 "? I can't make any sense of it - other than it actually works.

Upvotes: 4

Views: 494

Answers (5)

Abhijit Bashetti
Abhijit Bashetti

Reputation: 8658

If you have a string "Test" the the total length is 4, but the charatcter counts starts from 0 and ends at 3 and if you have string length in your loop as string.length(), it would 4 but it ends at 3.

So here your loop will start at 3 and will end at 0. so to avoid the IndexOutOfBoundsException have it goes as string.length()-1

Upvotes: 0

user
user

Reputation: 745

Arrays begin with index 0 up to n-1 if the allocated size was n. To prevent an IndexOutOfBoundException the correct (highest) valid index is n-1. However array.lenght will return n. So you have to shift the index.

Upvotes: 1

blazetopher
blazetopher

Reputation: 1050

The key here is that String objects are backed by a char[]. So iterating over a string follows the rules for any other Java array, where .length() is the size (count, capacity) of the array. Indexing into any array (including strings) is 0 based, so the item in the "first" slot is accessed using 0 and so on.

Upvotes: 1

Dragondraikk
Dragondraikk

Reputation: 1679

You have to start at length - 1 because Strings, like many other Java Lists and Arrays are 0-indexed. This means their indexes go from 0 to capacity - 1.

Attempting to read the position at capacity will result in an IndexOutOfBoundsException

Upvotes: 3

JP Moresmau
JP Moresmau

Reputation: 7403

If a string has 4 characters, you'll get the first one via charAt(0), and the last one via charAt(3), because the index is zero based. So your loop would start at 3 and ends at 0, and not start at 4.

Upvotes: 9

Related Questions