What is the difference between these two following statements?
String s = "text";
String s = new String("text");
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
new String("text");explicitly creates a new and referentially distinct instance of a
Stringobject;String s = "text";may reuse an instance from the string constant pool if one is available.You very rarely would ever want to use the
new String(anotherString)constructor. From the API:Related questions
What referential distinction means
Examine the following snippet:
==on two reference types is a reference identity comparison. Two objects that areequalsare not necessarily==. It is usually wrong to use==on reference types; most of the timeequalsneed to be used instead.Nonetheless, if for whatever reason you need to create two
equalsbut not==string, you can use thenew String(anotherString)constructor. It needs to be said again, however, that this is very peculiar, and is rarely the intention.References
class Object–boolean Object(equals)Related issues