The boolean keyword has following two usages in Java:
- boolean data type
- boolean return type of a method
The boolean keyword is a data type that is used when declaring a variable. The possible values of a boolean variable are true or false.
boolean b1 = true; boolean b2 = false;
It is also used as a return type for a method. If a method is supposed to return either true or false, then the return type of this method can be declared as boolean as shown below:
public boolean isEven(int num){ if(num%2 == 0) return true; else return false; }
Example: boolean data type
class JavaExample{ public static void main(String args[]){ //boolean variable can only hold true or false boolean isTrue = true; boolean isFalse = false; int num = 99; System.out.print("Is given number even: "); if(num%2 == 0) System.out.print(isTrue); else System.out.print(isFalse); } }
Output:
Is given number even: false
Example: boolean return type
class JavaExample{ public static boolean isEven(int num){ if(num%2 == 0) return true; else return false; } public static void main(String args[]) { int num = 99; if(isEven(num)) //if method returns true System.out.println("Given number is even"); else //if method returns false System.out.println("Given number is odd"); } }
Output:
Given number is odd