1.

How many objects will be created for the following codes:

Answer»

A. 

String str1 = "abc"; //Line1String str2 = new String("abc"); //Line2

B.

String str1 = "abc"; //Line1String str2 = "abc"; //Line2

C.

String str1 = new String("abc"); //Line1String str2 = new String("abc"); //Line2
  • For A: In this case, TWO objects will be created. We know that WHENEVER a Java string is created using a new keyword, then two objects will be created i.e. one in the Heap Area and another one in the String constant pool. When the line1 is executed, the new string object str1 gets created and stored in the string constant pool. However, when line2 is executed, only one object is created using a new operator that gets stored in the heap memory (str2). This is because String constant pool already has a String object with the same string value (abc), and therefore, the reference of the string str1 from the string constant pool is returned.
  • For B: In this case, one object will be created. Here, for line1 (str1), one new object will get created in String constant pool, WHEREAS for line 2, string str2 will create a reference to the String str1 because the string constant pool already has a String object str1 with the same string value (abc).
  • For C: In this case, three objects will be created. In the case of line1 (str1), two objects are created, one in the string constant pool and one in the heap memory. As for line 2 (str2), one new object is created and stored in heap memory, but not in the string constant pool because a String constant pool object str1 already has the string object str1 with the same string value (abc).


Discussion

No Comment Found