2011-06-05 96 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

相關問題