Home »
Java »
Java Articles
How to convert integer to Boolean in Java?
By IncludeHelp Last updated : February 4, 2024
Boolean and Integer are data types in Java. Boolean represents two values true and false while integer represents the numbers.
Understanding the logic to convert integer to Boolean
In the programming, all zeros are considered as false and all negative and positive numbers are considered as true. We will simply check the condition if the number is zero then it will be false; true, otherwise.
Converting integer to Boolean in Java
To convert an integer to Boolean, check the number whether it is 0 or not. If the number is 0 then assign false, and if the number is not 0 then assign true.
Java program to convert integer to Boolean
This program converts an integer value to a Boolean value.
// Java program to convert integer to boolean
public class Main {
public static void main(String[] args) {
// An integer variable
int a = 0;
// a boolean variable
boolean b;
// Checking the condition
if (a >= 1) {
b = true;
} else {
b = false;
}
// Printing the values
System.out.println("Value of a : " + a);
System.out.println("Value of b : " + b);
// Reassigning value to integer variable
a = 100;
// Checking the condition
if (a >= 1) {
b = true;
} else {
b = false;
}
// Printing the values
System.out.println("Value of a : " + a);
System.out.println("Value of b : " + b);
}
}
Output
The output of the above program is:
Value of a : 0
Value of b : false
Value of a : 100
Value of b : true
Alternative Approach
Use the ternary operator to check and convert an integer to Boolean. Below is an example,
// Java program to convert integer to boolean
public class Main {
public static void main(String[] args) {
// An integer variable
int a = 0;
// a boolean variable
boolean b;
// Converting integer to boolean
// using the condition operator
b = a == 0 ? false : true;
// Printing the values
System.out.println("Value of a : " + a);
System.out.println("Value of b : " + b);
// Reassigning value to integer variable
a = 100;
// Converting integer to boolean
// using the condition operator
b = a == 0 ? false : true;
// Printing the values
System.out.println("Value of a : " + a);
System.out.println("Value of b : " + b);
}
}
The output of the above example is:
Value of a : 0
Value of b : false
Value of a : 100
Value of b : true