Java中字符串与逻辑运算符的比较

发布于 2024-10-13 06:41:04 字数 436 浏览 4 评论 0原文

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

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");
        }
    }
}

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");
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

农村范ル 2024-10-20 06:41:04

您不应该使用 == 因为它会做一些超出您想象的事情。

在这种情况下,“hello”被保存(阅读字符串实习),所以它与你的stirng是同一件事是“巧合”。

== 检查两个事物是否完全相同,而不是它们是否具有相同的内容。这是一个非常大的差异,一些偶然的(尽管可以解释的)“误报”并不是使用此方法的理由。

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

从这个网站来看一个例子:
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。

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

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

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.

Just use equals for string comparison.

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);

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));
鲸落 2024-10-20 06:41:04

这种魔法被称为实习

Java interns 字符串文字,因此它的计算结果很可能为 true:

String a = "hello";       // "hello" is assigned *and* interned
String b = "hello";       // b gets a reference to the interned literal
if (a == b)
   System.out.println("internd.");

String c = "hello" + Math.abs(1.0);   // result String is not interned
String d = "hello" + Math.abs(1.0);   // result String is not interned
System.out.println(c==d);             // prints "false"

c = c.intern();
System.out.println(c==d);             // prints "false"

d = d.intern();
System.out.println(c==d);             // prints "true"

The magic is called interning.

Java interns String literals and so there is a high probability that it evaluates to true:

String a = "hello";       // "hello" is assigned *and* interned
String b = "hello";       // b gets a reference to the interned literal
if (a == b)
   System.out.println("internd.");

String c = "hello" + Math.abs(1.0);   // result String is not interned
String d = "hello" + Math.abs(1.0);   // result String is not interned
System.out.println(c==d);             // prints "false"

c = c.intern();
System.out.println(c==d);             // prints "false"

d = d.intern();
System.out.println(c==d);             // prints "true"
舞袖。长 2024-10-20 06:41:04

== 运算符用于检查两者是否是对同一 String 对象的引用,而 .equals 则比较值。

The == operator is used to check if both are references to the same String object while .equals compares the values.

吖咩 2024-10-20 06:41:04

它适用于您的情况(据我所知,它也像早期的 JVM 中那样工作),因为 s 引用字符串文字 "hello"。用文字初始化的字符串引用指的是文字(这是后台的全局对象),而不是单独创建的新对象。正如其他人也提到的那样,这个术语是实习。因此,示例中的 s"hello" 指的是同一个物理对象。考虑

String s1 = "hello";
String s2 = "hello";
String s3 = "hello";

所有这些字符串都引用同一个物理对象,因此任何一对字符串之间或其中任何字符串与 "hello" 之间的 '==' 比较都会返回 true

然而,

String s4 = new String ("hello");

创建了一个新对象,因此 s4 == "hello" 产生 false

It works in your case (and AFAIK it has been working like that in earlier JVMs as well) because s refers to the string literal "hello". String references initialized with literals refer to the literal (which is a global object in the background), not a separately created new object. The term for this, as others have mentioned too, is interning. Thus s and "hello" in your example refer to the same physical object. Consider

String s1 = "hello";
String s2 = "hello";
String s3 = "hello";

All of these strings refer to the same physical object, thus '==' comparison between any pair of these, or between any of them and "hello" returns true.

However

String s4 = new String ("hello");

creates a new object, thus s4 == "hello" yields false.

临风闻羌笛 2024-10-20 06:41:04

“Java 虚拟机维护一个内部字符串引用列表(唯一字符串池),以避免堆内存中出现重复的字符串对象。每当 JVM 从类文件加载字符串文字并执行时,它都会检查该字符串是否存在于内部列表中如果它已经存在于列表中,那么它不会创建一个新的字符串,并且它使用对现有字符串对象的引用,JVM 在内部对字符串文字进行这种类型的检查,但不检查它通过“new”创建的字符串对象。 ' 关键字。您可以显式强制 JVM 对使用 String.intern() 方法通过 'new' 关键字创建的 String 对象进行这种类型的检查,这会强制 JVM 检查内部列表并使用现有的 String 对象(如果是)。 所以结论

是,JVM 在内部为 String 文字维护唯一的 String 对象,程序员不必担心 String 文字,但他们应该担心使用“new”关键字创建的 String 对象,并且应该使用 intern() 方法来避免。堆内存中的重复 String 对象反过来又提高了 java 性能。有关详细信息,请参阅以下部分。”

参考:PreciseJava.com - 字符串中的优化技术和 StringBuffer(JVM 如何使用字符串)

"Java Virtual Machine maintains an internal list of references for interned Strings ( pool of unique Strings) to avoid duplicate String objects in heap memory. Whenever the JVM loads String literal from class file and executes, it checks whether that String exists in the internal list or not. If it already exists in the list, then it does not create a new String and it uses reference to the existing String Object. JVM does this type of checking internally for String literal but not for String object which it creates through 'new' keyword. You can explicitly force JVM to do this type of checking for String objects which are created through 'new' keyword using String.intern() method. This forces JVM to check the internal list and use the existing String object if it is already present.

So the conclusion is, JVM maintains unique String objects for String literals internally. Programmers need not bother about String literals but they should bother about String objects that are created using 'new' keyword and they should use intern() method to avoid duplicate String objects in heap memory which in turn improves java performance. see the following section for more information."

Reference: PreciseJava.com - Optimization techniques in Strings and StringBuffer (How the JVM works with Strings)

﹏半生如梦愿梦如真 2024-10-20 06:41:04

== 比较对象引用

您可以通过观察以下代码中的输出来理解它:

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

这个程序会打印 No hello

因为在这段代码中,变量 s 引用新的字符串对象,该对象又引用字符串池中的字符串文字“hello”。

== compares the object references

You can understand it by observing the output in the following code:

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

This program would print No hello

Because in this code, the variable s refers to new String Object which in turn refers to String literal "hello" from the String pool.

千年*琉璃梦 2024-10-20 06:41:04

== 比较对象引用,equals() 比较字符串的值。

在您的情况下,您分配两个 String 对象,它们的值都是“hello”,然后将它们与 == 进行比较。编译器可能会决定优化并使用相同的对象引用,从而给出与您获得的结果类似的真实结果。然而,这并不能保证行为——使用 equals() 进行值比较要安全得多。

== compares the object references, equals() compares the values of the Strings.

In your case you are allocating two String objects both with value "hello", then comparing them with ==. The compiler may decide to optimise and use the same object reference, giving a true result like the one you got. However this is not guaranteed behaviour - it is much safer to use equals() for value comparison.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文