I know that if you compare a boxed primitive Integer with a constant such as:
Integer a = 4;
if (a < 5)
a
will automaticall
We should always go for equals() method for comparison for two integers.Its the recommended practice.
If we compare two integers using == that would work for certain range of integer values (Integer from -128 to 127) due to JVM's internal optimisation.
Please see examples:
Case 1:
Integer a = 100; Integer b = 100;
if (a == b) { System.out.println("a and b are equal"); } else { System.out.println("a and b are not equal"); }
In above case JVM uses value of a and b from cached pool and return the same object instance(therefore memory address) of integer object and we get both are equal.Its an optimisation JVM does for certain range values.
Case 2: In this case, a and b are not equal because it does not come with the range from -128 to 127.
Integer a = 220; Integer b = 220;
if (a == b) { System.out.println("a and b are equal"); } else { System.out.println("a and b are not equal"); }
Proper way:
Integer a = 200;
Integer b = 200;
System.out.println("a == b? " + a.equals(b)); // true
I hope this helps.