Boolean

Primitive Data Types

Boolean

🙋 Need help? Ask an expert now!

Boolean is a primitive data type that is used to represent a single true/false value. A boolean value can only hold one of two values, true or false. Other words such as "yes" or "no" will not compile and will result in a syntax error. The code below illustrates how boolean variables are declared and used.

BooleanDataTypeExample.java
package exlcode;
            
            public class BooleanDataTypeExample {
            
              // booleans can only be true or false
              public static boolean exampleVariableOne = true;
              public static boolean exampleVariableTwo = false;
              public static boolean exampleVariableThree = 5 > 4;
              public static boolean exampleVariableFour = 5 < 4;
            
              public static void main(String[] args) {
                System.out.println(exampleVariableOne);
                System.out.println(exampleVariableTwo);
                System.out.println(exampleVariableThree);
                System.out.println(exampleVariableFour);
              }
            }

We see in the code above that boolean values don't necessarily have to come out "true". For example "7>9" will be false, while "7<9" will be true. Boolean is extremely useful because it allows particular statements and methods to be executed only in certain situations based on whether the boolean statement is true or false. For this reason, it is one of the most important primitive data types.

Later on, we will examine comparing boolean values to each other and the role that plays with control flow statements.

Edit Me on GitHub!

Application Question

Which one of these is a valid boolean declaration?