Translate

Tuesday, June 7, 2016

String with equals method and == operator.

What will be the output?


String s1="hello";

String s2="hello";

String s3=new String("hello");

line-1  System.out.print(s1==s2);  // o/p true


line-2  System.out.print(s1==s3);    // o/p false


line-3  System.out.print(s1.equals(s2));    // o/p true


line-4  System.out.print(s1.equals(s3));     // o/p true

Because when we create string object by string literal then string object will get created in String Constant Pool  and if there are we create two object of same content then both reference point to the same object that's why line-1 give o/p true.

If we create string object by new keyword then always a new object will get created and ==  operator only compare references that's why line-2 give o/p false.

If we talk about equals method of object class then equals method also compare only references but string class override the equals method and for string class equals method compare the content of objects that's why line-3 & line-4 give o/p true.



No comments:

Post a Comment