What is the difference between == and .equals() in Java?
In Java, == and .equals() are used to compare objects or variables, but they serve different purposes:
1. == Operator
Purpose: Compares references (memory addresses) of objects.
Usage: Used to check if two references point to the same object in memory.
Example:
String str1 = new String(“Hello”);
String str2 = new String(“Hello”);
System.out.println(str1 == str2); // false (different memory locations)
2. .equals() Method
Purpose: Compares the content (value) of objects.
Usage: Used to check if two objects have the same value or content.
Example:
String str1 = new String(“Hello”);
String str2 = new String(“Hello”);
System.out.println(str1.equals(str2)); // true (content is the same)