main(){
Integer i1 = 500;
Integer i2 = 500;
System.out.println(i1 == i2); // O/P is "**false**"
String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1 == s2); // O/P is "**true**"
} // End of main.
I am not able to figure out why the output is different. As far as I know s1, s2 will point to the same object on the heap. So their reference address are same. Similarly I think Integer is also the same. But it is not. Why is it different?
It has been already answered here: java: Integer equals vs. ==
Taken from this post: The JVM is caching Integer values. == only works for numbers between -128 and 127. So it doesn’t work with 500 in your example.