Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Java
  3. Question
Java

Is Java cast boolean to int a good idea?

Asked by Alex Gonzalez Oct 6, 2022 1.2K views 1 answer
Share

About this question

Note: Even though this contains Python, it's not specifically about Python. It's more generally about expecting a certain behaviour from a language which is not necessarily the same across compilers/interpreters.


So I came across this question:


How do I convert a boolean to int in Python? Can I just do it(mybool)?


My response was to write:


1 if mybool else 0

My reasoning was that blindly "casting" to int would rely on the internal implementation of the compiler/interpreter. And who knows, if running through a different interpreter int(mybool) might return something else. Explicitly stating the value for a "truthy" value and for a "falsey" value will always yield the expected behaviour.


This is surely something which one can consider for most languages.


Am I too picky about this? I know that I have written int(mybool) myself in the past. And that question made me think: Was that okay? Given that this is a very common case, are the compilers/interpreters smart enough to do "the right thing" for bool -> int conversions?


Now, for the special case for duck-typing languages like Python, int(mybool) might certainly be a really bad idea, but other languages are a bit clearer on their typing.

Your answer

1 Answer

More Java discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Java Blogs

Guides, tips and career advice on Java from JanBask experts.