Sunday, November 7, 2010
What will happen when you attempt to compile and run the above code? (Assume that the code is compiled and run with assertions enabled.)
a. It will print odd and even numbers from 0 to 9 correctly (0 even and 1 odd).
b. It will print odd and even numbers from 0 to 9 incorrectly (0 odd and 1 even).
c. Compilation error at line 9.
d. Compilation error at line 10.
e. It will result in an infinite loop.
Solution : Choice A is the correct answer.
The code will compile successfully and it will print odd and even numbers from 0 to 9 correctly, without reversing even and odd.
Let's look at the execution of the code. The assert statement at line 9 asserts that "i%2==0" must be true, which will be true for all the even numbers in the range 0 to 9 (0, 2, 4, 6, and 8), and false for all the odd numbers in the range 0 to 9 (1, 3, 5, 7, and 9). When the assert statement is evaluated to true, the second expression on the right hand side of the colon is not evaluated. On the other hand, when the assert statement is evaluated to false, the expression on the right hand side of the colon is evaluated and an AssertionError is thrown.
When the for loop starts with i=0, the assert condition at line 9 is evaluated to true, hence the other expression i-- is not evaluated, the value of i (0 here) is printed at line 10. Next, i is incremented to 1 in the next iteration of the for loop. The assert condition at line 9 is false in this case, hence the expression i--is evaluated (i becomes 0) and an AssertionError is thrown. The print statement at line 10 is not executed in this case. The catch statement at line 12 catches this error and the print statement at line 14 increments i with ++i and prints its value (which is 1 in this case). The same process is repeated for all the numbers, thus effectively printing all the even and odd number correctly.
The key here lies in understanding when the right-hand side expression of an assert statement gets evaluated. It gets evaluated *only* when the boolean left-hand side expression is evaluated to false. Hence, the loop will not result in an infinite loop.
Source : "Facebook community"