How to convert boolean to integer in Java

In this tutorial, we will learn how to convert boolean to integer in java ? Let’s understand what  is boolean and integer?

In Java, Boolean and Integer are data types: Boolean represents the two values ‘true‘ and ‘false‘, while Integer represents numerical values(0, 1, 2).

some key points about booleans in Java:
1.Declare a boolean variable and initialize it with a value (true or false).
2.Boolean values are commonly used in control flow statements such as  if , while, and for.

Convert boolean to integer in java

To convert a Boolean to an integer in programming, we follow a simple logic:
All zeros are considered ‘false’, while any positive or negative number is considered ‘true’. Thus, if a Boolean value is true, we convert it to the integer 1; if it is false, we convert it to 0.

To convert a Boolean to an integer, you simply check the Boolean value: assign 1 to the integer variable if the value is true, and assign 0 if the value is false.

Java program to convert boolean to integer:

public class Main {
    public static void main(String[] args) {
        // Define two boolean variables
        boolean a = true;
        boolean b = false;

        // Define two integer variables
        int x;
        int y;

        // Convert boolean 'a' to integer 'x'
        if (a) {
            x = 1; // If 'a' is true, set 'x' to 1
        } else {
            x = 0; // If 'a' is false, set 'x' to 0
        }

        // Convert boolean 'b' to integer 'y'
        if (b) {
            y = 1; // If 'b' is true, set 'y' to 1
        } else {
            y = 0; // If 'b' is false, set 'y' to 0
        }

        //Print the values
        System.out.println("Boolean values = a: " + a + ", b: " + b);
        System.out.println("Integer values = x: " + x + ", y: " + y);
    }
}

OUTPUT:-

Boolean values = a: true, b: false
Integer values = x: 1, y: 0

you can also read about – how to convert stack to an array in java.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top