这是代码:
public class Demo
{
public static void main(String[]args)
{
if(5>10)
System.out.println("5>10");
if(true)
System.out.println("true");
if((3+6)==(3-6))
System.out.println("false");
}
}输出为string: true (处理了第二个if语句)
我不明白为什么if(true) System.out.println("true");会被处理并打印出来。true语句中的条件if没有引用任何内容。我是从课本上得到这个密码的。Java中布尔值的默认值应该是false,那么为什么第二个if语句可以打印出来呢?
发布于 2016-03-26 02:34:29
实际上,如果计算结果导致条件(括号(条件)中)导致true,则会执行if -语句,而不管条件是什么。只要条件为真,就会输入if块。只要条件为false,则不会输入if块.
这就是为什么你的第一次和最后一次如果:
if(5>10) //false
if((3+6)==(3-6)) //false永远不会被输入,因为它们总是导致错误(因此,什么也没有打印)。
尽管这是无用的,但人们也可以在if语句中直接将真假作为一个条件:
if(true)如果其块为true或false,则其块将始终被执行或不执行。
将"true“作为检查条件的实际用法通常带有无限循环:
while(true){
//do something infinitely till break or error
}但我不认为
if(true)有什么真正的用处。
发布于 2016-03-26 02:30:48
true,这里是boolean。它会和
boolean first = true;
boolean second = false;
if (first) {
System.out.println("first");
}
if (second) {
System.out.println("second");
}这将只输出“第一”。
发布于 2016-03-26 02:35:13
我不明白为什么如果(真)System.out.println(“真”);将被处理并打印出true。
一般情况下,您应该真正了解条件语句。这里有一个,它谈论IF语句。
语法是
if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}https://stackoverflow.com/questions/36230961
复制相似问题