Which method is used to compare two strings in Java for equality?

Java MCQ: Which method is used to compare two strings in Java for equality?

a) equals()
b) compare()
c) compareTo()
d) ==

Answer:

a) equals()

Explanation:

In Java, the equals() method is used to compare two strings for equality. This method compares the content of the strings, character by character, and returns true if the strings are identical.

Using == to compare strings, on the other hand, compares the reference or memory addresses of the objects, not their actual content. Therefore, == should not be used to check string equality in Java.

The equals() method is a fundamental tool in Java programming, ensuring that string comparisons are based on the actual text rather than object references.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top