What is a boolean variable in Java?

A boolean variable in Java can be created using the boolean keyword. Unlike C++, a numerical value cannot be assigned to a boolean variable in Java – only true or false can be used. The strings “true” or “false” are​ displayed on the console when a boolean variable is printed.

Using the boolean keyword
Using the boolean keyword

java.lang.Boolean

The wrapper class java.lang.Boolean can be used to create a boolean variable as well. However, instead of creating an object using the keyword new, a value of true or false is directly assigned to Boolean (with an uppercase B). If a comparison with another string is required, or if the methods of the String class need to be used, the toString() method returns the boolean value as a string.

public class bool{
public static void main(String[] args){
// Using primitive boolean variable:
boolean x = true;
if(x)
System.out.println("x = " + x);
// Using java.lang.Boolean:
Boolean y = false;
if(y.toString().equals("false"))
System.out.println("y = " + y);
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved