首页 > 解决方案 > 自动类型转换如何与 Java 中的“char”一起使用?

问题描述

我不明白这种行为:

int i = 1;
char c = i; // compilation error: incompatible types: possible lossy conversion from int to char

char c = 1; // is OK

前提是整数文字具有默认类型 int。

标签: javajavac

解决方案


char 是 16 位。
int 至少是 32 位。

除非您向下转换,否则您不能将 32(或更多)位分配给 16 位变量。

向下投射示例:

int kapow = 7;
char blam = (char)kapow;

推荐阅读