How many String objects will the following code produce?
String s1="Hello"; //"Hello" is in String Pool Object #1
String s2 = s1.substring(2,3);//String object #2
String s3 = s1.toString();
String s4 = new StringBuffer(s1).toString(); //String Object #3
This is the question to one practice Java book I am reading.
There is no answer, so I am not sure if my answer is right. Are there 3 or 5 string objects created? Does toString() create a new String object? I looked up online and found that toString() “Returns a string representation of the object”. I don’t quite understand what this means.
I think you are correct. Number of String objects would be 3 NOT 5.
s1.toString();javadoc says:creates new String object.