問題描述
編譯器的某些功能讓我感到困惑(使用 Eclipse 的 Oracle JDK 1.7).
Certain functionality of the compiler puzzles me (Oracle JDK 1.7 using Eclipse).
所以我有這本書說 char 原語需要顯式轉換為 short 和 byte,這一切都是有道理的,因為數據類型的允許范圍不重疊.
So I've got this book that says char primitive needs to be explicitly cast to short and byte and this all makes sense due the data types' allowed ranges don't overlap.
換句話說,下面的代碼可以工作(但如果沒有顯式類型轉換就無法工作):
In other words below code works (but wouldn't work without the explicit type casts):
char c = '&';
byte b = (byte)c;
short s = (short)c;
打印 b 或 s 正確顯示數字 38,它是 Unicode 中 (&) 的數字等價物.
Printing b or s correctly displays the number 38, which is the numeric equivalent of (&) in Unicode.
這讓我想到了我的實際問題.為什么以下方法也有效?
byte bc = '&';
short sc = '&';
System.out.println(bc); // Correctly displays number 38 on the console
System.out.println(sc); // Correctly displays number 38 on the console
現在我肯定會理解以下內容(也可以):
Now I would certainly understand the following (which works too):
byte bt = (byte)'&';
System.out.println(bt); // Correctly displays number 38 on the console
但是這種沒有編譯器警告的字符到字節(和短的)潛行轉換"對我來說似乎不合適.
But this no-compiler-warning char to byte (and short) "sneak conversion" doesn't seem right to me.
誰能解釋一下,為什么允許這樣做?
原因可能在于 '<char>'
本身的解釋,因此它實際上不會進入 char 原始狀態,而是作為數字(八進制或十六進制等)值?
Could the reason be in the interpretation of the '<char>'
itself, so that it doesn't actually ever get to a char primitive state but is handled as a numeric (octal or hexadecimal etc) value?
推薦答案
基本上,賦值轉換規范指定
另外,如果表達式是一個常量表達式(§15.28)輸入 byte、short、char 或 int:
In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:
如果類型為變量是 byte、short 或 char,以及常量的值表達式可以用變量的類型來表示.
A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
您的 '&'
正是 byte、short、char 或 int 類型的常量表達式".
這篇關于Java - 為什么 char 不應該被隱式轉換為字節(和短)原語?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!