w3resource logo


Java Programming Exercies

Java String Exercises: Compare two strings lexicographically, ignoring case differences

Secondary Nav

Java String : Exercise-6 with Solution

Write a java program to compare two strings lexicographically, ignoring case differences.

Java Code:

public class Exercise6 {

public static void main(String[] args)
    {
        String str1 = "This is exercise 1";
        String str2 = "This is 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 exercise 1                                            
String 2: This is Exercise 1                                            
"This is exercise 1" is equal to "This is Exercise 1" 

Java Practice online:

public class Exercise6 {

public static void main(String[] args)
    {
        String str1 = "This is exercise 1";
        String str2 = "This is 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 + "\"");
        }
    }
}



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

Solve these problems:

Java: How to convert a string to an integer in Java?

C#: Loops in c#

SQL: JOIN using more than 5 tables