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








Question

What is the output of the following code snippet?

     3: int x1 = 5, x2 = 7; 
     4: boolean b = x1 >= x2; 
     5: if(b = true) System.out.println("Success"); 
     6: else System.out.println("Failure"); 

  1. Success
  2. Failure
  3. The code will not compile because of line 4.
  4. The code will not compile because of line 5.




Answer



A.

Note

The code compiles successfully.

The value of b after line 4 is false.

if-then statement on line 5 contains an assignment, not a comparison.

The variable b is assigned true on line 3, and the assignment operator returns true, so line 5 executes and displays Success.

public class Main{
   public static void main(String[] argv){
      int x1 = 5, x2 = 7; 
      boolean b = x1 >= x2; 
      if(b = true) 
         System.out.println("Success"); 
      else //from ww w  .  jav a  2 s  .c  o m
         System.out.println("Failure"); 
    
   }
}