0

Had a simple question around Stringz instance pooling in Java

If I have a situation like this: Scenario 1:

String s1 = "aaa";  
String s2 = new String("aaa");  

and then flipped Scenario 2:

String s1 = new String("aaa");  
String s2 = "aaa";  

In each case- how many objects are being created in the String Pool and Heap ? I assumed both would create an equal number of objects (2 Objects - one single "aaa" for both lines in each scenario in the String pool and one for the new Operator). I was told in an iview that this wasn't correct - I'm curious as to what is wrong with my understanding?

EdChum
  • 376,765
  • 198
  • 813
  • 562
  • Actually, this is the correct explanation: http://stackoverflow.com/questions/1881922/questions-about-javas-string-pool – evanwong Apr 06 '12 at 15:11
  • refer this https://stackoverflow.com/questions/3052442/what-is-the-difference-between-text-and-new-stringtext/63324716#63324716 – ThinkTank Aug 09 '20 at 09:55

2 Answers2

1

The String for the literal "aaa" is created and pooled when the class is loaded, so only one new String is created when your two lines are the code is executed.

To be clear: both examples only create one new String object when they execute. The literal is created the first time a class containing the String "aaa" is used.

class FooBar{
  void foo(){
    String s1 = "aaa";//the literal already exists  
    String s2 = new String("aaa");//creates string for s2 
  }
  void bar(){
    String s1 = new String("aaa"); //creates string for s1 
    String s2 = "aaa";//the literal already exists  
  }
}

class Test{

    public void main(String... args){
      ...
      //first time class FooBar used in program, class with literals loaded
      FooBar fb = new FooBar();
      //creates one string object, the literal is already loaded
      fb.bar();
      //also creates one string object, the literal is already loaded
      fb.foo();
    }
}
josefx
  • 15,506
  • 6
  • 38
  • 63
1

The answer is 1 instance in the heap and 1 in the String pool in either case as you said in your interview.

There are two spaces where Strings can reside: The heap and the perm gen where interned strings are stored.

The String constructor creates a String in the heap. String literals are created in the String pool within the permanent generation. Strings in the heap can be moved to the String pool with the method String.intern() which interns the String (that is, determines a reference to an equal String in the pool or creates an equal String there, if there is none yet) and returns a reference to the interned String.

EDIT: To check what I have answered, add System.out.println(s1 == s2); as a third line to each example. It will print false in both cases, proving that both objects have different memory addresses.

Michael Schmeißer
  • 3,407
  • 1
  • 19
  • 32