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) {
reverseVertical("laptop");
}
private static void reverseVertical(String string) {
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.
source
share