As separate Integer instances, I would expect these to return false under the == comparison. But they seem to return true when the values are within the range of a byte (-128 to 127) and autoboxing is used. If the values are outside the range of a byte or "new Integer(int)" is used, they return false.
Note: I see the same pattern autoboxing Long instances with long literals (for example, Long x = 127L). The unexpected results are still within the byte range.
[ February 05, 2005: Message edited by: marc weber ]
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
This behavior is mandated by JLS3 5.1.7. (Which is admittedly a beta and still subject to change - but assuming it doesn't...) Actually no guarantees are made for ints and shorts outside the range [-128, 127]; that's technically unspecified. But within that range, any two boxing conversions (in the same JVM at the same time) must result in the same wrapper instance. The implementation of this is visible in the source to Integer.valueOf() in JDK 1.5 - though this is not actually guaranteed in the API. Nothing says that boxing must use Integer.valueOf(), to my knowledge - but it looks like that is indeed the code that is used. [ February 05, 2005: Message edited by: Jim Yingst ]
Originally posted by rathi ji: ...Long i = 100; Long j = 100; i==j // ??? ...
I think Jim's post answers this question in general.
Joined: Oct 11, 2004
please put the answer ...
thanks a lot .
Joined: Jan 30, 2000
Why not run the code in your JDK to find out? You will need to fix a couple of compile errors of course, but that's good practice, right?
There doesn't seem to be any guarantee in JLS3 5.1.7 of the behavior in the case of long. However the current JDK seems to behave the same way for long that it does for int. Since this isn't guaranteed, I recommend not relying on this behavior. And it's not going to be on the test. (In contrast to the behavior for int within the range [-128, 127] which is guaranteed and therefore may be on the test.) [ February 07, 2005: Message edited by: Jim Yingst ]