Java Booleans Explained [Easy Examples]


JAVA

Author: Bashir Alam
Reviewer: Deepak Prasad

 

Introduction to Java booleans

Java Boolean is an inbuilt class that wraps are used for wrapping the value of primitive data type, i.e. boolean in an object. The boolean class contains two values, i.e. true or false. Java provides a wrapper class Boolean in java.lang package. The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field, whose type is boolean. In this tutorial, we will learn about java booleans in detail. We will see how we can use booleans in conditions, loops, and functions. Moreover, we will also cover some of the java operators that return a boolean value, along with examples. All in all, this will be one of the detailed tutorials about java booleans.

 

Getting started with Java booleans

The Boolean class is simply a wrapper class for the primitive type boolean. It wraps the boolean primitive value to an object. An object of type Boolean contains a single field whose type is boolean. The simple syntax of creating a boolean object from  a boolean class looks like this;

Boolean y = new Boolean("boolean argument");

Now let us create a boolean object and then use it in our java code. See the example below:

// class
public class Main  { 
   // main method
   public static void main(String[] args)  { 
       // creating java booleans object
       Boolean fristCase1 = new Boolean("TRUE");
       Boolean fristCase2 = new Boolean("True");
       Boolean fristCase3 = new Boolean("true");
       Boolean fristCase4 = new Boolean("False");
       Boolean fristCase5 = new Boolean("avce");
 
       // printing the object and java booleans
       System.out.println("Case 1 :"+fristCase1);
       System.out.println("Case 2 :"+fristCase2);
       System.out.println("Case 3 :"+fristCase3);
       System.out.println("Case 4 :"+fristCase4);
       System.out.println("Case 5 :"+fristCase5);
   }
}  

Output:

Case 1 :true
Case 2 :true
Case 3 :true
Case 4 :false
Case 5 :false

Notice that we get true for the first three cases which means that the java boolean class is not case sensitive. It will return true does not matter which alphabetic case we use.  And it will return false if we provide an argument other than true, that is why for the last case we get false.

 

Logical operators and Java booleans

We know that the logical operators in Java return booleans value. You can learn more about logical operators. There are three logical operators in Java which are as follow:

  • && ; Return true if both the conditions are true.
  • ||; Return true if any of the conditions are true.
  • !; Return true if the condition is not true

Now, in this section, we will take examples of each of these operators and get a boolean value.

 

Example-1 AND operator and Java booleans

AND operator returns boolean value true if both the conditions are satisfied, otherwise, it will return the boolean value false. See the example below which uses the logical AND operator.

// class
public class Main  {  
    // main method
    public static void main(String[] args)  {  
    //   logical AND operator and java booleans
    System.out.println("case 1: " + (true && true));
    System.out.println("case 2: " + (false && true));
    System.out.println("case 3: " + (true && false));
    System.out.println("case 4: " + (false && false));
    }
}   

Output:

case 1: true
case 2: false
case 3: false
case 4: false

Notice that the logical AND operator only returns true if both the conditions are true, else it returns false.

 

Example-2 OR operator and Java booleans

Java logical OR operator returns true if any of the conditions are true and only returns false if all the conditions are false. See the example below:

// class
public class Main  {  
    // main method
    public static void main(String[] args)  {  
    //   logical OR operator and java booleans
    System.out.println("case 1: " + (true || true));
    System.out.println("case 2: " + (false || true));
    System.out.println("case 3: " + (true || false));
    System.out.println("case 4: " + (false || false));
    }
}   

Output:

case 1: true
case 2: true
case 3: true
case 4: false

Notice that we only get false when both of the conditions were False.

 

Example-3 NOT operator and Java booleans

NOT operator simply reverses the condition, which means if the condition is true, it will return false and if the condition is false it will return true. See the example below:

// class
public class Main  {  
    // main method
    public static void main(String[] args)  {  
    //   logical NOT operator and java booleans
    System.out.println("case 1: " + !(true));
    System.out.println("case 2: " + !(false));
    }
}  

Output:

case 1: false
case 2: true

Notice that we get true for the False condition and vice versa.

 

Rational operators and Java booleans

Relational operator refers to the relationships that values or operands can have with one another. Java provides 6 relational operators for comparing numbers and characters. They are mostly used for comparison purposes. After the comparison, they return the result in boolean datatype. The rational operators in Java are listed below:

  • ==: Return true if both the operands are equal.
  • != ; Return true if both the operands are not equal.
  • < ; Return true if left-hand side operand is less than right side one.
  • > ; Return true if right-hand side operand is less than left side one.
  • <=; Return true if left side operand is less than or equal to right side one.
  • >= ; Return true if right side operand is less than or equal to left side one.

In this section, we will take these rational operations and see how and when they return java booleans.

 

Example-1 Equal and not equal assignment operators and Java booleans

Equal to the operator (==) return true if both the operands are equal. It can be used to compare lists, int, float dict, strings, and other data types. While not equal to (!=) operator returns true if both of the operands are not equal. It can also be used to compare various data types.

Now let us take an example and see how they are used to compare data types. See the example below:

