Java - What is the value of num after ((num = 50) > 5);

Question

Consider the following code.

int num = 10; 
boolean b = ((num = 50) > 5); // Assigns true to b 

What is the value of num?



Click to view the answer

50

Note

In the expression ((num = 50) > 5), the expression, (num = 50), is executed first.

It assigns 50 to num and returns 50, reducing the expression to (50 > 5), which in turn returns true.

If you use the value of num after the expression num = 50 is executed, its value will be 50.

Demo

public class Main {
  public static void main(String[] args) {
    int num = 10; 
    boolean b = ((num = 50) > 5); // Assigns true to b 
    System.out.println(b);//  w w  w . ja v a2s .  c o  m
    System.out.println(num);
  }
}

Result