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]上記のステートメントによると、文字列プールには 3 つのオブジェクトがあると言っても過言ではありません:-"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
will は偽であることがわかります。
StringBuilder を使用して実行時に評価された文字列連結の結果は、文字列プールに格納されず、代わりにヒープ(プール外)に入るということですか?