问题
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 letterL
orl
(ell); otherwise it is of typeint
(§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