Java boolean Keyword Tutorial

In this article, We will learn about the boolean keyword in Java.

In Java language, Boolean is used to declare a variable as a boolean type. This represents only either true or false(zero or one).

In Java language, the default boolean value is initialized with false;

the boolean keyword can be used with

Variables
Method parameters
Method return types

Please note that the size of boolean in Java is not precisely defined and it depends upon the Java Virtual Machine (JVM).

1. Java boolean syntax

//1. variable boolean isActive = false; //2. method parameters public void setActive( boolean active ) { //code here } return boolean public boolean isActive() { //code here }

2). Java Boolean class

We have a class java.lang.Boolean in Java. It is a wrapper class provided to wrap boolean primitive value. It has a single field of type boolean.

We can assign boolean primitive values to Boolean objects directly.

In java, there is a feature called autoboxing in Java where primitive values are automatically converted to their wrapper classes.

Boolean class

Boolean bool = new Boolean(true); //or Boolean bool = true; //autoboxing

3). Declare a boolean method

access_modifier return_type method_name { return return_type; } Example public boolean IsActive() { return true; }

4). Java Boolean example

public class BooleanExample { public static void main(String args[]) { int age = 20; boolean eligible = false; if (age > 18 && age < 25) { eligible = true; } else { eligible = false; } System.out.println("Candidate are eligible to apply the post : " + eligible); } } output: Candidate are eligible to apply the post : true

In this article, we have seen the Java boolean Keyword with Examples. All source code in the article can be found in the GitHub repository.