Using '==' instead of .equals for Java strings [duplicate]

ぃ、小莉子 提交于 2019-11-27 05:07:58

This is because you're lucky. The == operator in Java checks for reference equality: it returns true if the pointers are the same. It does not check for contents equality. Identical strings found at compile-time are collapsed into a single String instance, so it works with String literals, but not with strings generated at runtime.

For instance, "Foo" == "Foo" might work, but "Foo" == new String("Foo") won't, because new String("Foo") creates a new String instance, and breaks any possible pointer equality.

More importantly, most Strings you deal with in a real-world program are runtime-generated. User input in text boxes is runtime-generated. Messages received through a socket are runtime-generated. Stuff read from a file is runtime-generated. So it's very important that you use the equals method, and not the == operator, if you want to check for contents equality.

Can anyone give me an example of the == operator failing?

Example 1:

String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(s1 == s2); // false

Example 2:

Integer a=1000,b=1000;
System.out.println(a == b); // false

When you do this, you are actually creating string literals:

String s1 = "Hello";
String s2 = "Hello";

The compiler finds identical string literals and then optimizes by keeping one instance in the heap and making all the variables in the stack point to it. So doing an == will return true because they point to the same memory address.

When you do this, you are creating string objects:

String s1 = new String("Hello");
String s2 = new String("Hello");

The instantiation will create unique space on the heap for each of these and the stack variables will point to those separate locations. Thus, these will be equal using .equals() because their values are the same, but they will not be equal using == because they are different objects in the heap memory space.

Seasoned Java developers rarely if ever use new String(String), but the problem arises in other cases as well. For example:

String hello = "Hello"
String hell = hello.substring(0, 4);
System.err.println("Hell" == hell);  // should print "false".

(Most String instances in a real-world applications are formed either by taking a substring of some other String, or by constructing it from an array of characters. Very few applications will only use String instances created as literals.)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!