Java boolean type
In this chapter you will learn:
- What is Java boolean type
- Values for Java boolean type
- Literals for Java boolean type
- Java Boolean class
- Example - Java boolean type
- Example - How to create boolean Literals
Description type
Java has a boolean type for logical values. This is the type returned by all relational operators.
Value
It can have only one of two possible values, true
or false
.
Literals
Boolean literals are only two logical
values: true
and false
.
The values of true
and false
do
not convert into any numerical representation.
The true literal in Java does not equal 1
, nor does the false literal equal 0
.
In Java, they can only be assigned to variables declared as boolean
.
Boolean class
The Boolean class wraps a primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean.
Boolean class has the methods for converting a boolean to a String and a String to a boolean.
Example
Here is a program that demonstrates the boolean
type:
public class Main {
public static void main(String args[]) {
boolean boolVariable;
boolVariable = false;//from w w w. j a v a2 s . c o m
System.out.println("b is " + boolVariable);
boolVariable = true;
System.out.println("b is " + boolVariable);
}
}
Output:
Example 2
The true literal in Java does not equal 1
, nor does the false literal equal 0
.
In Java, they can only be assigned to variables declared as boolean
.
public class Main {
public static void main(String[] argv) {
boolean b = true;
/*w w w .ja v a2 s.c o m*/
int i = b;
}
}
If you try to compile the program, the following error message will be generated by compiler.
Next chapter...
What you will learn in the next chapter:
- What is Java char type
- Size of Java char type
- Value range for Java char type
- Java char type literals
- Example - Java char type
- How to create char Literals
- Example - Store unicode into a char