2014-01-24 51 views
0
public class Casting { 
    public static void main(String[] args){ 
     int I = 1; 
     long L = 1; 
     float F = 1; 
     double D = 1; 

     L = I; // int always fits into long, no problem here 
     I = L; // Error: Type mismatch: cannot convert from long to int 
       // long not always can fit into int, so explicit casting is required. Seems logical. 
       // But at the moment magnitude of L fits into I, and casting can be done without truncation 

     F = L; // This doesn't produce any error, and casting is done implicitly. 
       // In this case magnitude of L also fits into F 

    } 
} 
public class Casting { 
    public static void main(String[] args){ 
     int I = 1; 
     long L = 1; 
     float F = 1; 
     double D = 1; 

     L = I; // int always fits into long, no problem here 
     I = L; // Error: Type mismatch: cannot convert from long to int 
       // long not always can fit into int, so explicit casting is required. Seems logical. 
       // But at the moment magnitude of L fits into I, and casting can be done without truncation 

     F = L; // This doesn't produce any error, and casting is done implicitly. 
       // In this case magnitude of L also fits into F 

    } 
} 

因此,問題是 - 爲什麼在I = L的情況下,當L的大小足夠小以適合I時,它必須是明確地做了,但是在F = L的情況下,其中L的大小也適合於F,則該鑄造可以隱式完成而不會產生錯誤。顯式強制轉換爲int並隱式強制轉換爲浮點型

我的意思是在這兩種情況下右操作數的大小可能不適合左操作數。因此,爲什麼在一種情況下(I = L),鑄造必須明確進行,而在另一種情況下(F = L)它可以隱式完成? 儘管將long var隱式轉換爲int var似乎比將long var隱式轉換爲float var更自然(假設值足夠小以適合彼此)

希望我能夠表達我想要理解的內容。

+0

這將需要每次檢查,看看它是否適合。 –

+1

將一個long分配給一個int時,可能會丟失幅度(實際上,該值可能會變爲負數 - 即完全錯誤...)。當將一個長分配給一個浮點數時,你「僅」使用精度,因爲這個數值總是適合的。另請參閱http://stackoverflow.com/questions/2781086/loss-of-precision-int-float-or-double(這是指int,但類似地適用於很長時間) – Marco13

回答

4

Long.MAX_VALUE =(2^63)-1
Float.MAX_VALUE = 2^127
所以,龍價值總適合成浮點值。
編譯器不會分析代碼中的實際值。它從不驗證該值是否合適。

相關問題