String s1=new String("rahul");
s1=new String("rahul");
s1=new String("kumar");
String s2=new String("rahul");
s2=new String("rahul");
s2=new String("kumar");
// How many Objects are created?
String s1=new String("rahul");
s1=new String("rahul");
s1=new String("kumar");
String s2=new String("rahul");
s2=new String("rahul");
s2=new String("kumar");
// How many Objects are created?
Every new String(...)
creates a new object. So in your example six objects are created.
Actually,
An >>indeterminate<< number of objects are created. Creating a String
(using new
) also entails creating the internal object or objects that represent it.
Six String
objects are created when the code is executed. There are two more String
objects associated with the code ... representing the string literals.
At the end of executing the code fragment, the number of String
objects that still exist is >>indeterminate<<. Four of the six String
objects that were created will now be unreachable, but they will continue to exist until the GC deletes them ... or the JVM exits.