10
    public static void main(String[] args){
        one();
        two();
        three();
    }

    public static void one() {
        String s1 = "hill5";
        String s2 = "hill" + 5;
        System.out.println(s1==s2);
    }

    public static void two() {
        String s1 = "hill5";
        int i =5;
        String s2 = "hill" + i;
        System.out.println(s1==s2);
    }

    public static void three() {
        String s1 = "hill5";
        String s2 = "hill" + s1.length();
        System.out.println(s1==s2);
    }

出力は

true 
false 
false 

文字列リテラルはインターンプロセスを使用し、なぜtwo()three()が false.の場合は理解できますが、three()明確でtwo()はありません.しかし、両方の場合について適切な説明が必要です.

誰かが適切な理由を説明してもらえますか?

4

2 に答える 2

1

コンパイル時定数式を持つ文字列は、文字列プールに置かれます。主な条件は、コンパイル時の定数式です。メソッドでローカル変数を final にするtwo()と、two()出力も出力されますtrue

public static void two() {
    String s1 = "hill5";
    final int i =5;
    String s2 = "hill" + i;
    System.out.println(s1==s2);
}

出力:

true
于 2018-07-04T09:37:23.640 に答える