The difference between "==" and ".equals()" in Java

 In Java, "==" and ".equals()" are used to compare objects, but they have different purposes and behaviors:

"==" (Equality Operator)

The "==" operator checks referential equality, that is, it compares whether two objects reference exactly the same location in memory. This means that it checks whether both sides of the expression point to the same object. 

Example:

String str1 = new String("Hello");
String str2 = new String("Hello");
String str3 = str1;
System.out.println(str1 == str2); // false (different objects)
System.out.println(str1 == str3); // true (same reference)

".equals()"

The ".equals()" method is used to compare the contents of objects, not the memory reference. It is a method defined in the "Object" class and is often overridden by specific classes to provide a meaningful comparison implementation.

Example:

String str1 = new String("Hello");
String str2 = new String("Hello");

System.out.println(str1.equals(str2)); // true (same content)

In the above example, although "str1" and "str2" are different objects in memory, the ".equals()" method is overridden in the "String" class to compare the contents of the strings, resulting in "true".

Important Consideration

In many standard Java classes, such as "String", "equals()" is overridden to provide content comparison. However, in other classes, "equals()" may have the same behavior as "==" unless explicitly overridden.

Integer num1 = new Integer(5);
Integer num2 = new Integer(5);

System.out.println(num1 == num2);         // false (different references)
System.out.println(num1.equals(num2));    // true (same content)


In short, while "==" compares referential equality, ".equals()" compares the contents of objects. In many cases, especially when dealing with complex objects or user-defined classes, it is advisable to use ".equals()" to ensure correct content comparison.

Nenhum comentário:

Postar um comentário

Internet of Things (IoT) and Embedded Systems

The  Internet of Things (IoT)  and  Embedded Systems  are interconnected technologies that play a pivotal role in modern digital innovation....