Java - Boolean Class compareTo() Method

Boolean class compareTo() method: Here, we are going to learn about the compareTo() method of Boolean class with its syntax and example. By Preeti Jain Last updated : March 17, 2024

Boolean class compareTo() method

  • compareTo() method is available in java.lang package.
  • compareTo() method is used to check equality or inequality for this Boolean object against the given Boolean object mathematically or in other words, we can say this method is used to compare two Boolean objects.
  • compareTo() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • compareTo() method may throw an exception at the time of comparing the Boolean object.
    NullPointerException: When the specified argument is null.

Syntax

public int compareTo(Boolean value2);

Parameters

  • Boolean value2 – represents the Boolean object to compare with.

Return Value

The return type of this method is int - it returns a boolean value based on the following cases,

  • It returns 0, if value1 is equal to value2.
  • It returns positive value if value1 represent true and value2 represent false.
  • It returns negative value, if value1 represent false and value2 represent true.

Example

// Java program to demonstrate the example 
// of compareTo(Boolean value2) method of Boolean class

public class CompareToOfBooleanClass {
    public static void main(String[] args) {
        // Variables initialization
        boolean b1 = true;
        boolean b2 = false;

        // Boolean instance 
        Boolean value1 = new Boolean(b1);
        Boolean value2 = new Boolean(b2);

        // It compare two Boolean objects and placed the result 
        // in another variable (compare) of integer type
        int compare = value1.compareTo(value2);

        // Display result
        System.out.println("value1.compareTo(value2): " + compare);
        System.out.println();

        if (compare == 0)
            System.out.println("value1 is equal to value2");
        else if (compare < 0)
            System.out.println("value1 is less than value2");
        else
            System.out.println("value1 is greater than value2");
    }
}

Output

value1.compareTo(value2): 1

value1 is greater than value2

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.