The Boolean keyword in Java can be used in many contexts such as “boolean” primitive data type, Boolean class, Boolean wrapper object, Boolean expression, or Boolean operators, etc.
The Java Booleans are mostly used to apply conditional checks in the loops, ternary operators, or “if/else” statements to analyze the outcomes in different situations. This resultantly helps the developer to make decisions regarding the implemented code functionalities clearly.
Contents Overview
- What are Java Booleans?
- How to Declare a Boolean in Java?
- Understanding the “boolean” Primitive Data type in Java
- Boolean Operators in Java
- Boolean Logical Operators in Java
- Precedence of Logical Operators
- What is the Java Boolean Wrapper Class?
- What is the “parseBoolean()” Method in Java?
What are Java Booleans?
Boolean corresponds to a primitive data type that can have two return values. These values can be “true” or “false”.
How to Declare a Boolean in Java?
For declaring a boolean in Java, use the “boolean” keyword.
Syntax
boolean var_name = true/false;
Alternatively, it can also be declared via the following syntax:
boolean var_name;
var_name = true/false;
Here, “var_name” can be any custom variable and the return value is “true” or “false”.
Demonstration
Overview of the following code demonstration that declares a Boolean via the discussed approaches:
package jbArticles;
public class Javabooleans {
public static void main(String[] args) {
boolean val1 = true;
boolean val2;
val2 = false;
System.out.println(val1);
System.out.println(val2);
}}
In this code, initialize the first boolean directly and initialize the second boolean by first declaring it. After that, print both the booleans.
Output
Here, it can be seen that the declared booleans are returned appropriately.
Understanding the “boolean” Primitive Data type in Java
A “boolean” variable is one of Java’s 8 primitive data types. The boolean type can contain one bit of data, which represents the stored value as either “true” or “false”.
Boolean Operators in Java
Operator | Example | Outcome |
---|---|---|
Less than(<) | x < y | Returns true if “x” is less than “y”. Else, returns “false”. |
Greater than(>) | x > y | Gives true if “x” is greater than “y”. Otherwise, returns false. |
Equal to(==) | x == y | Retrievs true if “x” equals “y”. Else, returns false. |
Less than or Equal to(<=) | x <= y | Gives true if “x” is less than or equal to “y”. Otherwise, returns false. |
Greater than or Equal to(>=) | x >= y | It retrieves true if “x” is greater than or equivalent to “y”. Else, returns false. |
Not Equal to(!=) | x != y | Gives true if “x” does not equal “y”. Else, returns false. |
Boolean Logical Operators in Java
Operator | Example | Outcome |
---|---|---|
Logical Not(!) | Boolean x = true!x = false | Logically negates the boolean outcome. |
Logical AND(&) | x = true;y = false;x&y ==false | Gives true if both “x” and “y” are true. |
Logical OR(|) | x = true;y = false;x | y = true | Returns true if “x” or “y” or both are true. |
Logical exclusive OR XOR(^) | x = true;y = false;x ^ y = true | GIves true if one of the values i.e., “x” or “y” is true. |
Conditional OR(||) | x || yx = true;y = false;x || y = true | Retrieves the same outcome as that of the “|” operator except for if “x” is true, the operator retrieves true without checking “y”. |
Conditional AND(&&) | x && y | It returns the same output as that of the “&” operator except if “x” is false, the operator retrieves false without checking “y”. |
Precedence of Logical Operators
Following are the logical operators listed from higher to lower priority:
- !
- &
- ^
- |
- &&
- ||
Example 1: Implementing a Boolean Expression in Java
In this example, a boolean expression will be evaluated by building logic with the help of the comparison operators:
package jbArticles;
public class Javabooleans {
public static void main(String[] args) {
int a = 2;
int b = 4;
System.out.println(a > b);
System.out.println(a < b);
System.out.println(a == b);
}}
The code explanation is as follows:
- Initialize the given two values.
- After that, apply the comparison operators “>”, “<” and “==”, respectively as an expression.
- This resultantly returns the corresponding outcome based on the operator’s conditions.
Output
As analyzed, the Boolean values according to the applied expressions are returned.
A more convenient approach to evaluate the expressions and return the corresponding boolean values can be to specify the numbers directly, as demonstrated below:
Example 2: Applying the Logical Operators on the Java Booleans
In this code example, the logical operators will be applied to the defined Boolean values and the corresponding output will be returned:
package jbArticles;
public class Javabooleans {
public static void main(String[] args) {
boolean val1 = true;
boolean val2 = false;
System.out.println(val1 & val2);
System.out.println(val1 | val2);
System.out.println(!val2);
}}
Based on this block of code, consider the following steps:
- Initialize the given Boolean values.
- Now, use the logical operators “AND(&)”, “OR(|)” and “NOT(!)”, respectively to check if both the values are true, either of them is true and negate the latter value, respectively.
- Lastly, print the resultant outputs in each case individually.
Output
Example 3: Practical Scenario of Using Java Booleans to Check For the Prime Number Condition
This code example uses Java Booleans to analyze if the user input value is a prime number or not:
package jbArticles;
import java.util.Scanner;
public class Javabooleans {
public static void main(String[] args) {
int counter, val;
boolean x = true;
System.out.println("Input the number");
Scanner object = new Scanner(System.in);
val = object.nextInt();
for (int i = 2; i<= val/2; i++) {
counter = val%i;
if (counter == 0) {
x = false;
break;
}}
if(x)
System.out.println(val + " is a prime number");
else
System.out.println(val + " is not a prime number");
}}
In this block of code:
- Import the “java.util.Scanner” package to input data from the user.
- Specify the variables to be used and initialize a boolean value.
- Now, input the integer value from the user via the Scanner object and the “nextInt()” method.
- Apply the “for” loop to iterate through some numbers less than the user input number and use the modulus operator i.e., “%” to check if the user-input number is completely divisible by those numbers.
- Since the prime number is only divisible by itself, the resultant remainder is “0” in the case of complete divisibility which is the applied condition in the former “if” statement.
- In such a case i.e., complete divisibility, the Boolean value “false” is returned and the “else” statement executes.
- Otherwise, i.e., in the case of a number not divisible by the numbers, the number is prime, thereby invoking the “if” statement.
Output
From this output, it can be seen that the prime and non-prime numbers are evaluated accordingly.
What is the Java Boolean Wrapper Class?
The “Boolean” wrapper class is contained in the “java.lang” package. It is such that it wraps the primitive type boolean’s value in an object and comprises a single field having the type boolean.
Example: Utilizing the Boolean Wrapper Class to Create a Boolean Object in Java
The following code example uses this class to create Boolean instances comprising the Boolean values and return the outputs based on the passed values.
Syntax
Boolean obj = new Boolean(boolean val);
Boolean obj = new Boolean(String x);
In the above syntaxes, note that the object returns “true” if the passed value is not null and is equal, thereby ignoring the case sensitivity. Else, the Boolean value “false” is retrieved.
Now, move on to the implementation of utilizing the “Boolean” wrapper class to create Boolean objects:
package jbArticles;
public class Javabooleans {
public static void main(String[] args) {
Boolean val1 = new Boolean("true");
Boolean val2 = new Boolean("false");
Boolean val3 = new Boolean("xyz");
System.out.println(val1);
System.out.println(val2);
System.out.println(val3);
}}
According to this block of code, perform the below-given steps:
- Create three boolean objects utilizing the “new” keyword followed by the “Boolean()” constructor(comprising the boolean value as its argument).
- In the third object, an inappropriate value is also specified to analyze the corresponding output.
- Now, print all the objects returning the Boolean values.
Output
In this output, it can be implied that specifying an inappropriate value in the third Boolean object returns the Boolean outcome “false”.
What is the “parseBoolean()” Method in Java?
This particular method is used to transform a string into a Boolean without creating a Boolean object. This method works on the same principle as the Boolean class such that it returns “true” if the passed value is not null and is equal, thereby ignoring the case sensitivity. Else, the Boolean value “false” is retrieved.
Syntax
Boolean.parseBoolean(String val)
In this syntax, “val” refers to the value of type “String” comprising the value to be transformed into Boolean.
Return Value
This method gives the Boolean value “true” if the provided value equals “true” and retrieves “false” otherwise.
Example: Applying the “parseBoolean()” Method in Java
This demonstration implements the discussed method to parse the passed boolean values irrespective of the case sensitivity:
package jbArticles;
public class Javabooleans {
public static void main(String[] args) {
boolean val1 = Boolean.parseBoolean("false");
boolean val2 = Boolean.parseBoolean("true");
boolean val3 = Boolean.parseBoolean("FaLsE");
boolean val4 = Boolean.parseBoolean("TrUe");
boolean val5 = Boolean.parseBoolean("This condition is true!");
System.out.println(val1);
System.out.println(val2);
System.out.println(val3);
System.out.println(val4);
System.out.println(val5);
}}
In this snippet of code:
- Apply the “parseBoolean()” method to parse the passed Boolean values in lower case as well as in mixed cases i.e., upper and lower cases, respectively.
- Also, pass the Boolean value in a long string.
- Finally, print the Boolean values in each case individually.
Output
The last returned “false” Boolean output confirms that the Boolean value cannot be extracted from a longer string.
Note: A value other than “Boolean” also retrieves the Boolean outcome “false” demonstrated below:
Conclusion
Boolean corresponds to a primitive data type that comprises two return values i.e., “true” or “false” and for declaring a Java boolean, the “boolean” keyword is utilized. These Booleans are helpful to build the logic and can be utilized to evaluate a Boolean expression, in mathematical calculations, creating Boolean instances, etc.