• Post Reply Bookmark Topic Watch Topic
  • New Topic

String Concepts  RSS feed

 
Pankaj Shet
Ranch Hand
Posts: 320
Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ranchers,

I wish to know how to count the number of string objects created in  Java Program.

Suppose if I have :

Case1:
---------
String str1=new String("abc") ;
String str2=new String("abc") ;

now 2 objects are created on Heap.

but "abc" is interned and goes in a String Constant Pool.

which is 3rd object.

So in this case, total 3 objects will be created.

case 2:
----------

String str1="xyz";
String str2="xyz";

In this case only 1 object is created.

Case 3:
-----------
String str1=new String("Lmn");
String str2="Lmn";

In this case: At line 1,  2 objects will be created, 1 on heap, and 1 is interned.
                   At line 2, str2 just refers to the interned String "Lmn"

So only 2 objects are created.

Case 4:
-----------
String str1=pqr;
String str2=new String("pqr");

In this case: At line 1, pqr goes to String Pool.
                   At line 2, 1 object is created on heap, and  "pqr" is interned, but since it is already present in String Pool it is discarded.
So only 2 objects are created.

Please correct me if I am wrong.

Regards,
-Pankaj.








But I wish to understand, why is "abc" interned?

Regards,
-Pankaj.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!