StringLiteralNoObject
To get a String
object with a given value (e.g., "Hello"
),
one needs to use the String
constructor, like so: new String("Hello")
.
One needs to call the String constructor to get a String object from a literal
A String literal represents a String object and can be treated as such
CorrectionHere is what's right.
All the following three statements are correct.
String s1 = "Hello";
String s2 = new String("Hello");
String s3 = new String(new String("Hello"));
However, the second statement uses "Hello"
,
which already refers to a String
object,
as an argument to the String(String original)
constructor,
which copies the passed in String
.
Thus, it unnecessarily creates a copy of the original String
literal.
The third statement is even worse:
it creates a copy of "Hello"
,
and then it creates a copy of that copy.
That’s two unnecessary object allocations.
SymptomsHow do you know your students might have this misconception?
Novice students may write code like this:
public class Contact {
private String name = new String("Duke"); // unnecessary wrapping
private Address address = new Address("1 Java Way");
//...
}