Home »
Java programming language
Java String compareToIgnoreCase() Method with Example
Java String compareToIgnoreCase() Method: Here, we are going to learn about the compareToIgnoreCase() method with example in Java.
Submitted by IncludeHelp, on February 15, 2019
String compareToIgnoreCase() Method
compareToIgnoreCase() is a String method in Java and it is used to compare two strings by ignoring the case's sensitivity.
If both strings are equal (without considering the case-sensitivity) – it returns 0, otherwise, it returns a value less than 0 or greater than 0 based on the first dissimilar characters difference.
Syntax:
int string1.compareToIgnoreCase(string2);
Here, string1 and string2 are the strings to be compared, and it returns an integer value that is 0, less than 0 or greater than 0.
Example:
Input:
str1 = "Hello world!"
str2 = "Hello world!"
Output:
0
Input:
str1 = "Hello world!"
str2 = "HELLO WORLD!"
Output:
0
Input:
str1 = "Hello world!"
str2 = "Hi guys!!!"
Output:
-4
Java code to compare strings using String.compareToIgnoreCase() method
public class Main
{
public static void main(String[] args) {
String str1 = "Hello world!";
String str2 = "Hello world!";
String str3 = "HELLO WORLD!";
System.out.println("str1 and str2 = " + str1.compareToIgnoreCase(str2));
System.out.println("str1 and str3 = " + str1.compareToIgnoreCase(str3));
System.out.println("str2 and str3 = " + str2.compareToIgnoreCase(str3));
//checking with the condition
if(str1.compareToIgnoreCase(str2)==0){
System.out.println("str1 is equal to str2");
}
else{
System.out.println("str1 is not equal to str2");
}
if(str1.compareToIgnoreCase(str3)==0){
System.out.println("str1 is equal to str3");
}
else{
System.out.println("str1 is not equal to str3");
}
if(str2.compareToIgnoreCase(str3)==0){
System.out.println("str2 is equal to str3");
}
else{
System.out.println("str2 is not equal to str3");
}
}
}
Output
str1.compareToIgnoreCase(str2) = 0
str1.compareToIgnoreCase(str3) = 0
str2.compareToIgnoreCase(str3) = 0
str1 is equal to str2
str1 is equal to str3
str2 is equal to str3
public class Main
{
public static void main(String[] args) {
String str1 = "Hello world!";
String str2 = "Hi guys!!!";
if(str1.compareToIgnoreCase(str2)==0){
System.out.println("str1 is equal to str2");
}
else{
System.out.println("str1 is not equal to str2");
}
}
}
Output
str1 is not equal to str2