File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Wrapper Problem" Watch "Wrapper Problem" New topic
Author

Wrapper Problem

Micheal John
Ranch Hand

Joined: Nov 01, 2006
Posts: 344


I got the output as :
Not Equal
Equal

Why this difference? can anyone tell this?


Micheal John
SCJP 1.4 (86%), SCWCD 1.4 (86%), SCBCD 1.3 (85%), SCDJWS (Just Started...) - Satisfaction Lies in Our EFFORT, Not in the ATTAINMENT
Petrus Pelser
Ranch Hand

Joined: Feb 20, 2006
Posts: 132
Wrappers of the integral types will be equal (by using ==) when they are of the same type and the value is smaller than or equal to 127.
Satish Kota
Ranch Hand

Joined: Feb 08, 2006
Posts: 88
i1,i2 will point to same reference. Because JVM maintains a constant pool for wrapper objects just like it does for Strings. Hence i1 and i2 will point to the same reference in the constant pool. And i3,i4 will point to the same memory in the constant pool

so i1!=i2 will be False;
and i3==i4 will be True


SCJP 5.0 77%
Sanjeev Singh
Ranch Hand

Joined: Nov 01, 2006
Posts: 381
John,
The explantaion of this quesion is very well described in K&B book.
May be you can get some clue for this problem in this code.


~Sanjeev Singh<br />SCJP 1.5
Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9243
    
    1

Till 127, it returns true...and beyond that, false. One exception to this is, when you say Integer i1 = new Integer(10); and Integer i2 = new Integer(10); will point to 2 different objects.


SCJP 1.4, SCWCD 1.4 - Hints for you, SCBCD Hints - Demnachst, SCDJWS - Auch Demnachst
Did a rm -R / to find out that I lost my entire Linux installation!
Satish Kota
Ranch Hand

Joined: Feb 08, 2006
Posts: 88
Sanjeev,
That range of -128 to 127 is applicable to Byte, Short and Integer. Then what is the valid range for Long?
And also please let me know how did you get access to the code of Integer.valueOf() method ?
Satish Kota
Ranch Hand

Joined: Feb 08, 2006
Posts: 88
I just downloaded JDK 1.5 Source code from Sun site. When i peeped into the Byte, Short, Integer, Long source code the range was -128 to 127

For Character the range is for anything less than <=127

But for Float, Double no caching is provided.
That is

Float f1=3.0F;
Float f2=3.0F;
System.out.println(f1==f2);
will produce false
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Wrapper Problem
 
Similar Threads
KB 235
Boxing, == and equals
== and != for Wrapper Objects
Wrapper ==
Small doubt in Boxing & == & equals()