Java Boolean hashCode() Method
The hashCode() method of Boolean class returns the hash code for the specified Boolean object or the given Boolean value.
Syntax
- public int hashCode()
- public int hashCode(boolean value)
Parameters
The parameter ‘value’ represents the value to hash.
Overrides
The hashCode() method overrides hashcode in class object.
Return Value:
The hashCode () method returns a hash code value based on Boolean’s value.
- It returns 1231, if the Boolean’s value is true.
- It returns 1237, if the Boolean’s value is false.
Example 1
public class JavaBooleanHashCodeMethodExample1 { public static void main(String[] args) { Boolean b1 = true; //return the hash Code for true int val1 = b1.hashCode(); System.out.println("1. Hash code of true = "+val1); Boolean b2 = false; int val2 = b2.hashCode(); //print the hash code System.out.println("2. Hash code of false = "+val2); } }
Output
1. Hash code of true = 1231 2. Hash code of false = 1237
Example 2
import java.util.Scanner; public class JavaBooleanHashCodeMethodExample2 { public static void main(String[] args) { Scanner scanner= new Scanner(System.in); System.out.println("Are you above 18?"); Boolean b1= scanner.nextBoolean(); int val=b1.hashCode(); if(val==1231){ System.out.println("You are eligible."); } else{ System.out.println("Sorry! You are not eligible"); } } }
Output
Are you above 18? false Sorry! You are not eligible
Example 3
public class JavaBooleanHashCodeMethodExample3 { public static void main(String[] args) { boolean b1 =true; //primitive data type's object cannot be used to call Boolean class methods int val1 = b1.hashCode(); System.out.println("Hash code of true = "+val1); } }
Output
Error:(7, 22) java: boolean cannot be dereferenced
Example 4
public class JavaBooleanHashCodeMethodExample4 { static int i=1; public static void main(String[] args) { int val=Boolean.hashCode(true); System.out.println(i+ ". "+val); //for any value other than true it will return 1237 or false int val1=Boolean.hashCode(Boolean.parseBoolean("abc")); System.out.println(++i+ ". "+val1); } }
Output
1. 1231 2. 1237