java - 从数组中赋值时出现 Char 数组编译时错误

标签 java arrays char

所以我有这段代码

char [] a = {'a','b','c'};

char c = 'a' + 'b'; //works
char c2 = 98 + 97; //works
char c3 = a[0] + a[1]; //compile time error

所以它们都是相同的功能,但是在获取和使用数组值时它会给我一个编译时错误。这是什么原因??

The result of the additive operator applied two char operands is an int.

那我为什么可以这样做呢?

char c2 = (int)((int)98 + (int)97);

最佳答案

The result of the additive operator applied two char operands is an int.

Binary numeric promotion is performed on the operands. The type of an additive expression on numeric operands is the promoted type of its operands

前两个是常量表达式,其结果值是 int,可以安全地分配给 char

第三个不是常量表达式,因此编译器无法保证。

同理

then why can I do this?

char c2 = (int)((int)98 + (int)97);

这也是一个常量表达式,结果可以放在 char 中。

尝试使用更大的值,1234555555

关于java - 从数组中赋值时出现 Char 数组编译时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25196798/

相关文章:

java - 读取文件 utf-8

java - map 是原始类型。对泛型类型 Map<K,V> 的引用应该参数化

java - 如何创建 POJO?

python - 我如何计算数字/位数组的所有可能性(在 python 中,或与此相关的任何语言)

java - 关于代码的说明(两个字符串中公共(public)字符的数量)

c - 二进制到字符在c中的转换

c - 如何计算C中文本文件中的单词数

java - 我怎样才能让javac搜索类路径的子目录?

javascript - 在 Javascript 的值函数中使用数组键?

从删除\n 和\0 的字符串创建协议(protocol)行