Sunday, January 19, 2025
HomeQ&AWhat is the difference between = and Equals in Java?

What is the difference between = and Equals in Java?

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.

See also  How many tablespoons are in three ounces of cream?

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.
See also  1 Pound Of Uncooked Pasta Is How Many Grams?

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.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x