Please see the below code
class TestToString
{
public static void main(String args[])
{
CheckToString cs = new CheckToString (2);
CheckToString c = new CheckToString (2);
if( cs.equals(c))
System.out.println(" Both objects are equal");
else
System.out.println(" Unequal objects ");
}
}
class CheckToString
{
int i;
CheckToString ()
{
i=10;
}
CheckToString (int a)
{
this.i=a;
}
}
Output: Unequal objects
But I was expecting the output will be
Both objects are equal
I understood that both the objects have different refferences,
System.out.println(cs); //com.sample.personal.checkToString@19821f
System.out.println(c); //com.sample.personal.checkToString@addbf1
but I was asking, why do they have different referrences? whereas in the below case, the objects have same memory locations.
Integer a = new Integer(2);
Integer b = new Integer(2);
System.out.println(a); //2
System.out.println(b); //2
I am comparing the object of user-defined class with the object of pre-defined class. It seems the object of user-defined class behaves same as the object of Integer Class having value beyond -128 to 127. Why are the referrences different for both the cases? (same for Integer class having value within -128 to 127 and different for user-defined class)