[java] Convert boolean to int in Java

What is the most accepted way to convert a boolean to an int in Java?

This question is related to java casting boolean int

The answer is


Lets play trick with Boolean.compare(boolean, boolean). Default behavior of function: if both values are equal than it returns 0 otherwise -1.

public int valueOf(Boolean flag) {
   return Boolean.compare(flag, Boolean.TRUE) + 1;
}

Explanation: As we know default return of Boolean.compare is -1 in case of mis-match so +1 make return value to 0 for False and 1 for True


If you want to obfuscate, use this:

System.out.println( 1 & Boolean.hashCode( true ) >> 1 );  // 1
System.out.println( 1 & Boolean.hashCode( false ) >> 1 ); // 0

If you use Apache Commons Lang (which I think a lot of projects use it), you can just use it like this:

int myInt = BooleanUtils.toInteger(boolean_expression); 

toInteger method returns 1 if boolean_expression is true, 0 otherwise


public int boolToInt(boolean b) {
    return b ? 1 : 0;
}

simple


import org.apache.commons.lang3.BooleanUtils;
boolean x = true;   
int y= BooleanUtils.toInteger(x);

Using the ternary operator is the most simple, most efficient, and most readable way to do what you want. I encourage you to use this solution.

However, I can't resist to propose an alternative, contrived, inefficient, unreadable solution.

int boolToInt(Boolean b) {
    return b.compareTo(false);
}

Hey, people like to vote for such cool answers !

Edit

By the way, I often saw conversions from a boolean to an int for the sole purpose of doing a comparison of the two values (generally, in implementations of compareTo method). Boolean#compareTo is the way to go in those specific cases.

Edit 2

Java 7 introduced a new utility function that works with primitive types directly, Boolean#compare (Thanks shmosel)

int boolToInt(boolean b) {
    return Boolean.compare(b, false);
}

boolean b = ....; 
int i = -("false".indexOf("" + b));

That depends on the situation. Often the most simple approach is the best because it is easy to understand:

if (something) {
    otherThing = 1;
} else {
    otherThing = 0;
}

or

int otherThing = something ? 1 : 0;

But sometimes it useful to use an Enum instead of a boolean flag. Let imagine there are synchronous and asynchronous processes:

Process process = Process.SYNCHRONOUS;
System.out.println(process.getCode());

In Java, enum can have additional attributes and methods:

public enum Process {

    SYNCHRONOUS (0),
    ASYNCHRONOUS (1);

    private int code;
    private Process (int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }
}

int val = b? 1 : 0;

If true -> 1 and false -> 0 mapping is what you want, you can do:

boolean b = true;
int i = b ? 1 : 0; // assigns 1 to i.

public static int convBool(boolean b)
{
int convBool = 0;
if(b) convBool = 1;
return convBool;
}

Then use :

convBool(aBool);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to casting

Subtracting 1 day from a timestamp date Cast object to interface in TypeScript TypeScript enum to object array Casting a number to a string in TypeScript Hive cast string to date dd-MM-yyyy Casting int to bool in C/C++ Swift double to string No function matches the given name and argument types C convert floating point to int PostgreSQL : cast string to date DD/MM/YYYY

Examples related to boolean

Convert string to boolean in C# In c, in bool, true == 1 and false == 0? Syntax for an If statement using a boolean Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() Ruby: How to convert a string to boolean Casting int to bool in C/C++ Radio Buttons ng-checked with ng-model How to compare Boolean? Convert True/False value read from file to boolean Logical operators for boolean indexing in Pandas

Examples related to int

How can I convert a char to int in Java? How to take the nth digit of a number in python "OverflowError: Python int too large to convert to C long" on windows but not mac Pandas: Subtracting two date columns and the result being an integer Convert bytes to int? How to round a Double to the nearest Int in swift? Leading zeros for Int in Swift C convert floating point to int Convert Int to String in Swift Converting String to Int with Swift