为什么在 Java 中允许将 double 转换为 char?
为什么在 Java 中允许 char c = (char)65.8;
?
由于 65.8
不是精确的 Unicode 值,它不应该抛出错误吗?我知道双精度数被截断为整数,在本例中为 65
,但对我来说,允许程序员进行这样的转换似乎是糟糕的设计.
也就是窄化类型转换.来自 oracle 文档
:
原始类型的 22 种特定转换称为窄化原始转换:
字节或字符的缩写
字符转字节或短
int 转换为字节、short 或 char
long 为 byte、short、char 或 int
浮点到字节、short、char、int 或 long
double 到 byte、short、char、int、long 或 float
缩小原语转换可能会丢失有关数值的整体大小,也可能会丢失精度和范围.
在 Java 中,有两种基本类型的类型转换:widening 和 narrowing.
加宽转换
发生在您从较小(或较窄)的类型转换为较大(或较宽)范围的类型时.因此,不会有数据丢失的机会,并且转换被认为是安全"的.
窄化转换
发生在您从较大(或较宽)的类型转换为较小(或较窄)范围的类型时.由于我们正在缩小范围,因此可能会丢失数据,因此此转换被视为不安全"
byte到char的转换是一个特例,同时代表widening和narrowing.转换首先将 byte 转换为 int,然后将 int 转换为 char..p>
我能想到为什么缩小类型转换不会导致错误/异常的一个原因是在没有数据丢失的情况下允许方便/容易/快速的类型转换.编译器让我们来确保转换后的数据能够适应更小的范围.如果我们想快速截断值,例如舍入 double
的值(通过将其类型转换为 int
),它也很有用.
Why is char c = (char)65.8;
allowed in Java?
Shouldn't it throw an error since 65.8
is not an exact Unicode value? I understand that the double is truncated to an integer, in this case, 65
, but it seems like bad design to me to allow the programmer to make such a cast.
That is called Narrowing type casting.
From oracle docs
:
22 specific conversions on primitive types are called the narrowing primitive conversions:
short to byte or char
char to byte or short
int to byte, short, or char
long to byte, short, char, or int
float to byte, short, char, int, or long
double to byte, short, char, int, long, or float
A narrowing primitive conversion may lose information about the overall magnitude of a numeric value and may also lose precision and range.
In Java, there are two basic types of type conversions: widening and narrowing.
A widening conversion
occurs when you convert from a type with smaller (or narrower) to type with larger (or wider) range. Because of this, there is no chance for data loss and the conversion is considered "safe."
A narrowing conversion
occurs when you convert from a type with larger (or wider) to type with smaller (or narrower) range. Since we are shrinking the range, there is a chance of data loss so this conversion is considered "unsafe"
The conversion from byte to char is a special case and represents widening and narrowing at the same time. The conversion starts by converting the byte to an int and then the int gets converted to the char.
One reason I can think of why narrowing type casting doesn't result in an error/exception is to allow for a convenient/easy/quick type conversion in the cases when no data will be loss. Compiler leaves it up to us to make sure converted data will be able to fit in the smaller range. It is also useful if we want to quickly truncate values such as rounding the value of a double
(by type-casting it to an int
).
相关文章