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.
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.
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!
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.
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 ().
"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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With