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.
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.
byte b(int i) { return (byte) i; }
somewhere and statically import it. Then you can write f(b(10)).
Commented
Oct 11, 2013 at 18:56
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 :(
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
1
is an int literal, but double d = 1;
compiles just fine.
byte b(int i){}
, then b(1)
as long and less tricky than f=1
.
Commented
Aug 20, 2014 at 9:04
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);
public static final byte BYTE_MASK = ( byte )0xff;
byte BYTE_MASK = 0x000000ff;
lest I get some nasty sign extension bugs.
What about overriding the method with
void f(int value)
{
f((byte)value);
}
this will allow for f(0)
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