How many objects are created?

There was a simple question around the Stringz instance pool in Java

If I have a situation like this: Scenario 1:

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

and then clicked Scenario 2:

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

In each case, how many objects are created in the row pool and heap? I assumed that both would create an equal number of objects (2 objects - one single "aaa" for both lines in each script in the string pool and one for the new statement). I was told in iview that this was wrong: I am curious what is wrong with my understanding?

0
source share
2 answers

A line for a literal "aaa"is created and merged when the class is loaded, so only one new line is created when your two lines of code are executed.

: String . , "aaa".

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();
    }
}
+1

1 1 , .

, : perm perm, .

String . . String.intern(), String ( , ) .

EDIT: , , System.out.println(s1 == s2); . false , , .

+1

All Articles