Why doesn#39;t a character increment in System.out.println()?(为什么 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 incremented char1
在上面,为什么 (char1+1) 或 (char++) 不打印递增的字符而其他两个打印?
In the above, why doesn't (char1+1) or (char++) print the incremented character but theother two do?
推荐答案
首先,我假设因为您说 System.out.println
中的增量有效,所以您确实指定了:
First, I'm assuming that because you say the increment in System.out.println
works, that you have really specified:
char char1 = 'a';
编辑
针对问题的变化 (char1+1;
=> char1 += 1;
) 我看到了问题.输出是
In response to the change of the question (char1+1;
=> char1 += 1;
) I see the issue.
The output is
a
98
b
98
出现是因为 char a
被提升为 int
(二进制数字提升)以加 1.所以 a
变为 97('a'
的 ASCII 值)和 98 个结果.
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.
但是,char1 += 1;
或 char1++
不执行二进制数字提升,因此可以按预期工作.
However, char1 += 1;
or char1++
doesn't perform binary numeric promotion, so it works as expected.
引用 JLS,第 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 类型,则转换另一个长.
Otherwise, if either operand is of type long, the other is converted to long.
否则,两个操作数都转换为 int 类型.
(强调我的)
这篇关于为什么 System.out.println() 中的字符不增加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 System.out.println() 中的字符不增加?


基础教程推荐
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01