問題描述
我最近遇到了這樣一種情況,第一個(gè) syso() 字符工作正常,但在第二個(gè) 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 ?
}
}
我真的很想知道為什么它在第二個(gè) syso() 中打印 ascii 代碼?請(qǐng)幫忙
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
.
根據(jù) JLS第 15.25.2 節(jié)(強(qiáng)調(diào)和 [] 注意我的):
As per JLS section 15.25.2 (emphasis and [] note mine):
數(shù)值條件表達(dá)式的類型確定如下:
The type of a numeric conditional expression is determined as follows:
- 如果第二個(gè)和第三個(gè)操作數(shù)的類型相同,那么就是條件表達(dá)式的類型.
...
- 否則[如果上述規(guī)則都不成立],二進(jìn)制數(shù)值提升(§5.6.2)應(yīng)用于操作數(shù)類型,條件表達(dá)式的類型是第二個(gè)和第三個(gè)操作數(shù)的提升類型.
其中 二進(jìn)制數(shù)字促銷的相關(guān)規(guī)則是(強(qiáng)調(diào)我的):
加寬原語轉(zhuǎn)換(第 5.1.2 節(jié))適用于轉(zhuǎn)換以下規(guī)則中指定的一個(gè)或兩個(gè)操作數(shù):
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
如果任一操作數(shù)是 double 類型,則另一個(gè)操作數(shù)將轉(zhuǎn)換為 double.
If either operand is of type double, the other is converted to double.
否則,如果任一操作數(shù)為浮點(diǎn)類型,則將另一個(gè)轉(zhuǎn)換為浮點(diǎn)類型.
Otherwise, if either operand is of type float, the other is converted to float.
否則,如果其中一個(gè)操作數(shù)是 long 類型,則另一個(gè)將轉(zhuǎn)換為 long.
Otherwise, if either operand is of type long, the other is converted to long.
否則,兩個(gè)操作數(shù)都轉(zhuǎn)換為 int 類型.
因此在:
char x = ...;
int m = ...;
表達(dá)式條件?m : x
被提升為 int
和 System.out.println(int)
被調(diào)用,并將其打印為數(shù)字.
The expression condition ? m : x
is promoted to int
, and System.out.println(int)
is called, and it prints it as a number.
您必須將 m
或整個(gè)表達(dá)式顯式轉(zhuǎn)換為 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 的規(guī)則之一(我在上面省略了)是:
As for your condition ? x : 0
and condition ? 0 : x
forms, one of the rules (that I omitted above) from 15.25.2 is:
- 如果其中一個(gè)操作數(shù)是 T 類型,其中 T 是 byte、short 或 char,而另一個(gè)操作數(shù)是 int 類型的常量表達(dá)式(第 15.28 節(jié)),其值可在類型 T 中表示,則條件表達(dá)式是 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.
這篇關(guān)于具有 int 和 char 操作數(shù)的三元表達(dá)式的類型是什么?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!