需要有关此Java输出的帮助

时间:2015-09-02 09:08:53

标签: java

这是一个非常简单的代码:

  public class Test2 {

public static void main(String[] args)  {
        String a = "hello2"; 
        final String b = "hello";
        String d = "hello";
        String c = b + 2; 
        String e = d + 2;
        System.out.println((a));
        System.out.println((c));
        System.out.println((e));
        System.out.println((a == c));
        System.out.println((a == e));

    }
}

输出是:

hello2
hello2
hello2
true
false

请告诉我为什么最后一个是' false'谢谢

3 个答案:

答案 0 :(得分:1)

public static void main(String[] args)  {
        String a = "hello2"; 
        final String b = "hello"; // this will be a compile-time constant. `final String` makes a string compile-time-constant.
        String d = "hello";
        String c = b + 2; // The compiler will replace b+2 by "hello2"
        String e = d + 2; // d is not final. Hence value of b will be calculated at runtime.
        System.out.println((a));
        System.out.println((c));
        System.out.println((e));
        System.out.println((a == c));
        System.out.println((a == e));

    }

答案 1 :(得分:0)

这是因为您要比较对象,而不是实际的String值。使用.equals()比较字符串值。

答案 2 :(得分:0)

您应该将字符串值与equals()而不是==运算符进行比较。 ==比较引用而不是值。