What is the most accepted way to convert a boolean to an int in Java?
Hello,
int myInt = (myBoolean)?1:0 ;
^^
PS : true = 1 and false = 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.
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;
}
}
public interface StackOverflow {
public String askQuestionAndReturnTheBestAnswer(String question);
}
public class ConvertionUtils {
public static int convertBooleanToIntInAMostAcceptableWay(StackOverflow stackOverflow, boolean value) {
assert stackOverflow != null;
if (value == true) {
return stackOverflow.askQuestionAndReturnTheBestAnswer(
"Which integer value is the most acceptable for boolean \"true\" in Java?");
} else {
return stackOverflow.askQuestionAndReturnTheBestAnswer(
"Which integer value is the most acceptable for boolean \"false\" in Java?");
}
}
}
I think I don't need to post the implementation of StackOverflow interface.
Best Regards
Dr. Dr. Sheldon Lee Cooper
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.