• Post Reply Bookmark Topic Watch Topic
  • New Topic

Primitive Wrapper class  RSS feed

 
prateek shaw
Ranch Hand
Posts: 46
1
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All

why below code is not returning true.



And below code is returning  true.



I have read that it will be only return true if it value is between -128 to 127. I just try to compare with string behavior.
I can think that wrapper class can have more object than string therefore java cannot able to manage all the wrapper object, therefore they have this limit.

Is my understanding correct ?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16059
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, you have to understand that autoboxing is happening here. This means that the compiler automatically translates this:

into this:

Next, the behaviour you see comes from the way that the method Integer.valueOf(...) is implemented. It has a cache of Integer objects, for all values between -128 and 127. If you pass it a number that's in this range, the method returns the matching Integer object from its internal cache. Otherwise, it just creates a new Integer object with the value that you passed.

The == operator compares references when used with non-primitive types; in other words, if checks if two variables refer to the exact same object.

If you have two variables that point to the same Integer object because it came out of the internal cache, then i == j will return true. If you have to variables that refer to two different objects (even though they hold the same value), then the result will be false.
 
prateek shaw
Ranch Hand
Posts: 46
1
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your reply. I knew that auto boxing is done here. But i was not aware of that it will call valueof method. but now it make sense.
And i do found below explanation.

Returns an Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range
.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!