We normally create objects using the new keyword, like:
Object obj = new Object();
Strings are objects, yet we do not use new to create them:
String str = "Hello World";
Why is this? Can I make a String with new?
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.
In addition to what was already said, String literals [ie, Strings like
"abcd"but not likenew String("abcd")] in Java are interned – this means that every time you refer to “abcd”, you get a reference to a singleStringinstance, rather than a new one each time. So you will have:but if you had
then it’s possible to have
(and in case anyone needs reminding, always use
.equals()to compare Strings;==tests for physical equality).Interning String literals is good because they are often used more than once. For example, consider the (contrived) code:
If we didn’t have interning of Strings, “Next iteration” would need to be instantiated 10 times, whereas now it will only be instantiated once.