Why is an explicit cast not needed here?

核能气质少年 提交于 2021-02-04 17:10:06

问题


class MyClass {
    void myMethod(byte b) {
        System.out.print("myMethod1");
    }

    public static void main(String [] args) {
        MyClass me = new MyClass();
        me.myMethod(12);
    }
}

I understand that the argument of myMethod() being an int literal, and the parameter b being of type byte, this code would generate a compile time error. (which could be avoided by using an explicit byte cast for the argument: myMethod((byte)12) )

class MyClass{
    byte myMethod() {
        return 12;
    }

    public static void main(String [ ] args) {
        MyClass me = new MyClass();
        me.myMethod();
    }
}

After experiencing this, I expected that the above code too would generate a compile time error, considering that 12 is an int literal and the return type of myMethod() is byte. But no such error occurs. (No explicit cast is needed: return (byte)12; )

Thanks.


回答1:


Java supports narrowing in this case. From the Java Language Spec on Assignment Conversion:

A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.




回答2:


From Java Primitive Data Type reference:

byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).

Try returning 128 : ))




回答3:


This will work byte b = 4 as long as value is within the range, but if you try something like byte b = 2000 you would get compiler error because it is out of range. 12 is in within range so you aren't getting error.



来源:https://stackoverflow.com/questions/13915143/why-is-an-explicit-cast-not-needed-here

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