What is the result of compiling and executing the following fragment of code:
Boolean flag = false;
if (flag = true)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
Boolean flag = false;
if (flag = true)
{
System.out.println("true");
}
else
{
System.out.println("false");
}
The code fails to compile at the “if” statement.
An exception is thrown at run-time at the “if” statement.
The text“true” is displayed.
The text“false”is displayed.
Nothing is displayed.
public static void main(String[] args){
Boolean flag=false;//先调用Boolean.valueOf(boolean b)返回false对应的Boolean对象Boolean.FALSE,然后赋值给flag,flag值为Boolean.FALSE
/* 先赋值,遇到if条件表达式自动拆箱
* 1. 先调用Boolean.valueOf(boolean b)返回true对应的Boolean对象Boolean.TRUE,然后赋值给flag,flag值为Boolean.TRUE
* 2. 调用booleanValue()返回flag值对应的基础数据类型值true
* 3. 结果输出true
*/
if (flag=true){
System.out.println("true");
}else{
System.out.println("false");
}
}