为什么在System.out.println()中不增加字符? [英] Why doesn't a character increment in System.out.println()?
问题描述
char char1 ='a';
System.out.println(char1); // prints char 1
System.out.println(char1 + 1); // prints char 1
System.out.println(char1 ++); // prints char 1
System.out.println(char1 + = 1); // prints incremented char1
char1 + = 1;
System.out.println(char1); // prints increment char1
在上面的例子中,为什么不使用(char1 + 1) )打印增量字符,但另外两个?
首先,我假设, c $ c> System.out.println 工程,你真的指定:
='a';
EDIT
响应问题的改变( char1 + 1; =>
char1 + = 1;
)看到问题。
输出为
a
98
b
显示 98
,因为char a
被提升为 int
(二进制数字促销)以添加1.因此 a
变为97
但是, char1 + =
1;
或 char1 ++
不执行二进制数字促销,因此可按预期工作。
扩大原始转换(§5.1.2)适用于转换或
两个操作数由以下规则指定:
如果任一操作数的类型为double,则另一个转换为double。
否则,如果任一操作数的类型为float,则另一个操作数将转换为
为float。
否则, ,另一个是
转换为long。
否则两个操作数转换为int类型。
(强调我)
char char1 = 'a';
System.out.println(char1); //prints char 1
System.out.println(char1+1); //prints char 1
System.out.println(char1++); //prints char 1
System.out.println(char1+=1); //prints incremented char1
char1 += 1;
System.out.println(char1); //prints incremented char1
In the above, why doesn't (char1+1) or (char++) print the incremented character but theother two do?
First, I'm assuming that because you say the increment in System.out.println
works, that you have really specified:
char char1 = 'a';
EDIT
In response to the change of the question (char1+1;
=> char1 += 1;
) I see the issue.
The output is
a
98
b
The 98
shows up because the char a
was promoted to an int
(binary numeric promotion) to add 1. So a
becomes 97 (the ASCII value for 'a'
) and 98 results.
However, char1 += 1;
or char1++
doesn't perform binary numeric promotion, so it works as expected.
Quoting the JLS, Section 5.6.2, "Binary Numeric Promotion":
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
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.
Otherwise, if either operand is of type long, the other is converted to long.
Otherwise, both operands are converted to type int.
(emphasis mine)
这篇关于为什么在System.out.println()中不增加字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!