Category:
Java
Below are 5 ways to compare two Strings in Java:
- Using user-defined function : Define a function to compare values with following conditions :
- if (string1 > string2) it returns a positive value.
- if both the strings are equal lexicographically
i.e.(string1 == string2) it returns 0. - if (string1 < string2) it returns a negative value.
- Using String.equals()
- str1.equals(str2);
- Using String.equalsIgnoreCase()
- str2.equalsIgnoreCase(str1);
- Using Objects.equals() : Objects.equals(Object a, Object b)
- Objects.equals(string1, string2);
- Using String.compareTo()
- int str1.compareTo(String str2);