Java Tutorial - Java boolean








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;/*ww w.j  a va 2s.co  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;

    int i = b;

  }
}

If you try to compile the program, the following error message will be generated by compiler.