Saturday, October 25, 2025
HomeLanguagesJavaBoolean compareTo() method in Java with examples

Boolean compareTo() method in Java with examples

The compareTo() method of Boolean class is a built in method in Java which is used to compare the given Boolean instance with the current instance.

Syntax:

BooleanObject.compareTo(Boolean a)

Parameters: It takes a Boolean value a as parameter which is to be compared with the current instance.

Return Type: The return type of the function is int. It returns:

  • 0 if ‘a’ is equal to ‘b’,
  • a negative value if ‘a’is false and ‘b’ is true,
  • a positive value if ‘a’ is true and ‘b’ is false.

Below are programs to illustrate the compareTo() method of Boolean class:

Program 1:




// Java code to implement
// compareTo() method of Boolean class
  
class Lazyroar {
  
    // Driver method
    public static void main(String[] args)
    {
  
        // Boolean object
        Boolean a = new Boolean(true);
  
        // Boolean object
        Boolean b = new Boolean(true);
  
        // compare method
        System.out.println(a + " comparing with " + b
                           + " = " + a.compareTo(b));
    }
}


Output:

true comparing with true = 0

Program 2:




// Java code to implement
// compareTo() method of Java class
  
class Lazyroar {
  
    // Driver method
    public static void main(String[] args)
    {
  
        // Boolean object
        Boolean a = new Boolean(true);
  
        // Boolean object
        Boolean b = new Boolean(false);
  
        // compare method
        System.out.println(a + " comparing with " + b
                           + " = " + a.compareTo(b));
    }
}


Output:

true comparing with false = 1

Program 3:




// Java code to implement
// compareTo() method of Java class
  
class Lazyroar {
  
    // Driver method
    public static void main(String[] args)
    {
  
        // Boolean object
        Boolean a = new Boolean(false);
  
        // Boolean object
        Boolean b = new Boolean(true);
  
        // compare method
        System.out.println(a + " comparing with " + b
                           + " = " + a.compareTo(b));
    }
}


Output:

false comparing with true = -1
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS