How do you specify a byte literal in Java?

JavaByteLiterals

Java Problem Overview


If I have a method

void f(byte b);

how can I call it with a numeric argument without casting?

f(0);

gives an error.

Java Solutions


Solution 1 - Java

You cannot. A basic numeric constant is considered an integer (or long if followed by a "L"), so you must explicitly downcast it to a byte to pass it as a parameter. As far as I know there is no shortcut.

Solution 2 - Java

You have to cast, I'm afraid:

f((byte)0);

I believe that will perform the appropriate conversion at compile-time instead of execution time, so it's not actually going to cause performance penalties. It's just inconvenient :(

Solution 3 - Java

You can use a byte literal in Java... sort of.

    byte f = 0;
    f = 0xa;

0xa (int literal) gets automatically cast to byte. It's not a real byte literal (see JLS & comments below), but if it quacks like a duck, I call it a duck.

What you can't do is this:

void foo(byte a) {
   ...
}

 foo( 0xa ); // will not compile

You have to cast as follows:

 foo( (byte) 0xa ); 

But keep in mind that these will all compile, and they are using "byte literals":

void foo(byte a) {
   ...
}

    byte f = 0;

    foo( f = 0xa ); //compiles

    foo( f = 'a' ); //compiles

    foo( f = 1 );  //compiles

Of course this compiles too

    foo( (byte) 1 );  //compiles

Solution 4 - Java

If you're passing literals in code, what's stopping you from simply declaring it ahead of time?

byte b = 0; //Set to desired value.
f(b);

Solution 5 - Java

What about overriding the method with

void f(int value)
{
  f((byte)value);
}

this will allow for f(0)

Solution 6 - Java

With Java 7 and later version, you can specify a byte literal in this way: byte aByte = (byte)0b00100001;

Reference: http://docs.oracle.com/javase/8/docs/technotes/guides/language/binary-literals.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCharbelView Question on Stackoverflow
Solution 1 - JavaRobinView Answer on Stackoverflow
Solution 2 - JavaJon SkeetView Answer on Stackoverflow
Solution 3 - JavaRickHighView Answer on Stackoverflow
Solution 4 - JavaMike YockeyView Answer on Stackoverflow
Solution 5 - JavaBoris PavlovićView Answer on Stackoverflow
Solution 6 - JavaspiralmoonView Answer on Stackoverflow