Java : String Compare


 

Java : String Compare

This tutorial demonstrate various way to compare two strings.

This tutorial demonstrate various way to compare two strings.

Java : String Compare

This tutorial demonstrate various way to compare two strings.

 String Compare : In java, you can compare strings in many ways. It has provide ==operator, equals method and compareTo method to compare the strings.
 int compareTo( String anotherString ): This method compare two string based upon the unicode value of each character in the String and returns negative if first string is less than another and returns positive if first string is greater than another.

  • int compareTo(Object obj): It behaves same as the above method if the argument object is of type string.
  • int compareToIgnoreCase( String anotherString ): This method compare two strings ignoring the character case of the given Strings.
  • equals(String anotherString): This method checks the equality of two strings. It returns true and false.
  • equalsIgnoreCase(String anotherString): This method checks the equality of two strings  ignoring the character case of the given Strings.

Example:

class StringCompare {
public static void main(String[] args) {
String str1 = "Hello Roseindia";
String str2 = "hello roseindia";

// compareTo() method
if (str1.compareTo(str2) < 0) {
System.out.println("Strings are not equal");
} else {
System.out.println("Strings are equal");
}

// compareToIgnoreCase() method
if (str1.compareToIgnoreCase(str2) < 0) {
System.out.println("Strings are not equal");
} else {
System.out.println("Strings are equal");
}

// equals() method
if (str1.equals(str2)) {
System.out.println("Strings are equal");
} else {
System.out.println("Strings are not equal");
}
// equalsIgnoreCase() method
if (str1.equalsIgnoreCase(str2)) {
System.out.println("Strings are equal");
} else {
System.out.println("Strings are not equal");
}
}
}

Description : In this example, we have compared the two strings with different ways. When we check the strings by compareTo() method, the values comes negative therefore condition displays "Strings are not equal". On comparing with compareToIgnoreCase, we  get the positive value. Similar to compareTo method, when we have checked the strings with equals() method, it returns false and on comparing with equalsIgnoreCase() method, it returns true.

Output :

Strings are not equal
Strings are equal
Strings are not equal
Strings are equal

Ads