Up to two. The literal "hello" is placed in the string pool when the class is loaded (only if the pool doesn't already contain it), and new String(...) always creates one more String object on the heap. So it is two the first time, and one if "hello" was already in the pool.
Key Points: • The literal object is created once per JVM (per distinct text), not every time the line runs. • new always creates a new object, so s != "hello" when compared with ==. • Since Java 7u6, the new String shares the same internal character array with the literal, so the extra cost is one small object. • There is almost never a reason to write new String("literal"). Use the literal directly. • A follow-up question is often: how many objects does String s = "a" + "b" + "c"; create? The answer is one, because the compiler folds constants into "abc".
Code Example:
public class HowManyObjects {
public static void main(String[] args) {
String s1 = new String("hello"); // pool "hello" (if new) + heap object
String s2 = new String("hello"); // only one more heap object
String s3 = "hello"; // reuses the pooled literal
System.out.println("s1 == s2: " + (s1 == s2));
System.out.println("s1 == s3: " + (s1 == s3));
System.out.println("s1.intern() == s3: " + (s1.intern() == s3));
String folded = "a" + "b" + "c"; // compile-time constant: one object
System.out.println("folded == \"abc\": " + (folded == "abc"));
String x = "a";
String runtime = x + "b" + "c"; // built at runtime: a new object
System.out.println("runtime == \"abc\": " + (runtime == "abc"));
}
}Output:
s1 == s2: false s1 == s3: false s1.intern() == s3: true folded == "abc": true runtime == "abc": false
Good to Know: The exact count depends on whether the literal was already loaded into the pool by another class or an earlier line. That's why the precise answer is "one or two", and explaining why is what the interviewer is really looking for.
Interview Tip: A concise interview answer is:
"At most two: the literal 'hello' goes into the string pool if it isn't there already, and new String always creates a separate object on the heap. So it's two objects the first time and one if the literal was already pooled, and s won't be == to the literal. In practice I never write new String with a literal."
Next question: What does String.intern() do, and when should you use it?