| Author |
"==" on Wrapper Class
|
Sowjanya Chowdary
Greenhorn
Joined: Apr 06, 2007
Posts: 2
|
|
The concept is clear that, if two Integer objects has the same value, in the range of -128 to 127, they both refer to the same object. For Example: class Wrapper { public static void main(String[] args) { Integer i1=10; Integer i2=10; System.out.println(i1==i2);// prints true } } But please explain why the following code behaviour changes like this. class Wrapper { public static void main(String[] args) { Integer i1=new Integer(10); Integer i2=10; System.out.println(i1==i2);//Why does this prints false ? //i1=10; System.out.println(i1==i2); // when this line uncommented, why it prints true? } } Please explain, I think i am missing some logic here.
|
 |
Chandra Bhatt
Ranch Hand
Joined: Feb 28, 2007
Posts: 1707
|
|
Case #1 1- i1 is assigned a reference to the Object created using "new" operator. 2- primitive 10 is autoboxed and Integer object is referenced to the ref variable i2 So you are comparing two different references and hence result false. Case #2
//i1=10; System.out.println(i1==i2); // when this line uncommented, why it prints true?
You did the same what you talk about very first, (for some range of values the autoboxed ref will yield the value true) i1=10; i2=20; (i1==i2); //true Thanks,
|
cmbhatt
|
 |
Sowjanya Chowdary
Greenhorn
Joined: Apr 06, 2007
Posts: 2
|
|
Changed name according to naming policy. Thank you.
|
 |
Sasha Ruehmkorf
Ranch Hand
Joined: Mar 29, 2007
Posts: 115
|
|
To make it clear:
if two Integer objects has the same value, in the range of -128 to 127, they both refer to the same object.
is not always correct. It is correct for Integer-Objects that were created using auto-boxing, but not for Integers created with the new-Operator
|
 |
 |
|
|
subject: "==" on Wrapper Class
|
|
|