java - 我们不能将 int 向下转型为 boolean 吗?

标签 java

根据我的理解,0 在第 1 行中默认被视为 int。这就是为什么将 int 分配给 boolean 会给出编译时错误。这是对的吗?另外,为什么它在第 2 行给出编译错误,即使在显式向下转换时也是如此?

public class HelloWorld
{
   public static void main(String[] args)
  {
    boolean b = 0;         //1.compile time error
    boolean b = (boolean)0;//2.still compile time error
    System.out.print(b);
  }
}

最佳答案

Java 不支持从intboolean 的转换。这是因为 boolean 不是 Java 中的数字类型。

惯用的方法是编写表单的代码

boolean b = n != 0;

其中 n 是数字类型。

这包含在 JLS§4.2.5 中:

An integer or floating-point expression x can be converted to a boolean value, following the C language convention that any nonzero value is true, by the expression x!=0.

...

A boolean value may be cast to type boolean, Boolean, or Object (§5.5). No other casts on type boolean are allowed.

关于java - 我们不能将 int 向下转型为 boolean 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39386046/

相关文章:

java - Eclipse 和 println 似乎在动态设置私有(private)最终静态字段的值上存在分歧

java - LoadRunner Java over HTTP 协议(protocol)与 WEB (http/html) 协议(protocol)

Java压缩字节数组和base 64编码转base 64解码解压字节数组报错: different sized input/output arrays

java - 为什么当我们想要水平/垂直旋转矩阵时,我们将项除以 2?

java - HTTP 状态 500 - servlet HelloWeb 的 Servlet.init() 抛出异常?

Java泛型之泛型

java - hibernate 无法与 Heroku postgresql 插件连接

java - 接口(interface)是否通过代码重复来解决 DDD?

java - 包装类的 GSON 反/序列化

java - Highchart 使用 Java 离屏生成 SVG