Java boolean keyword

Java boolean keyword is used to declare a variable as a boolean type which represents only one of two possible values i.e. either true or false.

In java, by default boolean variables are initialized with false.

boolean keyword can be used with –

  • Variables
  • Method parameters
  • Method return types

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

1. Java boolean syntax

The boolean keyword can be used as shown in given examples.

//1. variable
boolean isMajorVersion = false;

//2. method parameters
public void setValid( boolean valid ) {
	//code
}

//3. method return type
public boolean isValid() {
	//code
}

2. Java Boolean class

We have a class java.lang.Boolean (with ‘B’ in capital) in Java. Boolean class is a wrapper class provided to wrap boolean primitive value. It has a single field of type boolean.

We can assign a boolean primitive values to Boolean object directly. It is called autoboxing in Java where primitive values are automatically converted to their wrapper classes.

Boolean b = new Boolean( true );

//or

Boolean b = true;	//autoboxing

3. Java boolean example

Java program to show the usage of boolean keyword.

public class Main 
{
    public static void main(String[] args) 
    {
        boolean condition = true;
        
        if(condition) {
            System.out.println("Condition is true");
        } else {
            System.out.println("Condition is false");
        }
        
        Boolean condObj = condition;
        
        System.out.println(condObj.booleanValue());
    }
}

Program output.

Condition is true
true

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode