C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Main: We test booleanToInt in the main method. When the boolean is false, we print 0 and when it is true we print 1.
Public, static: This method is public so it can be used throughout a program. It is static because it is not part of an object instance.
StaticJava program that converts boolean to int
public class Program {
public static int booleanToInt(boolean value) {
// Convert true to 1 and false to 0.
return value ? 1 : 0;
}
public static void main(String[] args) {
// Test our conversion method.
boolean value = false;
int number = booleanToInt(value);
System.out.println(number);
System.out.println(booleanToInt(true));
}
}
Output
0
1
Java program that causes error, casts boolean
public class Program {
public static void main(String[] args) {
// This does not compile.
boolean value = true;
int value2 = (int) value;
}
}
Output
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
Cannot cast from boolean to int
at Program.main(Program.java:6)
Tip: To achieve the best performance, avoiding conversions and branches is often the best option.