does both of these create different String object
There are two aspects here. First one is interning of String literals. Out of these two statements:
String s1 = "Hello";
String s2 = new String("Hello");
First one will use the literal string "Hello"
that is already in the constant pool. If it isn't there, it will create an entry in the constant pool for "Hello"
(In which case you can say that, an object is created)
In 2nd case, you have 2 string objects - first one is the string literal "Hello"
, which will be interned from the constant pool, and then the 2nd object creation is due to the use of new
keyword - new String(...)
will certainly create a new object. So:
s1 == s2; // This will return `false`
because, s1 and s2 are reference to 2 different String objects.
Now comes your 2nd case:
String s1 = "Hello";
StringBuffer sb = new StringBuffer("Hello");
In 2nd statement, you are creating a new StringBuffer
object. Well, firstly a StringBuffer
is not a String
. Secondly, since StringBuffer
class does not override equals()
method, so when you invoke equals
method like this:
sb.equals(s1);
it will invoke the Object#equals()
method, which does comparison based on the value of reference. So, it will return false, since sb
and s1
are pointing to 2 different instance.
However, if you compare them like this:
sb.toString().equals(s1);
then you will get true now. Since String
class has overridden the equals()
method, which does the comparison based on the contents.
See also: