Q:

Number of String objects created

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.

A:

It will create three. Your analysis is correct.

Does toString() create a new String object? I looked up online and found that toString() "Returns a string representation of the object".

That's the description for the generic Object.toString, but String overrides it to give more specific behavior. Its version is documented this way:

This object (which is already a string!) is itself returned.

[link]

A:

I think you are correct. Number of String objects would be 3 NOT 5.
s1.toString(); javadoc says: 

This object (which is already a string!) is itself returned.

new StringBuffer(s1)

creates new String object.

A:

Whenever you use a new keyword to create a string object it will create a new String object no matter the string is already present in the pool of strings
String s1="Hello"; //this will create a new string object and add it to the pool of strings

String s2 = s1.substring(2,3);//String object #2 again creates a string and adds it in the pools of strings
String s3 = s1.toString();//this will not create a new object but simply refer to already existing object in the pool of strings
String s4 = new StringBuffer(s1).toString(); //String Object #3 this will create a new object as you are using new keyword 

an example
public class Main {
    public static void main(String[] args) {
        String s1 = "abc";//created a string and added it to pool of string
        String s2 = "abc";//no need to create a new object
        String s3 = new String("abc");
        System.out.println("s1 = " + s1);
        System.out.println("s2 = " + s2);
        System.out.println("s2 = " + s3);
        System.out.println("s1 == s2? " + (s1 == s2));//proves that the ref refer to same object
        System.out.println("s1 == s3?"+ (s1==s3));
        System.out.println("s1.equals(s2)? " + (s1.equals(s2)));    
  }
}

the output
s1 = abc
s2 = abc
s3 = abc
s1 == s2? true
s1 == s3? false
s1.equals(s2)? true

