6

How many string objects will be created by the following code?

String s="";
s+=new String("a");
s+="b";

I had this question at exam. I want to know the right answer . I said 2 objects.
The object from pool that contains "" , "b" and the object created by new String("a");

Adi Botez
  • 61
  • 1
  • 3

4 Answers4

9

I'll anwser to another, clearer question: how many String instances are involved in the following code snippet:

String s="";
s+=new String("a");
s+="b";

And the answer is 6:

  • the empty String literal: "";
  • the String literal "a";
  • the copy of the String literal "a": new String("a");
  • the String created by concatenating s and the copy of "a";
  • the String literal "b"
  • the String created by concatenating s and "b".

If you assume that the three String literals have already been created by previously-loaded code, the code snippet thus creates 3 new String instances.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • String s1 = new String("hello"); , how many references are created at JVM level? I know of two objects:1 at the time of class loading for "hello" and 1 at the actual time of execution of command. 1 reference is s1, my doubt is there is also a 2nd reference s2 which is the result of "hello" string at class loading which is passed to the "new String()" constructor. In java, there is no way we can pass an object itself in a function or constructor, we can only pass a reference. Also, there should be a 3rd reference s3, which should be the result of new String("hello") and then got assigned to s1? – Bhavesh Agarwal Jan 16 '14 at 04:44
8

String s="";

creates no objects.

s+=new String("a");

creates five objects. the new String, the StringBuilder and its char[] and the String resulting and its char[]

s+="b";

creates four objects, the StringBuilder and its char[] and the String resulting and its char[]

So I get a total of nine objects of which are three String objects

Note: You can be sure that "" has already been loaded as it appear in many system classes including ClassLoader and Class.

The Strings "a" and "b" may or may not be considered as new Strings for the purpose of this question. IMHO I wouldn't count them as they will only be created at most once and if this code is only run once, it hardly matters how many strings are created. What is more likely to be useful is to know how many objects are created each time the code is run.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • The code doesn't compile (more specifically the following line `s+=new String("a");`). How did you even manage to count the number of objects created at runtime? – Darin Dimitrov Jun 24 '12 at 20:21
  • 6
    The question is about String instances. Not just objects. – JB Nizet Jun 24 '12 at 20:22
  • @DarinDimitrov My IDE and compiler says it compiles. What is supposed to be the problem? – Peter Lawrey Jun 24 '12 at 20:24
  • 2
    "" really creates no object? Then I wonder why `"".equals("")` is possible. – Pshemo Jun 24 '12 at 20:24
  • @Pshemo -- There is a single interned instance of "" for the entire JVM. In general, string literals are interned and don't "create" anything once the literals have been "primed" on first reference. – Hot Licks Jun 24 '12 at 20:26
  • 1
    @Pshemo The string literal already exists when the class loads, no more objects need to be created for `String s = "";` All it does is assign a reference from the string literal pool. You can be pretty confident that "" is already in the string literal pool before the class is loaded. – Peter Lawrey Jun 24 '12 at 20:26
  • 1
    Is there a way to profile java to show objects in memory? – Adel Boutros Jun 24 '12 at 20:27
  • How do you know that `""` is already in the string literal pool ? – Radu Murzea Jun 24 '12 at 20:27
  • Yes, you can use a profiler. ;) – Peter Lawrey Jun 24 '12 at 20:27
  • That's kind of nitpicking. The code doesn't create a String instance, but loading the code creates it, unless some already-loaded code has already caused its creation. The question is not as clear as it could be, but the answer isn't either, IMO. – JB Nizet Jun 24 '12 at 20:28
  • @PeterLawrey -- Technically, the first instance of a String literal must be created and interned, and that generally occurs on first reference, not class loading. – Hot Licks Jun 24 '12 at 20:28
  • 4
    @SoboLAN There are 2651 references to "" in the JDK, three are in ClassLoader and two in Class which you can be sure to be loaded first. – Peter Lawrey Jun 24 '12 at 20:30
  • Peter, that's the kind of answer that would hire you on the spot, and make the reviewers quietly stow away their exam materials to avoid further embarassment :) – Marko Topolnik Jun 24 '12 at 20:34
  • @MarkoTopolnik Depends on who is interviewing you. You can come across as someone who would be bored in the role they have in mind for you. ;) – Peter Lawrey Jun 24 '12 at 20:35
  • 1
    wait, the question is about STRING objects, so no char[]'s or StringBuilders please. – 11684 Jun 24 '12 at 20:38
  • @11684 That was JB Nizet's comment, second from the top. – Peter Lawrey Jun 25 '12 at 05:57
0

The number of objects actually created in a JITC situation is indeterminate. The JITC may well recognize that new String("a") is an identity, and that no intermediate values of s are referenced, so that only the StringBuilder is created. There are several potential side-effects that must be mimicked in the general case (eg, where the argument to new String() may be invalid), but with literals they can't occur.

In fact, javac could very well recognize that the result is "ab", with no potential side-effects, and just produce a String literal of that value. (It does string combining in slightly less complicated cases.)

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
0

Creating New Strings

Earlier we promised to talk more about the subtle differences between the various methods of creating a String. Let's look at a couple of examples of how a String might be created, and let's further assume that no other String objects exist in the pool:

String s = "abc"; // creates one String object and one reference variable

In this simple case, "abc" will go in the pool and s will refer to it.

String s = new String("abc"); // creates two objects, and one reference variable

In this case, because we used the new keyword, Java will create a new String object in normal (nonpool) memory, and s will refer to it. In addition, the literal "abc" will be placed in the pool.

From SCJP Sun Certified Programmer for Java 6 Study Guide (Exam 310-065).pdf

Community
  • 1
  • 1