Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Learn › Java › Commonly used classes

== and equals

Why is == false when the values are the same?

Why it exists — If the equality of objects is judged only by whether they are the same object, as with ==, there is no way to treat as the same the same string or the same member number created at different times. equals is the method that lets a class decide for itself "what counts as the same," and standard classes such as String and Integer have already overridden it to compare by content.

Where it's used today — Use equals to compare values that are objects, such as a string or an id received as a Long, and use == for primitive values, enums, and when you really want to check whether it is the same object. To use a class you made yourself as a key of a HashMap or an element of a HashSet, override equals and hashCode together, and compare values that may be null with Objects.equals.

== compares whether two variables refer to the same object, and equals compares whether the contents are the same. Depending on how they are created, strings and Integer objects are sometimes reused and sometimes created anew, so the result of == can differ even when the values are the same.

Checked against real execution · Every combination was run on JDK 21 and checked against the result

Concepts in this lab

Identity and equality
Identity means that two references point to the same object in memory, and you compare it with the == operator. Equality means that two objects logically have the same value, and you compare it with the equals() method. If you use == to compare strings or value objects, the result can be false even when the contents are the same.
String pool
This is a storage area where the JVM keeps string literals and reuses the existing object when a literal with the same contents appears again. It saves memory because the same string is not created several times. This sharing is possible because String is immutable. Creating a string with new String("a") makes a new object that is separate from the pool.
Boxing and unboxing
Why it exists — Before automatic boxing existed, every time you put an int into a collection you had to create an object with new Integer(n), and every time you took it out you had to call intValue() yourself. Automatic boxing and unboxing have the compiler insert this conversion for you.
Where it's used today — It always happens when you put numbers into and take them out of a List<Integer> or a Map<String, Integer>. In calculations that add many numbers repeatedly, an int array or an IntStream is used to avoid the cost of boxing.
Boxing converts a primitive type (such as int) to a wrapper object (such as Integer), and unboxing is the reverse. Collections can take only objects (references to objects), so a primitive value that you add is boxed automatically. This has a cost for object creation and conversion, and unboxing a wrapper that is null throws a NullPointerException.
Immutable object
This is an object whose state does not change after it is created. Because its value never changes, it is safe for several threads to use at the same time, you can pass it to other code without worrying that it will be changed, and it is well suited for caching or for use as a key in a hash collection. Declare the fields private final, provide no methods that change the state, and make the class final so that a subclass cannot change its behavior. If a field refers to a mutable object (such as a List or a Date), the constructor and the getters pass copies in and out (defensive copying) so that outside code cannot change the internals.

Try these

Running with the default settings

  1. String a = "hello": Only one copy of a string literal is created, and it is kept in the string pool. a refers to the "hello" object in the pool.
  2. String b = new String("hello"): new always creates a new object. Its contents are the same as the "hello" in the pool, but it is a separate object at a different place on the heap.
  3. a == b: This compares whether the two variables refer to the same object. a refers to object 1 and b refers to object 2, so the result is false.
  4. a.equals(b): The equals method of String checks whether the two strings have the same characters in the same order. Both are hello, so the result is true.

Result of this run

Code

// Only the lines inside main are shown (class and main declaration omitted)
String a = "hello";
String b = new String("hello");

System.out.println(a == b);
System.out.println(a.equals(b));

Assumptions of this model

The == result of every combination was checked against the result of running the same code in our test run (JDK 21). The Integer cache range of -128 to 127 is the minimum range that the Java Language Specification guarantees, and the upper bound can be raised with a JVM option. The string pool has been located inside the heap since JDK 7, but the diagram shows it separately to set it apart.

Previous lab: Strategy pattern · Next lab: equals and hashCode

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these