This week's book giveaway is in the Design forum. We're giving away four copies of Building Microservices and have Sam Newman on-line! See this thread for details.

I am confused on a control question, class JMM110 { public static void main (String[] args) { int j = 0; do for (int i = 0; i++ < 2 System.out.print(i); while (j++ < 2); }} answer = Prints: 121212 This would make sense to me if it was i++ <= 2 and j++ <= 2, otherwise how does it get to 2 for either test.

in both conditional statements you use ++ POSTfix operator. It does the following: first returns the value of a variable, and then increaments it. so in the for loop i++ < 2 means: compare i to 2, then increament it. if i is 0 initially this would happen: is 0 less than 2? yes (the expression evaluates to true) now add 1 to i (i is 1) print i (which is 1) on the next iteration i is 1 so... is 1 less than 2? yes (the expression evaluates to true) now add 1 to i (i is 2) print i (which is 2) the next iteration breaks out of the loop since 2 is not less than 2 change the postfix ++ to prefix and you'll get the desired results.

The sword of destiny has two blades, one of them is you.

so in the for loop you see what is happening, you start by making i=0, then check 0 < 2 then increment. so i=1, 1 < 2 then increment i=2, so output is 12 2 is not less than 2 so check while. while is o < 2 then increment so start the for loop again from the start so ouptut is: 1212 check while 1 < 2, true, so do the for loop again. ouptut is 121212 then check while. 2 is not less than 2 so false so stop the do statement. hope this helps you with the output. Davy