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
?
Answer
In addition to what was already said, String literals [ie, Strings like "abcd"
but not like new String("abcd")
] in Java are interned - this means that every time you refer to "abcd", you get a reference to a single String
instance, rather than a new one each time. So you will have:
String a = "abcd";
String b = "abcd";
a == b; //True
but if you had
String a = new String("abcd");
String b = new String("abcd");
then it's possible to have
a == b; // False
(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:
for (int i = 0; i < 10; i++) {
System.out.println("Next iteration");
}
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.
No comments:
Post a Comment