I Need Help Annotating a Java Problem

I am currently beginning a class in Java and I was wondering if someone could walk me step-by-step through this code. This is the first time I have even seen Java code like this as I am just beginning.

String test = "123456";
for (int index = 0; index < test.length() - 1; index = index + 2)
{
    System.out.print(test.substring(index,index+2));
}

The first line creates a new string test which is “123456”.

Next, there is a for loop which is going to loop over the string “123456”.

At the beginning of the for loop, the variable index is declared as an integer and set equal to 0. Then our for loop checks if our variable index, which is equal to zero is less than the length of our string test. This is true, because 0 is less than 6. Then we print the result of

Well, we know index is equal to zero initially, so let’s just plug that in.

test.substring(0, 0+2) which is just test.substring(0, 2) and this is our string indexed from 0 to the second index. Here we need to recall that the Java substring method doesn’t go up to the end index. Refer to this page: https://www.javatpoint.com/substring

So, test.substring(0,2) is really the string from test indexed from 0 to 1 which is “12”.

Since this is a for loop we increment our index and test our condition again. We do index = index + 2; and check if its the case that index < test.length(). The next time index is equal to 2. I’ll let you walk through what happens next.

1 Like