Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can string pool contain two strings with the same value? [duplicate]

Tags:

java

string

Can string pool contain two strings with the same value??

String str = "abc";
String str1 = new String("abc");

   Will the second statement with `new()` operator creates two objects of `string` "abc", one on `heap` and another on `string` pool? 

   Now if i call intern() on str1 ie str1.intern(); as a third statement, will str1 refer to the "abc" from String pool? 

  If yes then what will happen to the object that was created on heap earlier by the new(). Will that object be eligible for garbage collection.?
  If no then what will be the result of str1.intern();?
like image 767
Yogesh Pangam Avatar asked Jul 20 '26 18:07

Yogesh Pangam


1 Answers

No first will also create one object and also second one will create only one string object. Difference is that first one will create in String pool and second one will create in heap only. If you will call str1.intern(); then it will be added to String pool.

String str1 = "abc";
String str2 = new String("abc");
Stirng str3 = "abc"

Here two objects will be created. first line will create one strong object with reference str1 and 3rd line will point to the same object created in 1st line with reference str3 but in 2nd line one new object will be created as we are using new keyword here. Hope it will help you.

Also check this answer. Good explanation is there.

like image 89
Android Killer Avatar answered Jul 22 '26 09:07

Android Killer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!