Why 'int' by default, but not 'byte'? [duplicate]

萝らか妹 提交于 2021-01-29 09:53:24

问题


Explain me please, why, when I write 4 overloaded methods and call it => it chooses method with 'int' as default, but not 'byte', which is closer/better, because it can storage values from -127 to 128?

class Main {
    public static void method(short s) {
        System.out.println("short");
    }

    public static void method(byte b) {
        System.out.println("byte");
    }

    public static void method(int i) {
        System.out.println("int");
    }

    public static void method(long l) {
        System.out.println("long");
    }

    public static void main(String[] args) {
        // put your code here
        method(10);
    }
}

回答1:


Because the Java Language Specification says so.

Section 3.10.1. Integer Literals says:

An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).

So your numeric literal 10 is of type int.




回答2:


It's because default type of number's literal is integer. To specify long literal you should add L at the end. To specify byte literal - you should cast the value



来源:https://stackoverflow.com/questions/61467032/why-int-by-default-but-not-byte

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