Java
Integer
equals
comparison
programming

Java Integer equals vs.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Java: Integer equals vs. ==

In Java, comparing Integer objects involves intricacies that can trip up even seasoned developers. The crux of the confusion lies in the difference between the equals() method and the == operator, both of which are used for comparison. Understanding these operations in detail, with specific attention to the JVM internals and object identity, ensures robust and bug-free code.

Technical Explanation

In Java, the Integer class, a subclass of Number, is part of the java.lang package and is used to wrap the primitive type int in an object. Being an immutable object, it represents an int value but as an Object. This setup leads to two distinct methods of comparison: using the equals() method and the == operator.

The equals() Method

The equals(Object obj) method in Integer is overridden from the Object class. This method is used to compare the values within two Integer objects. It checks whether two objects are logically "equal", as it compares the actual contents (or the values) of the objects. Here's how it works technically:

java
1Integer num1 = new Integer(100);
2Integer num2 = new Integer(100);
3
4System.out.println(num1.equals(num2)); // Output: true

In the above example, the equals() method returns true because the values within num1 and num2 are the same.

The == Operator

The == operator, on the other hand, is used to determine if two references point to the same object in memory – it checks for reference equality, not value equality:

java
1Integer num1 = new Integer(100);
2Integer num2 = new Integer(100);
3
4System.out.println(num1 == num2); // Output: false

Here, num1 and num2 point to different objects, so the == operator returns false.

Integer Caching

Java provides an optimization technique known as integer caching. For values in the range of -128 to 127, the JVM caches Integer objects, meaning that Integer objects created with values in this range point to the same memory object:

java
1Integer num1 = 100; // Autoboxing invokes Integer.valueOf(100)
2Integer num2 = 100; // Uses cached object
3
4System.out.println(num1 == num2); // Output: true

The output is true because num1 and num2 reference the same cached object from the Integer cache pool.

Differences Between equals() and ==

Comparison Typeequals() Method== Operator
FunctionalityCompares values within the objectsCompares object references
Comparison ResultLogical equalityReference equality
OutcomeTrue if values are equalTrue if both references point to the same object
Example (100)new Integer(100).equals(new Integer(100)) Outputs: truenew Integer(100) == new Integer(100) Outputs: false
Example (Caching)Integer.valueOf(100).equals(Integer.valueOf(100)) Outputs: trueInteger.valueOf(100) == Integer.valueOf(100) Outputs: true due to caching

Autoboxing and Unboxing

The concept of autoboxing and unboxing further compounds the complexity in comparing Integer objects. Java automatically converts between primitive types and their corresponding wrapper classes, a feature known as autoboxing (converting int to Integer) and unboxing (converting Integer to int).

java
1Integer num1 = 100;   // Autoboxing
2int num2 = num1;      // Unboxing
3
4if (num1 == num2) {   // True due to unboxing
5    System.out.println("Equal");
6}

Here, the Integer object num1 is automatically converted to the primitive int before being compared to num2, leading to integer value comparison.

Best Practices

  1. Use equals() for value comparison: Always use the equals() method for comparing two Integer objects if the intent is to compare the values within those objects.
  2. Be cautious with == when dealing with objects: Remember that == checks for reference equality. Use it only if you need to confirm that two references point to the exact same object.
  3. Consider integer caching: Take advantage of the caching for integer values between -128 and 127 for performance optimizations.
  4. Understand autoboxing behavior: Be mindful of Java's autoboxing and unboxing behavior to avoid unintended comparison results.
  5. Use primitives when possible: If object overhead and nullability are not needed, consider using primitive int, which avoids the complexity of object comparison.

By understanding and applying these concepts, you can prevent subtle bugs and ensure clear and efficient comparisons in Java applications. The key lies in choosing the right comparison technique based on the context of your application logic.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.