英文:
Types conversion from int to char Int to char
问题
假设
FileInputStream in = new FileInputStream("file.txt");
char c = (char) in.read();
给我一个错误:
>java:不兼容的类型:从int到char可能有损失的转换
,
但是
char b = 87;
不会给我任何错误,而是会给我Unicode字符
- 为什么char变量c会产生错误,因为
in.read()
返回一个int值,该值可以是一个Unicode字符,但是char变量b却不会产生错误?
英文:
Assuming
FileInputStream in=new FileInputStream ("file.txt");
char c=in.read();
Gives me an error:
>java: incompatible types: possible lossy conversion from int to char
,
but
char b=87;
Does not give me any error,rather it gives me the Unicode character
- why does char c variable gives an error since
in.read()
returns an int value that can be a Unicode character but char b variable doesn't?
答案1
得分: 0
因为一个整数也可以是2147000000,而这无法转换为字符。当你指定87时,编译器知道它在预期的字符范围内,但当你从其他地方接收它时,无法确保数据的安全性。
英文:
Because an int can also be 2147000000 and that cannot be converted to a char. When you specify 87 the compiler knows that falls within the expected char boundaries but when you are receiving it from somewhere else there is no way to ensure data safety.
答案2
得分: -1
整数类型通常为32位(与系统相关),而字符类型通常为8位。因此,您正在将32位转换为8位,并可能丢失数据。
英文:
An int type is generally 32-bit (system dependent) while char is generally 8-bit. Therefore you are converting 32-bit to 8-bit and potentially losing data.
专注分享java语言的经验与见解,让所有开发者获益!
评论