Year-End Discount: 10% OFF 1-year and 20% OFF 2-year subscriptions!

Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java

What is a boolean variable in Java?

Educative Answers Team

Tired of LeetCode? 😩

Learn the 24 patterns to solve any coding interview question without getting lost in a maze of LeetCode-style practice problems. Practice your skills in a hands-on, setup-free coding environment. 💪

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.

svg viewer
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 ©2022 Educative, Inc. All rights reserved

Tired of LeetCode? 😩

Learn the 24 patterns to solve any coding interview question without getting lost in a maze of LeetCode-style practice problems. Practice your skills in a hands-on, setup-free coding environment. 💪

Keep Exploring
Related Courses