Java隐式转换

标签 java jakarta-ee implicit-conversion

使用以下代码:

Float a = 1.2;

有一个错误,因为它将小数作为 double 值,而 double 是比 float 更大的数据类型。

现在,它采用整数作为默认的 int 类型。那么,为什么下面的代码没有给出任何错误?

Byte b = 20;

最佳答案

编译器足够聪明,可以计算出 20 的位表示(int 值)可以装入 byte 而不会丢失数据。来自Java Language Specification §5.1.3 :

A narrowing primitive conversion from double to float is governed by the IEEE 754 rounding rules (§4.2.4). This conversion can lose precision, but also lose range, resulting in a float zero from a nonzero double and a float infinity from a finite double. A double NaN is converted to a float NaN and a double infinity is converted to the same-signed float infinity.

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

另见 this thread .

关于Java隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32255812/

相关文章:

eclipse - 如何通过 Eclipse 直接在 tomcat 中运行/调试 Ant 项目?

c++ - 解析有符号和无符号 int 之间的 char 是否未指定?

java - 我应该在 Java 中使用哪种数据结构来实现 1 键多值

java - 如何在 'war' 文件 : (Outside the project directory) 之外创建一个目录

java - 为什么 Android Firebase 会跳过身份验证 Activity

java - 如何在JavaEE(@Inject)中使用模拟@Autowired注释?

c++ - 如何进行从 std::string_view 到 std::string 的转换

c# - vb.NET 到 C# 的转换错误 : Cannot implicitly convert type 'object' to 'MyCustomObject' An explicit conversion exists

java - 无法让RecyclerView水平显示Android Java

java - classNotFoundException : org. springframework.core.io.Resource when intellij idea deploy maven spring mvc web project on tomcat7