Javatpoint Logo
Javatpoint Logo

Java String compare

java string comparison

We can compare string in java on the basis of content and reference.

It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc.

There are three ways to compare string in java:

  1. By equals() method
  2. By = = operator
  3. By compareTo() method

1) String compare by equals() method

The String equals() method compares the original content of the string. It compares values of string for equality. String class provides two methods:

  • public boolean equals(Object another) compares this string to the specified object.
  • public boolean equalsIgnoreCase(String another) compares this String to another string, ignoring case.
Test it Now
Output:true
       true
       false
Test it Now

Output:

false
true
Click here for more about equals() method

2) String compare by == operator

The = = operator compares references not values.

Test it Now
Output:true
       false

3) String compare by compareTo() method

The String compareTo() method compares values lexicographically and returns an integer value that describes if first string is less than, equal to or greater than second string.

Suppose s1 and s2 are two string variables. If:

  • s1 == s2 :0
  • s1 > s2   :positive value
  • s1 < s2   :negative value
Test it Now
Output:0
       1
       -1
Click me for more about compareTo() method



Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA