-1

In Java Boolean.TRUE method has following implementation

 /**
 * The {@code Boolean} object corresponding to the primitive
 * value {@code true}.
 */
public static final Boolean TRUE = new Boolean(true);

and now:

System.out.println(new Boolean(true) == new Boolean(true));
System.out.println(Boolean.TRUE == Boolean.TRUE);

prints:

false
true

WHY ?!

user109447
  • 1,069
  • 1
  • 10
  • 20

1 Answers1

2

Boolean.TRUE is not a method but a member variable declaration.

public static final Boolean TRUE = new Boolean(true);

Whenever you use new operator it creates a new instance and operator == compares instance references and not their content (equals compares contents) which means below is comparing two different instance references and not their contents, hence its false.

new Boolean(true) == new Boolean(true)

As Boolean.TRUE is static for Boolean wrapper class, below means you are comparing same static variable (not their content but actual instance reference), hence its true.

Boolean.TRUE == Boolean.TRUE
JRG
  • 4,037
  • 3
  • 23
  • 34