Skip to content

Instantly share code, notes, and snippets.

@Jenjen1324
Created April 5, 2021 15:20
Show Gist options
  • Save Jenjen1324/9b8971c0dced35333ed99f08e51fb128 to your computer and use it in GitHub Desktop.
Save Jenjen1324/9b8971c0dced35333ed99f08e51fb128 to your computer and use it in GitHub Desktop.
Java `Boolean.TRUE` vs `true` when assigning to Boolean

Test.java content:

public class Test {

    public Boolean mBoolean;

    public void foo() {
        this.mBoolean = Boolean.TRUE;
    }
}

Test2.java content:

public class Test2 {

    public Boolean mBoolean;

    public void foo() {
        this.mBoolean = true;
    }
}

Generated bytecode of method foo()

# javap -c Test.class

...
  public void foo();
    Code:
       0: aload_0
       1: getstatic     #2                  // Field java/lang/Boolean.TRUE:Ljava/lang/Boolean;
       4: putfield      #3                  // Field mBoolean:Ljava/lang/Boolean;
       7: return

# javap -c Test2.class

...
  public void foo();
    Code:
       0: aload_0
       1: iconst_1
       2: invokestatic  #7                  // Method java/lang/Boolean.valueOf:(Z)Ljava/lang/Boolean;
       5: putfield      #13                 // Field mBoolean:Ljava/lang/Boolean;
       8: return

So apparently it actually calls Boolean.valueOf(true) when you assign the primitive value which results in a few more instructions. Keep in mind though that Boolean.valueOf returns either Boolean.TRUE or Boolean.FALSE no instance creation is done. The performance impact (in my opinion) is thus neglible and it can be argued for either case and may be a matter of style.

The JIT might optimize the call away anyways.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment