与Java中的逻辑运算符的字符串比较 [英] String comparison with logical operator in Java

查看:132
本文介绍了与Java中的逻辑运算符的字符串比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比较两个字符串时,我被告知我们不应该使用逻辑运算符(==)。我们应该使用String.equals(String)进行比较。但是,我看到以下代码符合并使用最新的JDK(1.6_23)打印 Hello Friend 。我试着四处寻找,找不到任何参考。从何时发生?

When comparing two strings, I was taught that we shouldn't use the logical operator (==). We should use String.equals(String) for the comparison. However, I see that the following code complies and prints "Hello Friend" with the latest JDK(1.6_23). I tried searching around and couldn't find any reference. From when is this happening?

public class StringComp{
public static void main(String args[]){
        String s = "hello";
        if(s=="hello"){
                System.out.println("Hello Friend");
        }else{
                System.out.println("No Hello");
        }
    }
}


推荐答案

您不应该使用 == ,因为它会做您认为的其他事情。

You shouldn't use == because it does something else then you think.

在此保存hello(读取字符串实习),因此与你的激动相同是巧合。

In this case, the "hello" is saved (Read up on string interning), so it is "coincidence" that it is the same thing as your stirng.

== 检查两件事情是否完全相同,而不是内容相同。这是一个非常大的区别,一些偶然的(虽然可以解释)虚假的可能性没有理由使用这种方法。

== checks if two things are EXACTLY the same thing, not if they have the same content. This is a really big difference, and some accidental (though explainable) "false possitives" are no reason to use this method.

只需使用equals进行字符串比较。

Just use equals for string comparison.

从这个站点得到一个例子:
http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/

From this site an example: http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/

String a = new String ("a");
String b = new String ("a");
System.out.println (a == b);

它返回false,而以下代码返回true。

It returns false, while the following code returns true.

String a = new String ("a");
String b = new String ("a");
System.out.println (a.equals(b));

这篇关于与Java中的逻辑运算符的字符串比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