This question already has an answer here:
What is the difference between
String str = new String("abc");
and
String str = "abc";
This question already has an answer here:
What is the difference between
String str = new String("abc");
and
String str = "abc";
When you use a string literal the string can be interned, but when you use
new String("...")
you get a new string object.In this example both string literals refer the same object:
Here, 2 different objects are created and they have different references:
In general, you should use the string literal notation when possible. It is easier to read and it gives the compiler a chance to optimize your code.
As Strings are immutable, when you do:
while creating the string, the JVM searches in the pool of strings if there already exists a string value
"xyz"
, if so'a'
will simply be a reference of that string and no new String object is created.But if you say:
you force JVM to create a new
String
reference, even if"xyz"
is in its pool.For more information read this.
Some disassembly is always interesting...
According to String class documentation they are equivalent.
Documentation for
String(String original)
also says that: Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.Look for other responses, because it seems that Java documentation is misleading :(
String is a class in Java different from other programming languages. So as for every class the object declaration and initialization is
or
Here,
st1
,st2
andst3
are different objects.That is:
Because
st1
,st2
,st3
are referencing 3 different objects, and==
checks for the equality in memory location, hence the result.But:
Here
.equals()
method checks for the content, and the content ofst1 = ""
,st2 = "hello"
andst3 = "hello"
. Hence the result.And in the case of the String declaration
Here,
intern()
method ofString
class is called, and checks if"hello"
is in intern pool, and if not, it is added to intern pool, and if "hello" exist in intern pool, thenst
will point to the memory of the existing"hello"
.So in case of:
Here:
Because
st3
andst4
pointing to same memory address.Also:
String s = new String("FFFF")
creates 2 objects:"FFFF"
string andString
object, which point to"FFFF"
string, so it is like pointer to pointer (reference to reference, I am not keen with terminology).It is said you should never use
new String("FFFF")