HomeLanguagesJavaJava Program to convert boolean to integer

Java Program to convert boolean to integer

Given a boolean value, the task is to convert this boolean value into an integer value in Java. Examples:

Input: boolean = true
Output: 1

Input: boolean = false
Output: 0

Approach:

  • Get the boolean value to be converted.
  • Check if boolean value is true or false
  • If the boolean value is true, set the integer value as 1.
  • Else if the boolean value is false, set the integer value as 0.

Below is the implementation of the above approach: Example 1: When boolean value is true 

Java




// Java Program to convert boolean to integer
 
public class GFG {
 
    public static void main(String[] args)
    {
 
        // The boolean value
        boolean boolValue = true;
 
        // The expected integer value
        int intValue;
 
        // Check if it's true or false
        if (boolValue) {
            intValue = 1;
        }
        else {
            intValue = 0;
        }
 
        // Print the expected integer value
        System.out.println(
            boolValue
            + " after converting into integer = "
            + intValue);
    }
}


Output:

true after converting into integer = 1

The time complexity is O(1), which means it will take a constant amount of time to execute, regardless of the input size.

The auxiliary space used by the program is also constant.

Example 2: When boolean value is false 

Java




// Java Program to convert boolean to integer
 
public class GFG {
 
    public static void main(String[] args)
    {
 
        // The boolean value
        boolean boolValue = false;
 
        // The expected integer value
        int intValue;
 
        // Check if it's true or false
        if (boolValue) {
            intValue = 1;
        }
        else {
            intValue = 0;
        }
 
        // Print the expected integer value
        System.out.println(
            boolValue
            + " after converting into integer = "
            + intValue);
    }
}


Output:

false after converting into integer = 0
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32533 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6913 POSTS0 COMMENTS
Nicole Veronica
12029 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12132 POSTS0 COMMENTS
Shaida Kate Naidoo
7043 POSTS0 COMMENTS
Ted Musemwa
7280 POSTS0 COMMENTS
Thapelo Manthata
7000 POSTS0 COMMENTS
Umr Jansen
6986 POSTS0 COMMENTS