Java OCA OCP Practice Question 350

Question

What is the output of the following program?

1: public class Main { 
2:   public static void main(String[] args) { 
3:     int i = 10; 
4:     if((i>10 ? i++: --i)<10) { 
5:       System.out.print("Square"); 
6:     } if(i<10) System.out.print("Rectangle"); 
7: } 
8:} 
  • A. Square
  • B. Rectangle
  • C. SquareRectangle
  • D. The code will not compile because of line 4.
  • E. The code will not compile because of line 6.
  • F. The code compiles without issue but does not produce any output.


C.

Note

The code compiles and runs without issue, so options D and E are correct.

Remember that only one of the right-hand ternary expressions will be evaluated at runtime.

Since i is not less than 10, the second expression, --i, will be evaluated, and since the pre-increment operator was used, the value returned will be 9, which is less than 10.

So the first if-then statement will be visited and Square will be output.

Notice there is no else statement on line 6.

Since i is still less than 10, the second if-then statement will also be reached and Rectangle will be output; therefore, the correct answer is option C.




PreviousNext

Related