Home / Programs / Write a java program to compare two strings lexicographically.
🚀 Programming Example

Write a java program to compare two strings lexicographically.

👁 1,654 Views
💻 Practical Program
📘 Step Learning
Write a java program to compare two strings lexicographically.

💻 Program Code

public class Exercise {
public static void main(String[] args)
    {
        String str1 = "This is Exercise 1";
        String str2 = "This is Exercise 2";

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

        // Compare the two strings.
        int result = str1.compareTo(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 + "\"");
        }
    }
}

                        

🖥 Program Output

String 1: This is Exercise 1
String 2: This is Exercise 2
"This is Exercise 1" is less than "This is Exercise 2"
Press any key to continue . . .
                            

📘 Explanation

None
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.