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 ==.
A good rule is that every time you use new, you get a unique new object that will not == any other object.
Note that while two String.equals() and Integer.equals() check for same actual classes and values, StringBuffer inherits Object.equals() and checks for identical objects.
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'.
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.
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.
Post by:autobot
Every time you till, you lose 30% of your organic matter. But this tiny ad is durable:
a bit of art, as a gift, the permaculture playing cards