In java boolean datatype is used to take value true or false. This is the type that is returned by all relational operators, as in the case a<b.
boolean is also required by conditional expressions that govern the control statement such as if and for.
In previous we learn about primitive datatype which give introduction of basic java’s data type. We know that boolean only take the value either true or false. Unlike in C where the boolean also takes 0 and 1 to determine false and, true this is the not case in java.
- Example
The below example shows error generated and error free code to know boolean takes which types of value.
class BoolConcept { public static void main(String args[]) { int i; boolean b; for(i=0;i<5;i++) { if(i%2)//this gives error. { //b=i%2; //it gives error because int can't convert to boolean System.out.println("Value Of Boolean Is "+b+" Non Zero"); } else { System.out.println("Value Of Boolean Is "+b+" Zero"); } } } }
- Generated error code from above code.
BoolConcept.java:9: error: incompatible types: int cannot be converted to boolean if(i%2) ^ 1 error
The below code is valid
class BoolConcept { public static void main(String args[]) { int i; boolean b; for(i=0;i<5;i++) { if(b=(i%2!=0)) { //b=i%2; //it gives error because int can't convert to boolean System.out.println("Value Of Boolean Is "+b+" Non Zero"); } else { System.out.println("Value Of Boolean Is "+b+" Zero"); } } } }
- OutPut
Value Of Boolean Is false Zero Value Of Boolean Is true Non Zero Value Of Boolean Is false Zero Value Of Boolean Is true Non Zero Value Of Boolean Is false Zero