In java if quot;char c = #39;a#39; quot; why does quot;c = c + 1quot; not compile?(在java中如果“char c = a为什么“c = c + 1?不编译?)
问题描述
我尝试编译以下代码:
public static void main(String[] args){
for (char c = 'a'; c <='z'; c = c + 1) {
System.out.println(c);
}
}
当我尝试编译时,它会抛出:
When I try to compile, it throws:
错误:(5, 41) java: 不兼容的类型: 可能的有损转换int转char
Error:(5, 41) java: incompatible types: possible lossy conversion from int to char
问题是,如果我编写 c = (char)(c + 1)
、c += 1
或 c++
.
The thing is, it does work if I write c = (char)(c + 1)
, c += 1
or c++
.
我检查过,当我尝试 char c = Character.MAX_VALUE + 1;
时编译器会抛出类似的错误,但我认为 'c' 的值无法传递 'char' 类型最大值在原始函数中.
I checked and the compiler throws a similar error when I try char c = Character.MAX_VALUE + 1;
but I see no way that the value of 'c' can pass 'char' type maximum in the original function.
推荐答案
c + 1
是一个 int
,因为操作数经过 二进制数字提升:
c + 1
is an int
, as the operands undergo binary numeric promotion:
c
是一个char
1
是一个int
c
is achar
1
is anint
所以 c
必须扩展为 int
以使其兼容添加;并且表达式的结果是 int
类型的.
so c
has to be widened to int
to make it compatible for addition; and the result of the expression is of type int
.
至于有效"的东西:
c = (char)(c + 1)
将表达式显式转换为char
,因此其值与变量的类型兼容;c += 1
等价于c = (char) ((c) + (1))
,所以和上一个基本一样.c++
是类型char
,所以不需要强制转换.
c = (char)(c + 1)
is explicitly casting the expression tochar
, so its value is compatible with the variable's type;c += 1
is equivalent toc = (char) ((c) + (1))
, so it's basically the same as the previous one.c++
is of typechar
, so no cast is required.
这篇关于在java中如果“char c = 'a'"为什么“c = c + 1"?不编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在java中如果“char c = 'a'"为什么“c =


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