Martin Martin - 2 months ago 18
Java Question

convert from boolean to byte in java

I need to set byte value as method parameter. I have boolean variable

isGenerated
, that determines the logic to be executed within this method. But I can pass directly boolean as byte parameter this is not allowed and can't be cast in java. So the solution I have now looks like this:

myObj.setIsVisible(isGenerated ? (byte)1 : (byte)0);


But it seems odd for me. Maybe some better solution exists to do this?

Answer

your solution is correct.

if you like you may avoid one cast by doing it the following way:

myObj.setIsVisible((byte) (isGenerated ? 1 : 0 ));

additionally you should consider one of the following changes to your implementation:

  • change your method to something like setVisiblityState(byte state) if you need to consider more than 2 possible states

  • change your method to setIsVisible(boolean value) if your method does what it's looking like