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.
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…