Java OCA OCP Practice Question 1109

Question

Which of the following code snippets will compile without any errors?

Assume that the statement int x = 0; exists prior to the statements below.

Select 3 options

  • A. while (false) { x=3; }
  • B. if (false) { x=3; }
  • C. do{ x = 3; } while (false);
  • D. for ( int i = 0; i< 0; i++) x = 3;


Correct Options are  : B C D

Note

In a do-while, the block is ALWAYS executed at least once because the condition check is done after the block is executed.

Unlike a while loop, where the condition is checked before the execution of the block.

while (false) { x=3; } is a compile-time error because the statement x=3; is not reachable;

for ( int i = 0; false; i++) x = 3; is a compile time error because x= 3 is unreachable.

In if (false){ x=3; }, although the body of the condition is unreachable, this is not an error because the Java Language Specification explicitly defines this as an exception to the rule.

It allows this construct to support optimizations through the conditional compilation.

For example,

if (DEBUG){ 
   System.out.println ("beginning task 1");  
}  

The DEBUG variable can be set to false in the code while generating the production version of the class file, which will allow the compiler to optimize the code by removing the whole if statement entirely from the class file.




PreviousNext

Related