QUESTIONS & ANSWERS
JAVA
How two strings are compared in Java?
There are several ways to compare two strings in Java.
- Using the
equals()
method:
Theequals()
method compares the contents of two strings and returnstrue
if they are equal, i.e., if they have the same characters in the same order. It returnsfalse
otherwise. Here's an example:String str1 = "Hello"; String str2 = "World"; String str3 = "Hello"; System.out.println(str1.equals(str2)); // false System.out.println(str1.equals(str3)); // true
- Using the
==
operator:
The==
operator compares the references of two objects. If the references are equal, the operator returnstrue
. Otherwise, it returnsfalse
.String str1 = "Hello"; String str2 = "Hello"; System.out.println(str1 == str2); // true
However, it is important to note that the
==
operator does not compare the contents of the strings. It only compares the references. This means that the following code will also printtrue
:String str1 = new String("Hello"); String str2 = new String("Hello"); System.out.println(str1 == str2); // false
Even though the strings
str1
andstr2
have the same content, they are not equal because they are different objects. - Using the
compareTo()
method:
ThecompareTo()
method compares two strings lexicographically. It returns an integer value that indicates the relationship between the two strings. The return value is:
-> Negative if the first string is lexicographically less than the second string.
-> Zero if the two strings are equal.
-> Positive if the first string is lexicographically greater than the second string.String str1 = "apple"; String str2 = "banana"; String str3 = "apple"; System.out.println(str1.compareTo(str2)); // negative value System.out.println(str1.compareTo(str3)); // 0 System.out.println(str2.compareTo(str1)); // positive value
It's important to note that the
compareTo()
method is case-sensitive, meaning uppercase letters are considered to have a different value than lowercase letters. - Using the
compareToIgnoreCase()
method:
ThecompareToIgnoreCase()
method is similar to thecompareTo()
method, but it ignores case differences.
For example, the following code will print0
:String str1 = "Hello"; String str2 = "hello"; System.out.println(str1.compareToIgnoreCase(str2)); // 0
This is because the values of
str1
andstr2
are equal, even though they differ in case.
These are the basic methods to compare strings in Java. Additionally, Java provides other methods likeequalsIgnoreCase()
,startsWith()
,endsWith()
, etc., that allow you to perform more specific string comparisons based on your requirements. In general, theequals()
method is the most commonly used method for comparing strings.