beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Compare boolean values in java – compareTo() Method

By Chaitanya Singh | Filed Under: java.lang.Boolean

Description

Program to compare boolean values.

Example

In this example we are going to see how to compare two boolean values by using compareTo() method of Boolean class.

class CompareBooleanValues {
 
  public static void main(String[] args) {
    // Creating Objects of Boolean class
    Boolean bObj = new Boolean("true");
    // Case does not matter
    Boolean bObj2 = new Boolean("FaLsE");
    Boolean bObj3 = new Boolean("true");
 
    // Comparing values using compareTo() method
    /* public int compareTo(Boolean b): It returns zero if 
     * the object represents the same boolean value as
     * the argument; a positive value if this object 
     * represents true and the argument represents false; 
     * and a negative value if this object represents 
     * false and the argument represents true
     */
    System.out.println(bObj.compareTo(bObj2));//+ve
    System.out.println(bObj.compareTo(bObj3));//Zero
    System.out.println(bObj2.compareTo(bObj3));//-ve
  }
}

Output:

1
0
-1

Reference:
compareTo() Method – Javadoc

Enjoyed this post? Try these related posts

  1. Cast Boolean Object to boolean in Java – booleanValue() Method
  2. Convert String Object to Boolean Object in Java
  3. Convert String to boolean primitive in Java: parseBoolean() method
  4. Boolean.hashCode() Method in Java
  5. Convert boolean Primitive to Boolean object in Java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap