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.
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
View all Courses