Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert from boolean to byte in java

Tags:

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?

like image 480
Martin Avatar asked Aug 18 '14 09:08

Martin


People also ask

How do you convert boolean to Java?

To convert String to Boolean, use the parseBoolean() method in Java. The parseBoolean() parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

Can we convert byte to string in Java?

Given a Byte value in Java, the task is to convert this byte value to string type. One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.


2 Answers

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

like image 141
PrR3 Avatar answered Sep 19 '22 10:09

PrR3


You can use this solution. I found it on this very useful page

boolean vIn = true;
byte vOut = (byte)(vIn?1:0);
like image 42
Federico Traiman Avatar answered Sep 17 '22 10:09

Federico Traiman