具有 int 和 char 操作数的三元表达式的类型是什么?

2022-01-12 00:00:00 char java

我最近遇到了这样一种情况,第一个 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 被提升为 intSystem.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 符合此描述.xchar,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.

相关文章