// class
public class Main  {  
    // main method
    public static void main(String[] args)  {  
    //   logical equal to operator and java booleans
    System.out.println("Equal to operator;");    
    System.out.println("case 1: " + (3==3));
    System.out.println("case 2: " + (3==5));
    System.out.println("case 3: " + ("Bashir"=="Bashir"));
    // logical not equal to and java booleans
    System.out.println("Not equal to operator:");
    System.out.println("case 1 : " + (3!=5));
    System.out.println("case 2: " + (3!=3));
    System.out.println("case 2: " + ("Bashir"!="Bashir"));
    }
}   

Output:

Equal to operator;
case 1: true
case 2: false
case 3: true
Not equal to operator:
case 1 : true
case 2: false
case 2: false

 

Example-2 Greater than or less than operators and Java booleans

Greater than (>) operator returns true if the left side is greater than the right side one else, it returns false. Similarly, the less than (<) operator returns true if the left side is smaller than the right side one, else it will also return false.

See the example below which uses these operators.

// class
public class Main  {  
    // main method
    public static void main(String[] args)  {  
    //   greater than operator and java booleans
    System.out.println("Greater than operator;");    
    System.out.println("case 1: " + (3>3));
    System.out.println("case 2: " + (5>3));
    // Less than operator and java booleans
    System.out.println("Less than operator:");
    System.out.println("case 1 : " + (3<3));
    System.out.println("case 2: " + (3<5));

    }
}   

Output:

Greater than operator;
case 1: false
case 2: true
Less than operator:
case 1 : false
case 2: true

Notice that we get the result accordingly.

 

Java booleans in conditional statements

One of the important uses of java booleans is in conditional statements. If the condition is true, the java statements inside the condition will be executed and if the condition is false then none of the statements inside the condition will be executed. So the java booleans are important parts of if-else statements. In this section, we will be discussing how the java booleans control the if-else statements in the java programming language.

 

Example-1 Direct use of java booleans

First, let us directly use the java booleans in our conditional statements so it will give us a depth understanding of how it works in if-else statements. See the example below:

// class
public class Main  {  
    // main method
    public static void main(String[] args)  {  
    // direct use of java boolens
    if(true){
        System.out.println("The condition is true!!");
    }
    else{
        System.out.println("The condition is false!!");
    }
 }  
} 

Output:

The condition is true!!

Notice that the first condition was true so it was executed. Now if we make the first condition false, then the else statement will be executed. See the example below:

 

Example-2 Using conditions that return Java booleans

We already had discussed some of the java operators that return booleans in a couple of sections above. Now, let us see how we can use those operators in java conditions and executed the required statements only. See the example below:

// class
public class Main  {  
    // main method
    public static void main(String[] args)  {  
    // variables
    int a = 3;
    int b = 4;
    int c = 6;
    // java booleans in conditional statements
    if ( a > b && b > c){
        System.out.println("a is the greater then others!");
    }
    else if( b> a && a>c ){
        System.out.println("b is the greater then others!");
    }
    else{
        System.out.println("c is the greater then others!");

    }
 }  
} 

Output:

c is the greater then others!

Notice that the operators in the if and else if statements, return false because the conditions were false and it only executes the last statement.

 

Java booleans in while loop

Java while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. ... If the condition evaluates to true then we will execute the body of the loop and go to update expression inside the loop. In this section let us use java while loop with java booleans.

 

Example-1 Direct use of java booleans in while loop

If we use direct true in the while loop without any break statement or condition, it will be an infinity loop and if we use direct false in our while loop, then the loop will never be executed. See the example below which uses direct true boolean in while loop:

// class
public class Main  {  
    // main method
    public static void main(String[] args)  {  
    while(true){
        System.out.println("True");
    }
 }  
} 

This is an infinity loop because the condition is never going to be false and we don't have any break statements as well. This kind of loop is prohibited in any programming language because it returns unexpected values. It is always recommended to use either break or conditional statements inside loops.

Now let us see what will happens if we use direct false booleans value while loop. See the example below:

// class
public class Main  {  
    // main method
    public static void main(String[] args)  {  
    while(false){
        System.out.println("False");
    }
 }  
} 

This time we will get an error because we had used a direct the false boolean value and java will through an error saying that the code inside the loop is not reachable. See the error below:

Java Booleans Explained [Easy Examples]

 

Example-2 using condition in while loop

Now let us use a condition that returns true if it is true and returns false if it becomes false. See the example below:

// class
public class Main  {  
    // main method
    public static void main(String[] args)  {  
        // vairable
        int a = 0;
    while(a<10){
        System.out.println("Counting....."+ a);
        // increment a
        a++;
    }
 }  
} 

Output:

Counting.....0
Counting.....1
Counting.....2
Counting.....3
Counting.....4
Counting.....5
Counting.....6
Counting.....7
Counting.....8
Counting.....9

Notice that as the condition was true, the loop was executing and as soon as the condition becomes false, the loop stops executing.

 

Summary

In Java, the boolean keyword is a primitive data type. It is used to store only two possible values, either true or false. It specifies 1-bit of information and its "size" can't be defined precisely. The boolean keyword is used with variables and methods. Its default value is false. It is generally associated with conditional statements. In this tutorial, we learned about java booleans in detail.

We learned how we can create a java boolean object from the boolean class in java by taking examples. Moreover, we also learned about the java operators that return boolean values depending on the condition and we also discussed how booleans play important role in java while loop. All in all, this tutorial, contains all the information that you need to start working with java booleans.

 

Further Reading

Java booleans
Java booleans documentation
Java operators

 

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment