Java - What is the result: int i =5; if (i = 5){

Question

What is the result of the following code?

public class Main {
  public static void main(String[] args) {
  
    int i =5; 
    if (i = 5){
      System.out.println("5");
    }else {
      System.out.println("not 5");
    }
  }
}


Click to view the answer

if (i = 5) /* A compile-time error */

Note

This if statement will not compile because i = 5 is an assignment expression and it evaluates to an int value 5.

The condition expression in an if statement must be of the boolean type.

To compare two int variables, i and j, for equality, if statement must look like the following:

if (i == j)
    statement

Related Quiz