OCA Java SE 8 Operators/Statements - OCA Mock Question Operator and Statement 18








Question

What is the output of the following code snippet?

3: boolean x = true, z = true; 
4: int y = 2; 
5: x = (y != 1) ^ (z=false); 
6: System.out.println(x+", "+y+", "+z); 
  1. true, 1, true
  2. true, 2, false
  3. false, 2, true
  4. false, 2, false
  5. false, 2, true
  6. The code will not compile because of line 5.




Answer



B.

Note

z=false assigns the value false to z and returns false for the expression.

Since y does not equal 1, the left-hand side returns true; therefore, the exclusive or ^ of the entire expression assigned to x is true.

There is no no change to y.

public class Main{
   public static void main(String[] argv){
        boolean x = true, z = true; 
        int y = 2; 
        x = (y != 1) ^ (z=false); 
        System.out.println(x+", "+y+", "+z);       
   }
}