How to compare Strings in Java?


There are many ways how to compare strings in Java and most of them are different. Here we will cover these cases:

  • Using .equals() method;
  • Using .compareTo() method;
  • Using == operator.


  1. Let’s check what we can compare using .equals() / .equalsIgnoreCase() methods. If you are newbie in programming / Java – I am almost sure that this is what are you looking for. If you are using these methods – you will compare actual String values, are they equal or not. For example:
    String s1 = "";String s2 = "vilbay";
    System.out.println(s1.equals(s2)); //false
    s2 = "";
    System.out.println(s1.equals(s2)); //true


  2. Now let’s have a look to method .compareTo(). It compares strings on the basis of Unicode value of each character in strings. If first string is lexicographically greater than second string, it returns positive number (difference of character value). If first string is less than second string lexicographically, it returns negative number and if first string is lexicographically equal to second string, it returns 0.
    String s1="abc";
    String s2="abc";
    String s3="d";
    String s4="z";
    String s5="v";
    System.out.println(s1.compareTo(s2));//0 because both are equal
    System.out.println(s1.compareTo(s3));//-3 because "a" is 3 times lower than "d"
    System.out.println(s1.compareTo(s4));//-25 because "a" is 25 times lower than "z"
    System.out.println(s4.compareTo(s5));//4 because "z" is 4 times greater than "v"


  3. Now the last case, which will be covered in this tutorial is == operator. It does not compare values, it compares references to values. In other words, it answers the question “Does it reference to the  same place in RAM?”. 
    String s1="vilbay";
    String s2=s1;
    String s3=new String("vilbay");


Leave a Reply

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