Booleans Class in Java

JavaObject Oriented ProgrammingProgramming

The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean.

Following are the fields of the Boolean class −

  • static Boolean FALSE − This is the Boolean object corresponding to the primitive value false.
  • static Boolean TRUE − This is the Boolean object corresponding to the primitive value true.
  • static Class<Boolean> TYPE − This is the Class object representing the primitive type boolean.

Following are some of the methods of the Boolean class−

Sr.No.Method & Description
1boolean booleanValue()
This method returns the value of this Boolean object as a boolean primitive
2int compareTo(Boolean b)
This method compares this Boolean instance with another.
3boolean equals(Object obj)
This method returns true if and only if the argument is not null and is a Boolean object that represents the same boolean value as this object.
4static boolean getBoolean(String name)
This method returns true if and only if the system property named by the argument exists and is equal to the string "true".
5int hashCode()
This method returns a hash code for this Boolean object.
6static boolean parseBoolean(String s)
This method parses the string argument as a boolean.
7String toString()
This method returns a String object representing this Boolean's value.

Let us now see an example −

Example

 Live Demo

import java.lang.*;
public class Demo {
   public static void main(String[] args){
      Boolean val1, val2;
      val1 = new Boolean(true);
      val2 = new Boolean(true);
      boolean res = val1.equals(val2);
      System.out.println("Are both the Boolean values equal? = "+res);
   }
}

Output

Are both the Boolean values equal? = true

Let us now see another example−

Example

 Live Demo

import java.lang.*;
public class Demo {
   public static void main(String[] args){
      Boolean val1, val2;
      val1 = new Boolean(false);
      val2 = new Boolean(true);
      System.out.println("Value1 = "+val1);
      System.out.println("Value2 = "+val2);
      System.out.println("HashCode Value1 = "+val1.hashCode());
      System.out.println("HashCode Value2 = "+val2.hashCode());
      boolean res = val1.equals(val2);
      System.out.println("Are both the Boolean values equal? = "+res);
   }
}

Output

Value1 = false
Value2 = true
HashCode Value1 = 1237
HashCode Value2 = 1231
Are both the Boolean values equal? = false
raja
Updated on 02-Jan-2020 10:54:02

Advertisements