Boolean Operators



Boolean data type variable can have only two values, true and false. Data size of boolean variable is one bit. Only one bit is sufficient to store two values(true and false). Boolean variable can't be assigned other values accept true or false.

Important ! true and false both are not keywords of java.


Example:

	 //file:bool.java
	 //www.jgyan.com
class bool
 {
   public static void main(String arg[])
     {
	   boolean b=true;
	   boolean c=false;
	   // Error: expected value is boolean but integer is assigned.
	   boolean d=1; 
	 }
 }
	

In above example variable b and c are right, but variable d has been assigned 1(integer value). Unlike c, in java integer are not treated as true.


Every logical expression in java return boolean value only. In c all non zero values are considered as true and zero is considered as false. But this is not same in java, only boolean value can be used as conditions.

Example:

//file:bool1.java
//www.jgyan.com
class bool1
 {
  public static void main(String arg[])
    {
	  boolean a=true;
	  // Expression will be evaluated and result(boolean) will be stored in b
	  boolean b= 12>13; 
	  
	  // we can assign direct true or false value in if, looping constructs and switch
	  if(true)
	   System.out.println("Always true case");
	  if(a==true)
	   System.out.println("A value is true");
	
	}
 
 }  
 




JVM provide boolean data type in the form of integer. For true value it uses 1 and for false it uses 0.

  //file:bool2.java
  //www.jgyan.com 
class bool2
 {
   public static void main(String arg[])
     {
	   boolean b=true;
	 }
 }
	

When we see byte code of above program. it will show that internally there is no boolean data type in JVM. It is managed by using integer.


Byte Code

Compiled from "bool.java"
class bool {
  bool();
    Code:
       0: aload_0      
       1: invokespecial #1                  // Method java/lang/Object."":()V
       4: return        

  public static void main(java.lang.String[]);
    Code:
       0: iconst_1     
       1: istore_1     
       2: return       
}
   

Byte code of main method shows that first iconst_1 will push constant 1 onto stack. Second instruction istore_1 will store value from store to first variable. Both instruction starting from 'i', which stands for integer.