简体   繁体   English

字符串比较意外输出

[英]String comparison unexpected output

In below program i am getting output as false .But as per my understanding when we add two temporary reference variable then result go inside constant pool which does not allow duplicates so we must have gotten output as true here but we are getting false as an output .Can somebody explain me reason behind this? 在下面的程序中,我得到的输出false 。但是据我的理解,当我们添加两个临时参考变量时,结果进入常量池内,不允许重复,因此我们必须在此处获得正确的输出,但我们得到的输出却为false有人能解释一下我的原因吗?

package com.lara;

public class Man9 
{
    public static void main(String[] args) 
    {
        String s1 = "ja";
        String s2 = "va";
        String s3 = "ja".concat("va");
        String s4 = "java";
        System.out.println(s3==s4);
    }
}

Your understanding about string concatenation is incorrect. 您对字符串连接的理解不正确。

Only string constants get interned by default. 默认情况下,只有字符串常量被保留。 Now a string constant isn't just a string literal - it can include the concatenation of other constants using the + operator , eg 现在,字符串常量不仅是字符串文字,还可以使用+运算符将其他常量串联起来,例如

String x = "hello";
String y = "hel" + "lo";
// x == y, as the concatenation has been performed at compile-time

But in your case, you're making a method call - and that's not part of what the Java Language Specification considers when determining constant string expressions. 但是,在您的情况下,您正在进行方法调用-这不是Java语言规范在确定常量字符串表达式时考虑的一部分。

See section 15.28 of the JLS for what is considered a "constant". 关于什么是“常量”,请参见JLS的15.28节

You need to use s3.equals(s4), not s3==s4. 您需要使用s3.equals(s4),而不是s3 == s4。

Then you will get your true result. 然后,您将获得真实的结果。

See transcript below 见下面的成绩单

C:\temp>java foo
false
true

C:\temp>type foo.java
public class foo
{
    public static void main(String[] args)
    {
        String s1 = "ja";
        String s2 = "va";
        String s3 = "ja".concat("va");
        String s4 = "java";
        System.out.println(s3==s4);
        System.out.println(s3.equals(s4));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM