can Any body explain me what is happeing in the output. If == is use to compare two ref. variable it simply check its reference if they are same then it enter in if body, then why the hell aa==bb is equal if creting static method valueOf() and ee==ff is not equal (which is ok) if creating its object using new keyword ?
static void main(String args[])
{
Integer aa = Integer.valueOf("12");
Integer bb = Integer.valueOf("12");
if(aa==bb)System.out.println("aa==bb");
if(aa!=bb)System.out.println("aa!=bb");
Integer ee = new Integer("12");
Integer ff = new Integer("12");
if(ee==ff)System.out.println("ee==ff");
if(ee!=ff)System.out.println("ee!=ff");
}
Output :
aa==bb
ee!=ff
Sometimes you must use wrapper classes, for example when working with Collection objects, such as ArrayList, where primitive types cannot be used (the list can only store objects): To create a wrapper object, use the wrapper class instead of the primitive type. To get the value, you can just print the object:
The table below shows the primitive type and the equivalent wrapper class: Sometimes you must use wrapper classes, for example when working with Collection objects, such as ArrayList, where primitive types cannot be used (the list can only store objects): To create a wrapper object, use the wrapper class instead of the primitive type.
While creating an object of the wrapper class, space is created in the memory where primitive data type is stored. Wrapper class provides some features for the conversion of the object to primitive data & primitive data to object, i.e. boxing/unboxing.
The list of eight wrapper classes are given below: The automatic conversion of primitive data type into its corresponding wrapper class is known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to Boolean, double to Double, and short to Short.
The ==
comparator checks for object equality!
Since Integer.valueOf
maintains a cache of Integer Objects with the value -128 to 127 valueOf(String)
returns the cached object, thus the ==
comparance results in true.
Integer a1 = new Integer("12");
Integer b1 = new Integer("12");
//a1 == b1 returns false because they point to two different Integer objects
Integer aa = Integer.valueOf("12");
Integer bb = Integer.valueOf("12");
//aa == bb returns true because they point to same cached object
For the comparance of object values always use the .equals
method, for primitives like int, long etc. you can use the ==
comparator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With