Feedback - An explanation is required.

I have been programming in java for a while, but I just go back to the basics and try to understand what is going on.

The syntax for reversing a string using a for loop, which decreases rather than increases, is

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

But I really don't understand why I need to put "-1" after .length ()? Here is 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 of -1? I can’t interpret this, except that it really works.

+4
source share
5 answers

If the string has 4 characters, you will get the first through charAt(0), and the last through charAt(3), because the index is based on a zero value. So your loop will start at 3 and end at 0, and not start at 4.

+9

length - 1, , Java- , 0-. , 0 capacity - 1.

capacity IndexOutOfBoundsException

+3

, String char[]. Java, .length() - (, ) . ( ) 0, "" 0 ..

+1

0 n-1, n. IndexOutOfBoundException, ( ) - n-1. array.lenght n. .

+1

If you have the string "Test", the total length is 4, but the charatcter counter starts at 0 and ends at 3, and if the length of the string in your loop is string.length (), it will be 4, but it ends at 3.

So your loop will start at 3 and end at 0. therefore, to avoid IndexOutOfBoundsException, it has a value of string.length () - 1

0
source

All Articles