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.
- 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 = "vilbay.com";String s2 = "vilbay";
s2 = "vilbay.com";
- 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.
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"
- 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 s3=new String("vilbay");