public class BuildStuff {
public static void main(String[] args) {
Boolean test = new Boolean(true);
Integer x = 343;
Integer y = new BuildStuff().go(test, x);
System.out.println(y);
}
int go(Boolean b, int i) {
if(b)
return (i/7);
return (i/49);
}
}
这是来自 SCJP ,我知道答案是“49”,但我有疑问。当我们创建一个对象并在该对象中传递一个值时。比方说:Dog d = new Dog("tommy");
在此语句中,d 是对对象 Dog 的引用,并且 Dog 的“name”实例变量设置为“tommy”。但这并不意味着 d = tommy
。
但是,如果是 boolean 值,当我们在 boolean 对象中传递 true 时。它将引用设置为 true。为什么它是 boolean 值的情况?还有其他类吗?
最佳答案
传入的 Boolean
b
可以通过拆箱转换转换为原始 boolean
,导致表达式 true
用于 if
语句。
所有原始类型都有对应的内置包装类,Java 会根据需要拆箱/装箱。
- boolean 值 <=> boolean 值
- 字节 <=> 字节
- 字符 <=> 字符
- 短 <=> 短
- 整数 <=> 整数
- 长<=>长
- float <=> float
- 双人 <=> 双人
(如果相应的包装器类实例为 null
,则拆箱转换将失败并返回 NullPointerException
:
Boolean test = null;
// NPE
boolean b = test;
)
关于java - 在 boolean 对象中传递值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21737107/