There are questions on here that appear to be similar to mine, but they all seem to differ in some respect, so I do think this question is unique.
I am trying out problems from the LinkedIn Skill Assessment for Java. The correct answer to the problem is that the statement will print 10 times. But I don't understand why that is the correct answer.
Here is the code:
public class Main{
public static void main(String[] args) {
for (int i=0; i<10; i=i++){
System.out.println("i first equals " + i);
i+=1;
System.out.println("i now equals " + i);
System.out.println("Hello World!");
}
}
}
I added the first two println statements myself to try to figure out the code.
I would think that i would increment every time the loop runs, and that i would increment in the loop also. So the first time the loop runs, i = 0, then in the loop i is increased to 1 (i+=1), then at the end of the first loop iteration (or the beginning of the second?) i is increased to 2 (i=i++), then in the loop i is increased to 3 (i+=1) and so on. However, the println statements show the following:
i first equals 0
i now equals 1
Hello World!
i first equals 1
i now equals 2
Hello World!
i first equals 2
i now equals 3
Hello World!
and so on. So what am I missing here? Why is there not both an increment within the loop and an increment on the loop itself happening? When the loop println statement says "i now equals 1", why doesn't the value 1 go into the loop's incrementer i=i++ and make it two so the next time within the loop the println says "i first equals 2"?