问题描述
但是, char1 + = 1; 或 char1 ++ 不执行二进制数字促销,因此可按预期工作。
引用:
(强调我)
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 char1In 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 bThe 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":
(emphasis mine)
这篇关于为什么在System.out.println()中不增加字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!