Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Wrapper Problem

 
Micheal John
Ranch Hand
Posts: 344
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I got the output as :
Not Equal
Equal

Why this difference? can anyone tell this?
 
Petrus Pelser
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Sanjeev Singh
Ranch Hand
Posts: 381
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Joe Harry
Ranch Hand
Posts: 10091
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Satish Kota
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic