Java OCA OCP Practice Question 504

Question

What is the output of the following application?


public class Main { 
        public String runTest(boolean spinner, boolean roller) { 
           if(spinner = roller) return "up"; 
           else return roller ? "down" : "middle"; 
        } //from ww  w  .ja va  2 s .  c o m
        public static final void main(String pieces[]) { 
           final Main tester = new Main(); 
           System.out.println(tester.runTest(false,true)); 
        } 
} 
  • A. up
  • B. middle
  • C. down
  • D. The code does not compile.


A.

Note

The code compiles without issue, so Option D is incorrect.

The key here is that the if-then statement in the runTest() method uses the assignment operator (=) instead of the (==) operator.

The result is that spinner is assigned a value of true, and the statement (spinner = roller) returns the newly assigned value.

The method then returns up, making Option A the correct answer.

If the (==) operator had been used in the if-then statement, then the process would have branched to the else statement, with down being returned by the method.




PreviousNext

Related