Is if(x) same as if(x==true)?

if-statement, java

Solution

Yes,

if(x) {

}

is the succinct equivalent of

if(x == true) {

}

As @Sotirios points out, they are different at the bytecode level. Consider the following Java class:

class Test { 
   public void foo() { 
      boolean x = true;
      if(x == true) { 
      }
   }
}

emits:

  public void foo();
    Code:
       0: iconst_1      
       1: istore_1      
       2: iload_1       
       3: iconst_1      
       4: if_icmpne     7
       7: return 

vs

class Test { 
   public void foo() { 
      boolean x = true;
      if(x) { 
      }
   }
}

which emits:

  public void foo();
    Code:
       0: iconst_1      
       1: istore_1      
       2: iload_1       
       3: ifeq          6
       6: return  

I don't think this has any bearing on the performance or correctness of the program.

Problem

Ok, so let's say I have an if statement and a boolean x: ``` if (x) { // some stuff } ``` What happens here? Does this mean the same thing as `if(x == true)` ?

Original source