w3resource logo


Introduction to Java Programming

Java String : compareToIgnoreCase() Method

Secondary Nav

public int compareToIgnoreCase(String str)

The compareToIgnoreCase() method compares two strings lexicographically, ignoring case differences. This method returns an integer whose sign is that of calling compareTo with normalized versions of the strings where case differences have been eliminated by calling Character.toLowerCase(Character.toUpperCase(character)) on each character.

Note: This method does not take locale into account, and will result in an unsatisfactory ordering for certain locales. The java.text package provides collators to allow locale-sensitive ordering.

Java Platform: Java SE 8

Syntax :

compareToIgnoreCase(String str)

Parameters:

Name Description Type
str the String to be compared. int

Return Value :
a negative integer, zero, or a positive integer as the specified String is greater than, equal to, or less than this String, ignoring case considerations.

Return Value Type: int

Example : Java String compareToIgnoreCase() Method

The following example shows the usage of java String() method.

public class Exercise {

public static void main(String[] args)
    {
        System.out.println();
        String str1 = "This is Python exercise 1";
        String str2 = "This is Ruby Exercise 1";

System.out.println("String 1: " + str1);
System.out.println("String 2: " + str2); 

        // Compare the two strings.
int result = str1.compareToIgnoreCase(str2);

        // Display the results of the comparison.
if (result < 0)
        {
System.out.println("\"" + str1 + "\"" +
" is less than " +
                "\"" + str2 + "\"");
        }
else if (result == 0)
        {
System.out.println("\"" + str1 + "\"" +
" is equal to " +
                "\"" + str2 + "\"");
        }
else // if (result > 0)
        {
System.out.println("\"" + str1 + "\"" +
" is greater than " +
                "\"" + str2 + "\"");
        }
    }
}

Output:

String 1: This is Python exercise 1                    
String 2: This is Ruby Exercise 1                      
"This is Python exercise 1" is less than "This is Ruby 
Exercise 1"

Java Code Editor:







Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program