Search code examples
javaequals-operator

Why does variables of class Test for two different objects gives true for == operation and same operation results in false for String Objects?


For == operation on variables of String for two different objects s and p created using new gives result as false (line 1) which I understand but why does line 3 and 4 ( line number commented ) gives true as Output?

I am aware of the fact that == is meant for reference comparison and that's where i have the doubt if it's meant for reference comparison then why line 4 gives true as j is an integer and there is no immutability concept as for String ( String s ) and everytime a new object has to be created ?

    class World
{
    public static void main(String[] args)
    {   
        String s=new String("B");
        String p=new String("B");
        System.out.println(s==p);                    //false    line 1
        Test t1= new Test("A",4);
        Test t2= new Test("A",4);
        System.out.println(t1==t2);                 //false     line 2
        System.out.println(t1.s==t2.s);             //true      line 3
        System.out.println(t1.j==t2.j);             //true      line 4
    }
}

class Test
{
    String s;
    int j;
    Test(String s, int j)
    {
    this.s=s;
    this.j=j;
    }
}

Solution

  • strings are normally cached in java, so two strings with the same value might have the same reference. (The same goes for Integers, there objects in a certain range are referenced as the same object, if they have the same value). This could lead to having the same object "A" as your value of s for t1 and t2 in the constructors. Two int primitives are always the same if they have the same value.