java 运算符 == 使用

发布于 2024-11-28 11:20:51 字数 415 浏览 5 评论 0原文

可能的重复:
Java 中的字符串:equals vs ==
比较java中的字符串

==可以应用于字符串吗?

如果是这样,那么它对于 String 数据类型有什么用呢?

换句话说,虽然我们应该使用 equal 方法来比较两个字符串 java,但是 == 运算符在 java 中对 String 有什么用呢?

Possible Duplicates:
Strings in Java : equals vs ==
Comparing strings in java

is == can be apply to Strings ?

if so then what is the use of it for String's data type?

in other words although we should use equal method for comparing two string java, what is the use of == operator for String in java?

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

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

发布评论

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

评论(4

如日中天 2024-12-05 11:20:51

== 不会比较字符串的值,而是比较其地址。如果要比较值,请使用 equals() 方法。

== will not compare the value of the String but its addresse. If you want to compare the value use the method equals().

苍景流年 2024-12-05 11:20:51

当您想要比较 Java 中的对象时,应该使用 equals() 方法。运算符 == 用于比较 Java 对象中的引用,而不是值。

例如:

String s1 = "hello";
String s2 = new String("hello");
boolean comp = s1.equals(s2); // correct, returns true
comp = s1 == s2; // wrong, returns false

When you want to compare objects in Java, you should use the equals() method. The operator == is used to compare references, not values, in Java objects.

For example:

String s1 = "hello";
String s2 = new String("hello");
boolean comp = s1.equals(s2); // correct, returns true
comp = s1 == s2; // wrong, returns false
冧九 2024-12-05 11:20:51

'==' 运算符比较两个对象引用。因此,对于两个字符串,它会检查这些对象,并查看它们是否表示内存中的相同位置。

.equals() 方法将字符串的内容相互比较。

The '==' operator compares two Object references. So, in the case of two Strings, it is examining those objects, and seeing if they represent the same location in memory.

The .equals() method compares the Strings' contents to each other.

情深缘浅 2024-12-05 11:20:51

比较对象时,== 运算符会比较引用是否相同。在基本类型(int、float、double、boolean)中,它实际上比较值。由于字符串是对象,因此最好使用 equals() 方法。 == 将比较字符串的两个引用是否相同,但也可能不同。 Java 集合也使用 equals() 方法。

Comparing objects, == operator compares if the references are the same. In primitive types (int, float, double, boolean) it actually compares the value. Since Strings are objects, it's better to use the equals() method. == will compare if both references of strings are the same, which may not. equals() method is also used by Java Collections.

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