我正在阅读Java问题,然后我发现了这个问题。 我无法理解为什么这个代码 -
public class File
{
public static void main(String[] args)
{
System.out.println('H'+'I');
}
}
输出为145 并为此代码 -
public class File
{
public static void main(String[] args)
{
System.out.print('H');
System.out.print('I');
}
}
输出为HI。
在第一种情况下,我知道输出是添加了'H'和'I'的ASCII值,但对于第二种情况,它不显示ASCII值,为什么会这样? 谢谢!
答案 0 :(得分:2)
As described in JLS Sec 15.18:
If the type of either operand of a + operator is String, then the operation is string concatenation. ...
The binary + operator performs addition when applied to two operands of numeric type, producing the sum of the operands.
In the first case, you've got two chars (not strings), so they are widened to ints, and added, and then passed to System.out.print(int)
to be printed.
In the second case, you are invoking the System.out.print(char)
method, which prints the char
as a character. You invoke this twice, so you get two chars.