How do you specify a byte literal in Java?

ε祈祈猫儿з 提交于 2019-12-17 05:40:55

问题


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.


回答1:


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.




回答2:


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 :(




回答3:


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



回答4:


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);



回答5:


What about overriding the method with

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

this will allow for f(0)




回答6:


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



来源:https://stackoverflow.com/questions/5193883/how-do-you-specify-a-byte-literal-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!