从java中的If语句中删除花括号是否有区别? [英] Is there a difference in removing the curly braces from If statements in java
问题描述
在观看基本java的newbostons教程时,他教我们做if这样的语句。(注意花括号)
While watching thenewbostons tutorial on basic java, he teaches us to do if statements like this.(Notice the curly Braces)
if("pie"== "pie"){
System.out.println("Hurrah!");
}
所以我尝试删除大括号
if("pie"== "pie")
System.out.println("Hurrah!");
它仍然有效!由于我是java的新手,我不知道为什么会这样。我想知道删除(或添加)花括号是否有任何好处/缺点。
And it still works! Since I'm new to java, I don't know why that works. And I want to know if removing(or adding) the curly braces give any benefits/disadvantages.
推荐答案
对于单个语句它将保持不变,但如果要在if块中对多个语句进行分组,则必须使用花括号。
For a single statement it will remain same, but if you want to group more than one statement in the if block then you have to use curly braces.
if("pie"== "pie"){
System.out.println("Hurrah!");
System.out.println("Hurrah!2");
}
if("pie"== "pie")
System.out.println("Hurrah!"); //without braces only this statement will fall under if
System.out.println("Hurrah!2"); //not this one
你应该看到: Java中的块
块是平衡括号
之间的一组零个或多个语句,可以在允许单个语句的任何位置使用。以下
示例BlockDemo说明了块的使用:
A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed. The following example, BlockDemo, illustrates the use of blocks:
class BlockDemo {
public static void main(String[] args) {
boolean condition = true;
if (condition) { // begin block 1
System.out.println("Condition is true.");
} // end block one
else { // begin block 2
System.out.println("Condition is false.");
} // end block 2
}
}
(例子来自上面的链接)
这篇关于从java中的If语句中删除花括号是否有区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!