Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Comparison Of two Integer using == sometimes works and sometimes not? [duplicate]

I know that i am comparing reference while i'm using == which is not a good idea but i did not understand why is this happening.

Integer a=100;
Integer b=100;
Integer c=500;
Integer d=500;
System.out.println(a == b); //true
System.out.println(a.equals(b)); //true
System.out.println(c == d); //false
System.out.println(c.equals(d)); //true
like image 337
Hiren Avatar asked Dec 06 '25 16:12

Hiren


1 Answers

The Java Language Specification says that the wrapper objects for at least -128 to 127 are cached and reused by Integer.valueOf(), which is implicitly used by the autoboxing.

like image 161
chrylis -cautiouslyoptimistic- Avatar answered Dec 09 '25 19:12

chrylis -cautiouslyoptimistic-



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!