== Operator.
In Java, the == operator is used to compare primitive data types and object references. When comparing primitive data types, it checks whether the values are the same. When comparing object references, it checks whether the references point to the same memory location.
Example Java Code:
public class EqualityExample { public static void main(String[] args) { // Primitive types int x = 5; int y = 5; System.out.println(x == y); // true // Object references String str1 = new String("Hello"); String str2 = new String("Hello"); System.out.println(str1 == str2); // false } }
true
false
Explanation:
In the example, x == y is true because the values of x and y are both 5. However, str1 == str2 is false because the == operator compares the references, and str1 and str2 point to different memory locations.
equals() Methods.
The equals() method is a method provided by the Object class and is meant to be overridden by classes that need to define a logical equality. By default, the equals() method in the Object class compares object references, similar to the == operator.
Example Java Code:
public class EqualityExample { public static void main(String[] args) { String str1 = new String("Hello"); String str2 = new String("Hello"); System.out.println(str1.equals(str2)); // true } }
true
Explanation:
In this example, str1.equals(str2) is true because the String class overrides the equals() method to compare the actual content of the strings, not just the references.
It's important to note that many classes in Java, like String, Integer, and others, override the equals() method to provide meaningful content-based comparison. When working with custom classes, you should override equals() to suit the specific equality criteria for instances of your class.
No comments:
Post a Comment