Java String compareTo() method

In this program, You will learn how to implement String compareTo() method in Java.

if (a.compareTo(b)) { }

Example: How to implement String compareTo() method in Java

Run it Now
import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        Scanner sc = new Scanner(;
        String a, b;
        int i;

        System.out.print("Enter First String :");
        a = sc.nextLine();
        System.out.print("\nEnter Second String :");
        b = sc.nextLine();

        i = a.compareTo(b);

        if (i == 0) {
            System.out.print("\nStrings are equal");
        } else {
            System.out.print("\nStrings are not equal");



Enter First String :ABC
Enter Second String :abc
Strings are not equal