0

Below is a Java program.

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

How can I find out how many String object is created in the String pool. I think there are 4 objects created which are - "Fred" , "Fred47" , "ed4" , "ED4". Is this correct assumption?

2

1 Answer 1

1

For the Java version 7:

  • Due to this topic the + operator creates new object
  • Due to String reference and this topic:
    • substring() creates a new string because String is immutable
    • toUpperCase() creates a new string because String is immutable
    • toString() does not create a new string but returning him itself

Assigning the "Fred" at the beginning won't create a new object since it will be taken from literal pool

To sum up - 3 Strings has been created with every method call. The string is an object so returning it does not create new - it is done by reference.

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

2 Comments

Why do you think toUpperCase() doesn't create a new string?
Of course it will - I've been suggested with no explicit information in the reference what was acually wrong. The question is a duplicate of stackoverflow.com/questions/7370593/… btw but I cannot flag it for some weird reason - I edited answer to the proper one (cause I also cannot delete it now... uhh). Thanks for the warning anyway

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.