Java中equals()和==之间的区别

The equals() method and == operator in Java perform two different operations. The equals() method is used to compare two string values. On the other hand == operator is used to compare two primitive datatype variables or to compare references of two objects. Below is a sample program that shows difference between equals() and == in Java.

Java中的equals()方法和==运算符执行两种不同的操作。 equals()方法用于比较两个字符串值。 另一方面,==运算符用于比较两个原始数据类型变量或比较两个对象的引用。 下面是一个示例程序,显示了Java中equals()和==之间的区别。

class EqualsAndEqualExample
{
	public static void main(String...s)
	{
		String str1=new String("The Crazy Programmer");
		String str2=new String("The Crazy Programmer");
		
		System.out.println("str1 equals() str2 "+str1.equals(str2));
		System.out.println("str1 == str2 "+(str1==str2));
	}		
}

Output

输出量

Difference Between equals() and == in Java

In first case we are comparing the values or content of String objects str1 and str2 using equals() method. The result is true because there values are equal.

在第一种情况下,我们使用equals()方法比较String对象str1和str2的值或内容。 结果是正确的,因为那里的值相等。

In the second case we are comparing the references of String objects str1 and str2 using == operator. The result is false because there references are not equal as both the objects are different.

在第二种情况下,我们使用==运算符比较字符串对象str1和str2的引用。 结果为假,因为两个对象都不相同,所以引用不相等。

翻译自: https://www.thecrazyprogrammer.com/2015/08/difference-between-equals-and-in-java.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值