根据我的理解,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 不支持从int
到boolean
的转换。这是因为 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 typeboolean
,Boolean
, orObject
(§5.5). No other casts on typeboolean
are allowed.
关于java - 我们不能将 int 向下转型为 boolean 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39386046/