-7
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?

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
Rahul
  • 35
  • 5
  • 2
    42! Seems to be a homework dump. I am voting to close this as: unclear what you are asking. Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. – ctst Feb 05 '16 at 14:36
  • New keyword created new object every time – Alex Shutin Feb 05 '16 at 14:37
  • *"New keyword created new object every time"* - At least one new object. (Have you looked at what the `String` constructors do?) – Stephen C Feb 05 '16 at 14:44

2 Answers2

0

Every new String(...) creates a new object. So in your example six objects are created.

diiN__________
  • 7,393
  • 6
  • 42
  • 69
0

Actually,

  1. An >>indeterminate<< number of objects are created. Creating a String (using new) also entails creating the internal object or objects that represent it.

  2. Six String objects are created when the code is executed. There are two more String objects associated with the code ... representing the string literals.

  3. 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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216