Convert boolean to int in Java

int myInt = myBoolean ? 1 : 0;

^^

PS : true = 1 and false = 0


int val = b? 1 : 0;

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));

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

simple