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
booleantype stores one of two values,trueorfalse. It is mainly used for logical conditions and control flow in if statements, loops and switch cases. - Integer: the
inttype is a 32-bit signed two’s complement integer that stores values from-$2^{31}$to . It is used for counting, indexing, arithmetic and much more.
Ways to convert boolean to int
- Ternary operator: the most straightforward method. It evaluates the boolean and picks a value based on it.
If myBool is true, myInt becomes 1; otherwise it becomes 0.
if-elsestatement: same logic as the ternary, but more verbose. It can be preferable for clarity or to match coding standards.
- Bitwise operators: rarely used for this and mostly theoretical, because it makes the code hard to understand.
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
| Method | Code Example | Readability | Perfomance |
| Ternary Operator | int myInt = myBool ? 1 : 0; | High | Very High |
| If-Else Statement | if (myBool) { myInt = 1; } else { myInt = 0; } | High | High |
| Bitwise Operators | int myInt = myBool & true ? 1 : 0; | Low | Moderate |
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.
Related reading
- Convert Branch and Bound loop to use Java Stream API
- Convert character to ASCII numeric value in java
- Convert Enum to String
- Convert Enumeration to a Set/List
- Convert Existing Eclipse Project to Maven Project
- Convert float to String and String to float in Java
- Convert from enum ordinal to enum type
- Convert from java.util.date to JodaTime
System design interview problems on this topic
- Design an API Rate Limiter: solution and walkthrough
- Design a Distributed Messaging System: solution and walkthrough
- Design an Online Payment Service: solution and walkthrough
- Design a Key Value Store: solution and walkthrough

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 courseData 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.