This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
Integer i = new Integer(1); Integer i1 = new Integer("1"); System.out.println(i.equals(i1)); // true System.out.println(i==i1); // false
Why first one is giving true ... as i know that equals() method check if both object are equal or not . so one is string object & one is integer object . one is on string constant pool & one is on integer constant pool ( i am not sure in this , may be GCH ) ... so how can both equal ... please help ...
If you look in the javadocs Integer(String) can throw a NumberFormatException. This is because that constructor attempts to parse an Integer from the String. In the code you are compairing two integers with the same value of 1 so they are equal(). But they do not reference the same Object so they are not ==.
The equals() methods is overridden in all wrapper classes to compare value equality instead of reference equality.
Integer i = new Integer(1); Integer i1 = new Integer("1");
The Integer class wraps the value of primitive int in an object regardless of which constructor you have used. Whether you pass '1' as an int or String to the constructor the final stored value in the wrapper class will be the primitive '1'.
Note: if you use the constructor that accepts String as a parameter to pass a value, then the compiler implicitly performs Integer.parseInt() on the passed parameter and raises java.lang.NumberFormatException if it was not able to convert the String value to primitive '1'.
- Do not try and bend the spoon. That's impossible. Instead, only try to realize the truth. - What truth? - That there is no spoon!!!
Joined: Jul 21, 2003
One more thing, equals() method always returns false if you compare the equality of two different wrapper classes (ie. Integer and Long) even if they are holding the same value.
Here is Sun's implementation of the equals() method in the Integer class.
Joined: Oct 11, 2004
Thanks Vicken & all , thank you vary much .
Joined: Oct 11, 2004
Integer i1 = new Integer('2'); Integer i2 = new Integer("2"); System.out.println(i1.equals(i2));
why this code is giving false ... please help ... thanks a lot .
Originally posted by rathi ji: Integer i1 = new Integer('2'); Integer i2 = new Integer("2"); System.out.println(i1.equals(i2));
why this code is giving false ... please help ... thanks a lot .[/QUOTE
Only values that can be passed to Integer is a primitive int,long,short,byte. If you pass char then also i doesnt throw any error rather the output will be a different number.So the output of i1=50 If you pass a String then parseInteger()is invoked and output is a primitive with same value.and output of i2=2. Henceforth equal method returns false.