Java字符串文字串联

ank*_*hoi 9 java string string-concatenation

    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);
    }
Run Code Online (Sandbox Code Playgroud)

输出是

true 
false 
false 
Run Code Online (Sandbox Code Playgroud)

字符串文字使用实习过程,然后为什么two()而且three()是假的.我可以理解three()但是two()不清楚.但是需要对这两种情况进行适当的解释.

有人可以解释正确的理由吗?

ans*_*tta 14

在2和3的情况下,Compiler无法计算String的值,因为它hill + i是一个运行时语句,相同s1.length()

在这里阅读我问同样的情况 - 链接

这样认为String s1 and s2是使用编译时常量,s1="hill5"并且s2="hill" + 5,记住,作为文字指定的字符串是常量,其状态不能被修改,因为String是不可变的.

所以在编译时,编译器说"哦是的,它们被计算为相同的值,我必须为s1和s2分配相同的引用".

但是,在方法的情况下,two()three(),编译器说:"我不知道,可能是价值,我可以随时改变,或s1.length() 改变任何时间",其运行时的事情,所以编译器不会放的S2 two()three()方法游泳池,

因此,它们是错误的,因为在运行时,一旦它变得正确就会创建新对象!

  • @ankitagahoi不是真的 - 只有常量字符串放在池中,除非你使用`intern`方法... (2认同)
  • @anshulkatta JVM不检查任何此类事情.编译器将字符串文字放在常量池中:OP的代码创建新字符串.即使在相同的陈述已被纠正之后,你只是在弥补它.两次.规范性引用是JLS和JVM规范,而不是另一个论坛. (2认同)