In Java, = and equals are two distinct operators used for different purposes:
Assignment Operator (=)
The = operator is used for assignment, which means it assigns a value to a variable. It does not check for equality.
Example:
int x = 5; // Assigns 5 to x
Equality Operator (equals)
The equal’s method is used to compare the values of two objects. It checks whether the two objects have the same value or not.
Example:
String s1 = “Hello”
String s2 = “Hello”
Key differences:
- = is an assignment operator, while equals are a method used for comparison.
- = does not check for equality, whereas equals do.
- = is used with primitive data types, while equals are used with objects.
When to use each:
– Use = when you want to assign a value to a variable.
– Use equals when you want to compare the values of two objects.