This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Originally posted by Ismael Upright: Consider the following code:
This actually compiles and prints "true". For me it seems like code that should not compile..
What actually happend there?
In the above code, the comparison is done using the operand == instead of using equals() method. This means that the unboxing of Integer to int will be done in such a way it is possible to do a == comparison between short and int.
short s =9; Integer i =9; System.out.println(s==i);// which returns true as both are having a value of 9
In order to save memory, two instances of the following wrapper objects will always be == when their primitive values are the same: Boolean Byte Character from \u0000 to \u007f (7f is 127 in decimal) Short and Integer from -128 to 127
Integer i1constr_a = new Integer(7); Integer i1constr_b = new Integer(7);
Two objects are created, so both fail == operation.
Joined: May 07, 2008
agilemanoj kumar was faster than me ;-)
String a1_a = "a"; String a1_b = "a";
String a2_a = new String("a"); String a2_b = new String("a");
The compiler choses to unbox first because if it were to box the short into Short, it won't be able to compare the two references, as neither is a subclass of the other (you can't say if(myString == myInteger)).
Joined: Feb 15, 2007
Going back to my problem here
Was it like this?
1. Integer got unboxed to int 2. short was promoted to int 3. Two ints were compared by == 4. true was returned
Joined: Aug 06, 2007
Why this false ??. both are having saem values,as you said that wrapper class saves the memory if wrapper objects have same primitive value, which in this is 128 for both i2_a and i2_b..
The method valueOf(...) of class Integer has a caching mechanism. If the value you put into it is between -128 and +127, it will return a pre-made Integer object from the cache. If the value is outside that range, it will create a new Integer object initialized with the given value.
In the case of i2_a and i2_b, the value is outside the range, so i2_a and i2_b will refer to two new, different Integer objects.
As you know, if you use == on reference variables, it will only compare the references - you'll only get 'true' if the two variables refer to the exact same object. In this case, they don't - there are two separate Integer objects - so the result is 'false'.