简体   繁体   English

char c =某些整数文字可能会编译但浮动f =某些浮点文字永远不会编译。 为什么?

[英]char c = some integer literal might compile but float f = some floating point literal will never compile. Why?

char c1 = 123; //Compiles fine
char c2 = 123456; //Error: cannot convert from int to char

Java is smart enough to determine whether an integer is small enough to be converted to a character. Java足够聪明,可以确定整数是否足够小以转换为字符。 Why is it not able to convert very small floating point literals to a float?. 为什么它无法将非常小的浮点文字转换为浮点数? For example: 例如:

float f1 = 0.3; //Error: cannot convert from double to float
float f2 = 0.3f; //Compiles fine

char c = some integer literal might compile but float f = some floating point literal will never compile. char c =某些整数文字可能会编译但浮动f =某些浮点文字永远不会编译。 Why? 为什么?

PS: I know that a floating point literal is treated as a double by default PS:我知道默认情况下浮点文字被视为double

0.3 is treated as a double, so its binary representation takes 64 bits and it can't fit into a float without possible loss of precision, so you can't assign it to a float variable without an explicit cast. 0.3被视为double,因此它的二进制表示占用64位,并且它不能适应浮点而不会丢失精度,因此如果没有显式强制转换,则无法将其赋值给float变量。

On the other hand, if you assign to a char variable an int literal within the range of the char type (for example 123), there's no loss of data. 另一方面,如果为char变量分配char类型范围内的int文字(例如123),则不会丢失数据。

Both of the assignments (int to char variable and double to float variable) require a narrowing primitive conversion . 两个赋值(int到char变量和double到float变量)都需要缩小基元转换

JLS 5.2 says JLS 5.2

A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable. 如果变量的类型是byte,short或char,则可以使用缩小的基元转换,并且常量表达式的值可以在变量的类型中表示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM