根据 JLS(15.28 Constant Expressions) 的表达式仅包含:
i)Literals of primitive type and literals of type String (§3.10.1, §3.10.2, §3.10.3,
§3.10.4, §3.10.5)
or
ii)Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).
or
iii)...
是一个常数表达式。
NowString s1="a"+"b";
是一个常量表达式,将"ab"
在编译时计算。
所以s1="ab";
[1]我说的对吗,根据上面的说法,现在字符串池中有三个对象:-“a”,“b”,“ab”???
现在,
final String s="a";
final String s1="b";
String s2=s+s1; // is also constant expression and get evaluated at compile time.
上面的代码将s2="a"+"b";
在编译后转换为。
所以s2="ab";
会自动存储在字符串池中。
但,
// note there is no final now.
String s="a";
String s1="b";
String s2="a"+"b"; // constant expression.
String s3=s+s1; // is NOT a constant expression and get evaluated at RUN TIME.
对于String s3=s+s1;
,代码将被翻译为:
s3=new StringBuilder(String.valueOf(s)).append(s1).toString();
并将创建一个新的 String 对象。
因此,s2==s3
意志是虚假的;
这是否意味着在运行时使用 StringBuilder 评估的字符串连接的结果不会存储在字符串池中,而是进入堆(池外)?