Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many String objects will be created

Tags:

java

scjp

I have the following Java code:

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

The question is somehow simple: how many String objects will be created when this method is invoked?

At the beginning I answered that 5 String objects are created, but the answer from my book says that only 3 objects are created and no explanation was given (this is a SCJP question).

From my point of view there are 5 objects: "Fred", "47", "Fred47", "ed4", "ED4".

I also found this question on a SCJP simulation exam, with the same answer 3.

like image 325
Ramona Avatar asked Sep 10 '11 08:09

Ramona


People also ask

How many ways a string object can be created in Java?

How many ways a String object can be created in java? You can create a String by − Step 1 − Assigning a string value wrapped in " " to a String type variable. Step 2 − Creating an object of the String class using the new keyword by passing the string value as a parameter of its constructor.

How many objects are there in a StringBuilder?

It creates a StringBuilder and then appends the strings. So there may be 5 objects, 3 (variables) + 1 (sb) + 1 (Concatenated string). Thanks for contributing an answer to Stack Overflow!

How many objects are created when new string() is invoked?

Whenever new String () is invoked, it creates one object. But there is a method in String class which also restricts new from creating object if it is already there in string literal pool and that method is intern (). If abc is already present in literal pool then 1 object is created for str and reference is passed for abc.

How many objects can be created in a string literal pool?

Only one object gets created. Whenever new String () is invoked, it creates one object. But there is a method in String class which also restricts new from creating object if it is already there in string literal pool and that method is intern ().


1 Answers

"Fred" and "47" will come from the string literal pool. As such they won't be created when the method is invoked. Instead they will be put there when the class is loaded (or earlier, if other classes use constants with the same value).

"Fred47", "ed4" and "ED4" are the 3 String objects that will be created on each method invocation.

like image 186
Joachim Sauer Avatar answered Sep 28 '22 04:09

Joachim Sauer