How to convert Boolean to integer 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 Boolean to integer

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 given Boolean value is true then its number value will be 1; 0, otherwise.

Converting Boolean to integer

To convert a Boolean to an integer, check the Boolean value. If the given Boolean value is true then assign 1 to the integer variable, and if the given Boolean value is false then assign 0 to the integer variable.

Java program to convert Boolean to integer

This program converts a Boolean to an integer.

// Java program to convert Boolean to integer 
public class Main {
  public static void main(String[] args) {
    // Taking two boolean variables
    boolean a, b;
    a = true;
    b = false;

    // taking two int variables
    int x, y;

    // checking the condition and converting to booleans
    if (a)
      x = 1;
    else
      x = 0;

    if (b)
      y = 1;
    else
      y = 0;

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

Output

The output of the above program is:

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

Alternative Approach

Use the ternary operator to check and convert a Boolean value to an integer. Here is an example,

// Java program to convert Boolean to integer 
public class Main {
  public static void main(String[] args) {
    // Taking two boolean variables
    boolean a, b;
    a = true;
    b = false;

    // taking two int variables
    int x, y;

    // Converting boolean to integer
    // using ternary operator 
    x = a ? 1 : 0;
    y = b ? 1 : 0;

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

The output of the above example is:

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

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.