Thursday, 6 August 2009

Java Certification Question 0056

Given the following class

public class ZeroPrint{

public static void main(String argv[]){

int i =0;

//Here

}

}

Which of the following lines if placed after the comment //Here will print out 0.

1) System.out.println(i++);
2) System.out.println(i+'0');
3) System.out.println(i);
4) System.out.println(i--);


Answer 1, 3 and 4:

1) System.out.println(i++);
3) System.out.println(i);
4) System.out.println(i--);

The options for this question might look suspiciously easy if you are not aware of the effects of the post-increment operators. The ++ and -- operations for examples 1 and 4 only come into effect after the output operations, ie after whatever else is done to them on that line of code. Option 2 should be fairly obvious as you should know that the single quote characters indicate a char value, ie storing the character rather than the numberical value for 0.

No comments: