Java - What is the result: boolean b; if (b = true) {

Question

What is the output?

public class Main {
  public static void main(String[] args) {
    boolean b;
    if (b = true) { /* Always returns true */
      System.out.println("true");
    }else {
      System.out.println("not true");
    }
  }
}


Click to view the answer

true

Note

An assignment expression cannot be used as a condition expression in an if statement, except when you are assigning a Boolean value to a boolean variable.

b = true always returns true after assigning true to b.

Related Quiz