This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Wrapper problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Wrapper problem" Watch "Wrapper problem" New topic
Author

Wrapper problem

Bob CHOI
Ranch Hand

Joined: Nov 10, 2006
Posts: 127
My code below,



it prints out:

false

Are wrapper classes immutable? Do they use constants pool? Why is the result not true!???


Hard work rewards
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

First, == compares values. For objects, this means references. So if A and B reference different objects, then (A == B) will return false, regardless of how A and B might relate using the equals method.

Second, the code above uses boxing to wrap int values as Integer objects, and this introduces some interesting behavior. According to the JLS (5.1.7)...
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.

In this case, 0xFEDC is a hexadecimal representation of 65244, so it is not between -128 and 127. Therefore, there is no guarantee that i1 and i2 will point to the same wrapped instance.


"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
Bob CHOI
Ranch Hand

Joined: Nov 10, 2006
Posts: 127
Marc, thanks for the reference to JLS.

i'm wonderring why? if both reference variables, namely i1&i2, point to the same constant object, namely oxFEDC, they should have been equal, i mean "=="


In this case, 0xFEDC is a hexadecimal representation of 65244, so it is not between -128 and 127. Therefore, there is no guarantee that i1 and i2 will point to the same wrapped instance.


sorry, i got it above now, thanks again
[ December 14, 2006: Message edited by: Bob CHOI ]
Bob CHOI
Ranch Hand

Joined: Nov 10, 2006
Posts: 127
modified code below:

class Test011 {

public static void main(String[] args) {

Integer i1 = 0xFEDC;
Integer i2 = 0xFEDC;
System.out.println(i1==0xFEDC);

}

}




it prints out:

true

The reason has to be not 0xFEDC boxed to Integer constant but i1 unboxed to int, hasn't it?
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Bob CHOI:
...i1 unboxed to int, hasn't it?

Yes. (See 15.21.1.)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Wrapper problem