Integer to byte casting in Java

前端 未结 5 778
有刺的猬
有刺的猬 2021-01-18 18:43

In Java we can do

byte b = 5;    

But why can\'t we pass same argument to a function which accepts byte

myObj         


        
相关标签:
5条回答
  • 2021-01-18 19:00

    Normally, converting an int to a byte without an explicit cast is not allowed.

    However, if the conversion is part of an assignment, and the value is a statically-known constant that will fit in the destination type, the compiler will perform the conversion automatically.

    This special behaviour is described in section 5.2 of the JLS. It is a special case that only applies to assignment; it does not apply to conversions in other contexts.


    Now that I think about it, the lack of auto-narrowing for arguments is probably to avoid issues with overload resolution. If I have methods #foo(short) and #foo(char), it's not clear which one foo(65) should call. You could have special rules to get around this, but it's easier to just require the caller to be explicit in all cases.

    0 讨论(0)
  • 2021-01-18 19:01

    Integer literals are by default int in Java. And in myObject.testByte(5); 5 is an integer literal which will be treated as int.

    As all you know Java is strictly types language, so it will not allow to assign an int to a byte. All you need to have explicit type-casting.

    0 讨论(0)
  • 2021-01-18 19:04

    Hard-coded initializer values are somewhat special in Java - they're assumed to have a coercion to the type of the variable you're initializing. Essentially, that first bit of code effectively looks like this:

    byte b = (byte) 5;
    

    If you did this...

    myObject.testByte((byte) 5);
    

    ...you wouldn't get that error, but if you don't do that, then the 5 is created by default as an int, and not automatically coerced.

    0 讨论(0)
  • 2021-01-18 19:15

    You must cast your argument 5 to type byte in your method testByte. Java looks specifically at the argument type.

    Change it to:

    myObject.testByte( (byte) 5);
    
    0 讨论(0)
  • 2021-01-18 19:22

    The reason is that when you are narrowing a primitive, you must explicitly make a cast - so you acknowledge a possible loss of data.

    To illustrate, when casting 5 there is no loss because the value is within the -128...127 byte value range, but consider a larger int value, say 300 - if you cast to byte, you must throw away some bits to make it fit into 8 bits.

    The topic is covered in full here.

    0 讨论(0)
提交回复
热议问题