String s1 = "Amit"; //true
String s2 = "Amit"; //true
String s3 = new String("abcd"); //true
String s4 = new String("abcd"); //false
System.out.println(s1.equals(s2)); //true
System.out.println((s1==s2)); //true
System.out.println(s3.equals(s4)); //false
System.out.println((s3==s4)); //false
Assume it to be in main why the output of the above code is
true true true false and not true true false false???
Java uses a “string literal pool.” Since strings are immutable objects, there’s no reason two strings initialized to the same literal can’t be the same object—and as your code output suggests, they are the same object. (s1 and s2 are two names for the same location in memory)
The reason this isn’t true for s3 and s4 is because you’re explicitly allocating new strings, and using the constructor to initialize them. This means they are different objects, and hence they fail the “==” test.
In other words,
== compares if two object references are equal
.equals() compares if the contents of two objects are equal, irrespective of where they are in memory.