为什么下面的代码编译不出来
Why doesn't the following code compile
int n = 5;
char c = n;
但以下确实编译
char c = 5;
我不是在这两种情况下都给 char 分配了一个整数值吗?
Aren't I just assigning an integer value to char in both cases?
可以将 char 分配给 int 而无需强制转换,因为这是一种扩大转换.反过来,将 int 转换为 char 需要强制转换,因为它是一种缩小转换.
A char can be assigned to an int without a cast because that is a widening conversion. To do the reverse, an int to a char requires a cast because it is a narrowing conversion.
另请参阅 JLS.第 5 章.转化和促销.
这篇关于可以将整数值分配给 char 但不能将整数变量分配给 char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
“Char 不能被取消引用"错误quot;Char cannot be dereferencedquot; error(“Char 不能被取消引用错误)
Java Switch 语句 - 是“或"/“和"可能的?Java Switch Statement - Is quot;orquot;/quot;andquot; possible?(Java Switch 语句 - 是“或/“和可能的?)
Java替换字符串特定位置的字符?Java Replace Character At Specific Position Of String?(Java替换字符串特定位置的字符?)
具有 int 和 char 操作数的三元表达式的类型是什么What is the type of a ternary expression with int and char operands?(具有 int 和 char 操作数的三元表达式的类型是什么?)
读取文本文件并存储出现的每个字符Read a text file and store every single character occurrence(读取文本文件并存储出现的每个字符)
为什么我需要在 byte 和 short 上显式转换 char 原语Why do I need to explicitly cast char primitives on byte and short?(为什么我需要在 byte 和 short 上显式转换 char 原语?)