== compares references
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)On objects, == does not look at the data inside. It asks one question: do these two references point to the very same object?
== on objects asks: the same object?
Reference equality means two references point to the very same object in memory. For objects, the == operator checks reference equality (also called identity) and never compares the fields; for primitives such as int, == compares the values.
A variable such as Student a holds a reference, as in Objects: instances of a class (opens in a new tab). Each new makes a separate object, so two new Student("Aarav", 91) calls give two objects, even with the same data.
Example 1 · Same data, still not ==
class Student { String name; int marks;
Student(String name, int marks) { this.name = name; this.marks = marks; }}
public class SameDataDemo { public static void main(String[] args) { Student a = new Student("Aarav", 91); Student b = new Student("Aarav", 91); Student c = a;
System.out.println("a == b: " + (a == b)); System.out.println("a == c: " + (a == c)); System.out.println("a != b: " + (a != b)); }}a == b: false a == c: true a != b: true
What this code does
aandbcome from twonewcalls, so they are two objects; the matching data does not matter to==.c = acopies the reference, soaandcpoint to one object anda == cistrue.
c = a copies the reference, not the object, so a change made through c shows through a; Many objects, references and null (opens in a new tab) traces this. For int, double and the other primitives, == still compares values: 5 == 5 is true.
Predict the output
Same object or not?
Read the code and pick what it prints.
Round 1 of 3
Three Box variables, two objects.
Identity vs logical equality
Logical equality means two objects hold the same meaningful value, even when they are different objects. It is checked with equals(), but only after the class overrides equals() to compare its data; Object's own equals() just uses ==.
Two Rs. 500 notes have different serial numbers, yet they are worth the same. Two Student objects with roll 12 are two objects, yet they may describe one student.
Example 2 · The default equals() is no better
class Student { String name; int roll;
Student(String name, int roll) { this.name = name; this.roll = roll; }}
public class LogicalDemo { public static void main(String[] args) { Student a = new Student("Kavya", 12); Student b = new Student("Kavya", 12);
System.out.println("a == b: " + (a == b)); System.out.println("a.equals(b): " + a.equals(b)); System.out.println("same roll: " + (a.roll == b.roll)); }}a == b: false a.equals(b): false same roll: true
What this code does
aandbare two objects, soa == bisfalse.Studentdoes not overrideequals(), so the inherited version isthis == objand also saysfalse.- Only comparing the data, here
a.roll == b.roll, shows they describe the same student. That is logical equality.
Java cannot guess which fields make two objects "the same", so Object's equals() is simply this == obj. You define logical equality yourself by overriding equals(), which Write your own equals() (opens in a new tab) covers.
Strings and arrays follow the same rule
Strings and arrays are objects too. You met the String case in Compare Strings (opens in a new tab): text from Scanner, new String or + with a variable is a new object, so == fails.
Example 3 · Strings: == can fool you
public class StringEqualsDemo { public static void main(String[] args) { String s1 = "Rohan"; String s2 = "Rohan"; String s3 = new String("Rohan"); String part = "Ro"; String s4 = part + "han"; String s5 = "Ro" + "han";
System.out.println(s1 == s2); System.out.println(s1 == s3); System.out.println(s1 == s4); System.out.println(s1 == s5); System.out.println(s1.equals(s3) + " " + s1.equals(s4)); }}true false false true true true
What this code does
s1ands2are the same literal, reused from the string pool, so==istrueby luck.s3ands4are new objects made at run time (s4joins a variable), so==isfalse.s5joins two literals, so the compiler makes it"Rohan"and it comes from the pool.equals()compares the letters, so it istrueevery time. That is why Strings are always compared withequals().
Example 4 · Arrays and null
import java.util.Arrays;
public class ArrayNullDemo { public static void main(String[] args) { int[] x = {90, 85, 70}; int[] y = {90, 85, 70}; System.out.println(x == y); System.out.println(x.equals(y)); System.out.println(Arrays.equals(x, y));
String topper = null; System.out.println(topper == null); }}false false true true
What this code does
- Two arrays are two objects. Their
equals()is==, so onlyArrays.equalscompares the numbers inside. topper == nullis the correct, safe way to check fornull.
Arrays keep Object's equals(), so x.equals(y) is just ==; Arrays.equals(x, y) from The Arrays utility class (opens in a new tab) compares the contents. For Strings, always use equals().
When == is the right choice
A search with == misses an equal student, because the student you look for is a new object. Use == on objects only when identity really is the question.
Example 5 · Mistake: searching with ==
class Student { String name; int marks;
Student(String name, int marks) { this.name = name; this.marks = marks; }}
public class SearchBugDemo { public static void main(String[] args) { Student[] cls = { new Student("Kavya", 88), new Student("Diya", 76) }; Student wanted = new Student("Diya", 76);
boolean byEq = false; boolean byEquals = false; for (int i = 0; i < cls.length; i++) { if (cls[i] == wanted) { byEq = true; } if (cls[i].equals(wanted)) { byEquals = true; } } System.out.println("found with ==: " + byEq); System.out.println("found with equals: " + byEquals); }}found with ==: false found with equals: false
What this code does
wantedis a new object, so it is never==to an object inside the array, even with the same name and marks.Studentdoes not overrideequals(), so the inherited version is just==and fails too. The next lesson fixes this.
The right uses of == on references:
nullchecks:if (s == null). Nevers.equals(null): whensisnull, that call crashes.- Same-object checks, such as the quick
this == objat the start ofequals(). - Enum constants,
day == Day.MONDAY: each constant is one object, as in Why enums? (opens in a new tab).
== checks identity. For data, use equals(), once your class overrides it.Next step
Check your understanding
12 quick questions