Trusted answers to developer questions

What is a boolean variable in Java?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

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);
}
}

RELATED TAGS

java
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?