簡體   English   中英

Java integer到短轉換規則

[英]Java integer to short conversion rules

在代碼中,只有第一種情況(整數變量到 short)有編譯錯誤(從 int 到 short 的有損轉換)。 為什么其他情況(整數文字短而最終 integer 變量短)沒有同樣的編譯錯誤?

public class Test
{   
    public static void main(String[] args)
    {
        short shortNum = 0;
        
        //integer variable to short
        int intNum = 12;
        shortNum = intNum;
        
        //integer literal to short
        shortNum = 12;

        //final integer variable to short
        final int finalNum = 12;
        shortNum = finalNum;
    }
}

將答案視為評論:

short shortNum = 0;

//integer variable to short
int intNum = 12;
shortNum = intNum; //doesn't work, because casting primitives is required any time you are going from a larger numerical data type to a smaller numerical data type.
        
//integer literal to short
shortNum = 12; //This is not integer literal per se, you're initializing your short variable with 12, which fits in short data type, so it's short.

//final integer variable to short
final int finalNum = 12; //your variable is final, and according to Java Language Specification, if final variable's value fits into the type you're casting it, then no explicit cast is needed.
shortNum = finalNum;

答案在這篇文章中: Type cast issue from int to byte using final keyword in java

如果 Java 知道該數字是常數並且適合另一種類型,那么您可以使用它。

在非常量值的情況下,您無法知道變量將如何演變......在這種情況下,為了保護,它不會允許類型更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM