問題描述
我最近遇到了這樣一種情況,第一個 syso() 字符工作正常,但在第二個 syso() 中它正在打印 ASCII 代碼.
I recently come accross the scenario where in first syso() charcter is working fine but in second syso() it is printing ASCII code.
public class Test{
public static void main(String[] args) {
char x = 'A';
char y= 'B';
int m = 0;
System.out.println(true ? x : 0);//Working fine prints A
System.out.println(true ? y : 0);//Working fine prints B
System.out.println(false ? 0 : y);//Working fine prints B
System.out.println(false ? m : x);// Here it prints 65 why ?
}
}
我真的很想知道為什么它在第二個 syso() 中打印 ascii 代碼?請幫忙
I really want to know why it is printing ascii code in second syso() ? Please help
推薦答案
問題出在 false 的類型上?m : x
,最終是 int
,而不是 char
.
The issue is in the type of false ? m : x
, which ends up being int
, not char
.
根據 JLS第 15.25.2 節(強調和 [] 注意我的):
As per JLS section 15.25.2 (emphasis and [] note mine):
數值條件表達式的類型確定如下:
The type of a numeric conditional expression is determined as follows:
- 如果第二個和第三個操作數的類型相同,那么就是條件表達式的類型.
...
- 否則[如果上述規則都不成立],二進制數值提升(§5.6.2)應用于操作數類型,條件表達式的類型是第二個和第三個操作數的提升類型.
其中 二進制數字促銷的相關規則是(強調我的):
加寬原語轉換(第 5.1.2 節)適用于轉換以下規則中指定的一個或兩個操作數:
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
如果任一操作數是 double 類型,則另一個操作數將轉換為 double.
If either operand is of type double, the other is converted to double.
否則,如果任一操作數為浮點類型,則將另一個轉換為浮點類型.
Otherwise, if either operand is of type float, the other is converted to float.
否則,如果其中一個操作數是 long 類型,則另一個將轉換為 long.
Otherwise, if either operand is of type long, the other is converted to long.
否則,兩個操作數都轉換為 int 類型.
因此在:
char x = ...;
int m = ...;
表達式條件?m : x
被提升為 int
和 System.out.println(int)
被調用,并將其打印為數字.
The expression condition ? m : x
is promoted to int
, and System.out.println(int)
is called, and it prints it as a number.
您必須將 m
或整個表達式顯式轉換為 char
,例如:
You'd have to explicitly cast m
or the whole expression to a char
, e.g.:
System.out.println((char)(false ? m : x));
或者:
System.out.println(false ? (char)m : x);
至于你的條件?x : 0
和 條件 ?0 : x
形式,15.25.2 的規則之一(我在上面省略了)是:
As for your condition ? x : 0
and condition ? 0 : x
forms, one of the rules (that I omitted above) from 15.25.2 is:
- 如果其中一個操作數是 T 類型,其中 T 是 byte、short 或 char,而另一個操作數是 int 類型的常量表達式(第 15.28 節),其值可在類型 T 中表示,則條件表達式是 T.
0 符合此描述.x
是 char
,0 適合 char
,因此條件的類型是 char
和字符被打印出來了.
0 fits this description. x
is a char
, 0 fits in a char
, the type of the conditional is therefore char
and the character is printed.
這篇關于具有 int 和 char 操作數的三元表達式的類型是什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!