2011-06-05 93 views
3
class Test { 
    void m1(byte b) { 
    System.out.print("byte"); 
    } 

    void m1(short s) { 
    System.out.print("short"); 
    } 

    void m1(int i) { 
    System.out.print("int"); 
    } 

    void m1(long l) { 
    System.out.print("long"); 
    } 

    public static void main(String [] args) { 
    Test test = new Test(); 
    test.m1(2); 
    } 
} 

输出结果是:int。为什么jvm会考虑带int参数的方法?为什么带int参数的方法被认为是数值?

+0

为了完整起见,你可以的'M1(浮动)'和'M1(双)'添加到您的例子。 – 2011-06-05 09:46:49

回答

9

因为整型文字的类型是Java中的int。如果你想打电话给其他人,你需要明确的转换。 (或者,如果你要拨打的long版本添加一个后缀L

见细节JLS Lexical Structure§3.10.1整数字面

+0

优秀的参考。 – 2011-06-05 09:42:08

4
Data  Type   Default Value (for fields) 
byte  0 
short  0 
int   0 
long  0L 
float  0.0f 
double  0.0d 
char  '\u0000' 
String (or any object)  null 
boolean false 

所以,你需要明确地给数作为参数传递给你想要

适当的基本类型。如果你尝试给

public static void main(String [] args) { 
    Test test = new Test(); 
    test.m1(2L); 
    } 

输出将是long

shortbyte(隐含为int)的情况下,您需要将该类型转换为

public static void main(String [] args) { 
     Test test = new Test(); 
     test.m1((short)2); 
     } 

参考:Primitive Data Types in Java

相关问题