为什么默认是'int',而不是'byte'?[重复]

问题描述 投票:0回答:2

请解释一下,为什么我写了4个重载方法并调用它=>它选择了'int'作为默认值的方法,而不是'byte',这是比较接近的,因为它可以存储-127到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);
    }
}
java int byte overloading
2个回答
6
投票

因为 Java语言规范 说的。

3.10.1. 整数字 说。

一个整数字 属于 long 如果它的后缀是一个ASCII字母 Ll (ell);否则,它 属于 int (§4.2.1).

所以你的数字文字 10 属于 int.


0
投票

这是因为默认的数字文字类型是整数。要指定长的文字,你应该在最后加上L。如果要指定字节文字,你应该在最后加上L。

© www.soinside.com 2019 - 2024. All rights reserved.