Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

how is this possible please explain  RSS feed

 
Ranch Hand
Posts: 110
Android Java Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Integer i1=1000;

Integer i2=1000;

if(i1!=i2) System.out.println("different objects");

if(i1.equals(i2)) System.out.println("meaningfully equal");


output

different objects //how is this possible please explain

meaningfully equal









b]Integer i3=10;

Integer i4=10;

if(i3==i4) System.out.println("same objects");

if(i3.equals(i4)) System.out.println("meaningfully equal");


output

same objects //how is this possible please explain

meaningfully equal


how if(i3==i4) and if(i1!=i2) both can be true
 
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is due to autoboxing. In your first example, the value being boxed is outside the range -128 to 127. In your second example, the value is within that range. As explained under JLS - 5.1.7 Boxing Conversion...

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

 
Shashank Agarwalg
Ranch Hand
Posts: 110
Android Java Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the solution.
 
Java Cowboy
Sheriff
Posts: 16083
88
Android IntelliJ IDE Java Scala Spring
 
My honeysuckle is blooming this year! Now to fertilize this tiny ad:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!