3

I'm doing a few mock test for my Oracle Certified Java Programmer certification. One of the question I found in a test is this one:

public String makinStrings() { 
 String s = “Fred”; 
 s = s + “47”; 
 s = s.substring(2, 5); 
 s = s.toUpperCase(); 
 return s.toString();
}

And the question is "How many String objects will be created when this method is invoked?". I'm counting 5: "Fred", "47", "Fred47", the substring "ed4" and the uppercased string "ED4", but the question answer is 3 objects (and the document where the test is doesn't have an explanation section). Can you point where is my error?

1
  • Look at String literal constants and interning. Commented Nov 22, 2011 at 16:00

3 Answers 3

4

Sounds like the error is in the interpretation of "how many strings objects will be created when this method is invoked"

You are correct in stating that five strings are involved; however, Strings are immutable, and two of those are constants that are compiled into the class containing the makinStrings() method. As such, two of your five pre-exist the call of the method, and only three "new" strings are created.

The two constant strings exist in the class's constant pool, and were constructed at class load time.

Sign up to request clarification or add additional context in comments.

Comments

4

The string "Fred" and "47" are static, ie they're created when the class is loaded, not when the method is invoked.

Comments

1

Best I can see:

public String makinStrings() { 
 String s = “Fred”; 

"Fred" is a string literal created and added to the String pool at class load time. No object is created when it is assigned; the assignment just passes a reference to an existing String.

 s = s + “47”; 

Here, a new String is created as the combination of the previous value of s and the literal "47". (1)

 s = s.substring(2, 5);

substring() does not operate on the String itself (Strings are immutable in Java), rather, it returns a new String that is the method return value. (2)

 s = s.toUpperCase();

New string, for the same reason as the previous line. (3)

  return s.toString();
}

toString() in the String class returns a reference to the String itself. No new object is created.

So 3 sounds like the correct answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.