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); //line 4
}
Run Code Online (Sandbox Code Playgroud)
这个问题的答案是"4".我以为它会是"3".我的困惑是第3行,它再次创建"java"字符串,但是java不知道"java"字符串已经存在于字符串常量池中,那么为什么要再创建它呢?
Java知道"java"字符串已经存在于常量池中,所以它不需要再次创建对象吗?
实际上,它不是"java"池中存在的字符串,而是"Java"(大写).如果确实如此"java",toLowerCase()会认出它,并返回原始字符串.但由于返回值(即"java"全部小写)与原始字符串不匹配(即"Java"在大小写混合的情况下),因此String需要创建一个新对象,使计数为4.
编辑:在对问题进行编辑后,答案会发生变化:现在您已更改"Java"为"java",创建的对象数量为3,因为Java String有一个优化,从toLowerCase字符串已经是小写时返回原始字符串.所以线1创建一个字符串对象"java",第2行创建两个字符串对象" SE 6"和"java SE 6",以及线3和4不创建任何其他对象.
3 Java Strings已创建.
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)
Run Code Online (Sandbox Code Playgroud)