Why to Avoid Comparing Integer using == in Java 5?

In Java auto-boxing is very interested feature which automatically covert int to Integer, long to Long, float to Float etc. This feature introduced was introduced in the JAVA 5. Any developer want to compare the int to int or int to Integer or Integer to Integer, they mostly use == operator. But this operator == might be cause of many subtle bugs in your application because it works only for some defined range of integers. In some cases this operator == might be cause of NullPointerException due to whenever we will compare int to Integer, the Integer object is converted to a primitive value, if the Integer object is null, it throws NullPointerException. So when you compare two Integer objects using a == operator, Java doesn’t compare them by value, but it does reference comparison that means even if the two integer has the same value, == can return false because they are two different objects in the heap. That’s why you should use equals() method to compare objects.

This is one of very weird java question that will make your head spin. Java does it by caching of integer objects by Integer.valueOf() method. That mean your code might be work some range of integers but not for others. So what is this range of integers, Integer object for range -128 to 127, it return same Integer object in heap, and that’s why == operator return true if you compare two Integer object in the range -128 to 127, but return false afterwards, causing bug. This happens because auto boxing uses Integer.valueOf() method to convert Integer to int and since method caches.

There is no such problem if you using pre or Java 1.4 version because there was no auto boxing, so you always knew that == will check reference in heap instead of value comparison.

Example
Let’s see below line of code about this problem.

public class Main {
 public static void main(String[] args) {
  
  Integer c = 666;
  Integer d = 666;
  System.out.println("c == d "+ (c == d));
  Integer a = 42;
  Integer b = 42;
  System.out.println("a == b "+ (a == b));;
  
 }
}

Output
c == d false
a == b true

According to the output of above program c and d have value 666 but == operator return false and a and b also have same value 42 but here == operator return true.

In first case the literal 666 is boxed into two different Integer objects and then those objects are compared with ==. The result is false, as the two objects are different instances, with different memory addresses. Because both sides of the == expression contain objects, no unboxing occurs.

In the second case int values from -127 to 127 are in a range which most JVM will like to cache so the VM actually uses the same object instance for both a and b. As a result, == returns a true result.

Summary

So we have to avoid when comparing two integer objects by == operator. We can equal() method to compare the integer objects. The equal() method always compare the value of integer objects instead of comparing its references.

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago