Differences in Java == and the equals method

Code

public class xxx {
	

		
public static void main(String[] args)
{	
	String a1=new String("abc");
	String a2=new String("abc");
	String a3=a2;
	//使用“===”运算符比较a2和a3
	System.out.println("a2==a3的运算结果为:"+(a2==a3));
	//使用equal的方法比较a2和a3
	System.out.println("a2.equals(a3)的运算结果为:"+(a2.equals(a3)));
	

	}
 == 运行结果 ==

Here Insert Picture Description

We can see that == and equals () method is different:

1.equals()方法是String类中的方法,他用于比较两个对象引用所指内容是否相等
2. ==运算符比较的是两个对象引用地址是否相等。

Here too, a1 and a2 are two different object reference, two different position in the content, and String c3 = c1; c1 statement is assigned to c3, so the two object references are equal,
so it is clear that the results what we have seen in eclipse.

Graphic Interpretation:

Here Insert Picture Description

Published 63 original articles · won praise 12 · views 4078

Guess you like

Origin blog.csdn.net/qq_45353823/article/details/101949939