Java - What is the value of b after (25 > 5 && ((j = 20) > 15))

Question

Consider the following snippet of code:

int i = 10; 
int j = 10; 
boolean b = (i > 5 && ((j = 20) > 15)); 
  
System.out.println("b = " + b); 
System.out.println("i = " + i); 
System.out.println("j = " + j); 

What is the output?



Click to view the answer

b = true 
i = 10 
j = 20

Demo

public class Main {
  public static void main(String[] args) {
    int i = 10; // ww w  .  j ava  2 s . c  om
    int j = 10; 
    boolean b = (i > 5 && ((j = 20) > 15)); 
      
    System.out.println("b = " + b); 
    System.out.println("i = " + i); 
    System.out.println("j = " + j); 
  }
}

Result

Note

i > 5, evaluated to true, the right-hand of operand ((j = 20) > 15) was evaluated and the variable j was assigned a value 20.

What is the result of the following code?

int i = 10; 
int j = 10; 
boolean b = (i > 25 && ((j = 20) > 15)); 

System.out.println ("b = " + b); 
System.out.println ("i = " + i); 
System.out.println ("j = " + j); // Will print j = 10 


Click to view the answer

b = false
i = 10
j = 10

Demo

public class Main {
  public static void main(String[] args) {
    int i = 10; //ww w.  j  a v a  2  s  .co m
    int j = 10; 
    boolean b = (i > 25 && ((j = 20) > 15)); 

    System.out.println ("b = " + b); 
    System.out.println ("i = " + i); 
    System.out.println ("j = " + j); // Will print j = 10 

  }
}

Result

Note

If the left-hand operand evaluates to false, the right-hand operand would not be evaluated.

The value of j will remain 10.

((j = 20) > 5) is not evaluated because i > 25 returns false