Java
Boolean
Integer
Programming
Code Conversion

Convert boolean to int in Java

Codemia Knowledge Hub ·

Java has no built-in method to convert a boolean to an int, so you write the conversion yourself. The usual answer is the ternary operator: int myInt = myBool ? 1 : 0;.

Boolean and int in Java

  • Boolean: the boolean type stores one of two values, true or false. It is mainly used for logical conditions and control flow in if statements, loops and switch cases.
  • Integer: the int type is a 32-bit signed two’s complement integer that stores values from -$2^{31}$ to 231−12^{31}-1. It is used for counting, indexing, arithmetic and much more.

Ways to convert boolean to int

  1. Ternary operator: the most straightforward method. It evaluates the boolean and picks a value based on it.
java
boolean myBool = true;
int myInt = myBool ? 1 : 0;

If myBool is true, myInt becomes 1; otherwise it becomes 0.

  1. if-else statement: same logic as the ternary, but more verbose. It can be preferable for clarity or to match coding standards.
java
1boolean myBool = false;
2int myInt;
3
4if (myBool) {
5    myInt = 1;
6} else {
7    myInt = 0;
8}
  1. Bitwise operators: rarely used for this and mostly theoretical, because it makes the code hard to understand.
java
boolean myBool = true;
int myInt = myBool & true ? 1 : 0;

When converting boolean to int is useful

  • Interoperability with other systems: some systems or APIs require numeric input where the value is logically a boolean.
  • Statistical summaries: calculations where booleans represent occurrences or flags.
  • Storage optimization: in rare cases, storing integers may be more space-efficient or more compatible with system requirements than booleans.

Comparing the methods

MethodCode ExampleReadabilityPerfomance
Ternary Operatorint myInt = myBool ? 1 : 0;HighVery High
If-Else Statementif (myBool) { myInt = 1; } else { myInt = 0; }HighHigh
Bitwise Operatorsint myInt = myBool & true ? 1 : 0;LowModerate

The ternary operator is the most concise choice. An if-else statement can read better inside complex conditional logic. Pick whichever fits your codebase's standards.


Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms