3 回答

TA贡献1813条经验 获得超2个赞
对于单个语句,它将保持不变,但是如果要将多个语句组合在if块中,则必须使用花括号。
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演示了块的使用:
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
}
}
(来自以上链接的示例)

TA贡献1795条经验 获得超7个赞
不,绝对没有区别:一对花括号将多个语句组合成一个语句;if,while,for,等想到一条语句; 如果只需要保护一个语句,则不需要大括号。
但是,许多软件商店甚至坚持要求只用括号即可。原因是这样的错误:
if (x > 20)
x -= 7;
y -= 8;
上面的陈述是令人误解的:缩进使您相信这两个分配都受到保护,而实际上只有第一个是受保护的。这样做的原因是Java中的空格不重要:缩进一条语句不会改变其在程序整体流程中的位置。上面的错误很难发现,因此采用规则来防止它们是一个好主意。

TA贡献1821条经验 获得超6个赞
正如@rajesh所说,当主体是单个语句时,花括号是可选的。
话虽如此,某些编码方式建议即使在单语句情况下也要保留括号,因为您(或后来的程序员)在以后更改代码时不太可能出错。
if("pie"== "pie")
System.out.println("Hurrah!");
System.out.println("Tricked you");
Tricked you实际上,if由于缩进,第二个印刷品实际上没有出现在中。
但是,这只是一个风格问题,未被普遍接受,当然,有能力的程序员必须能够阅读这两种形式。
添加回答
举报