How many Java Strings Created?

前端 未结 2 1865
清酒与你
清酒与你 2020-12-11 10:05
public static void main(String [] args){ 
    String s = \"java\"; //line 1
    s.concat(\" SE 6\"); //line 2
    s.toLowerCase();  //line 3
    System.out.print(s);         


        
相关标签:
2条回答
  • 2020-12-11 10:14

    3 Java Strings are created.

    1. "java"  -> Goes into String constants pool // will be added if no already present
    2.  " SE 6" --> Goes into String constants pool?
    3. java SE 6 --> Goes on heap (call to concat)// Note : You are not re-assinging the value returned from concat() So s will still be "java"
    ** toLowerCase() \\ does nothing in your case since "java" is already present. toLowerCase retruns the same "java" object ( as there is no modification required to turn it into lowercase)
    
    0 讨论(0)
  • 2020-12-11 10:28

    Java know that the "java" string already exists in constant pool, so it needs not to create the object again?

    Actually, it's not "java" string that exists in the pool, but "Java" (in uppercase). If it were indeed "java", toLowerCase() would have recognized it, and returned the original string. But since the return value (i.e. "java" in all lowercase) does not match the original string (i.e. "Java" in mixed case) a new String object needs to be created, bringing the count to 4.

    Edit: After the edit to the question the answer changes: now that you've changed "Java" to "java", the number of objects that get created is three, because Java String has an optimization that returns the original string from toLowerCase when the string is already in lowercase. So line 1 creates one string object "java", line 2 creates two string objects " SE 6" and "java SE 6", and lines 3 and 4 do not create any additional objects.

    0 讨论(0)
提交回复
热议问题