Java has a "feature" which allows you to omit curly brackets when writing if statements, for loops, or while loops containing only a single statement. You should never use this feature – always include curly brackets. The reason for this is because omitting curly brackets increases your chances of writing buggy code.
If there is only one statement for the if condition, curly braces are optional but if there are a series of steps curly braces are mandatory. That being said, you always want to keep the option of adding more statements to an if condition later. It is more readable and reduces error or bugs.
Without curly braces only first statement consider in scope so statement after if condition will get executed even if there is no curly braces. But it is Highly Recommended to use curly braces. Because if the user (or someone else) ever expands the statement it will be required.
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
You should see: Blocks in Java
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
}
}
(example from the above link)
No, there is absolutely no difference: a pair of curly braces makes multiple statements into a single one; if
, while
, for
, and so on expect a single statement; if you need to guard only one statement, you do not need braces.
However, many software shops insist on having braces even for a single statement. The reason is errors like this:
if (x > 20)
x -= 7;
y -= 8;
The statements above are misleading: the indentation leads you to believe that both assignments are protected, while in reality only the first one is. The reason for that is that whitespace in Java is insignificant: indenting a statement does not change its placement in the overall flow of the program. Errors like the above are very hard to find, so adopting a rule to prevent them in the first place is a good idea.
As @rajesh says, braces are optional when the body is a single statement.
Having said that, leaving the braces in even for single statement cases is recommended by some coding styles because you (or the programmer who comes after you) are less likely to make errors when you change the code later.
if("pie"== "pie")
System.out.println("Hurrah!");
System.out.println("Tricked you");
The second print, Tricked you
, is not actually in the if
, it just looks like it because of the indentation.
However that is only a style point, not universally accepted, and certainly a competent programmer needs to be able to read both forms.
It does have a disadvantage. The answers mentioned so far are correct. But there are some disadvantages to it from the security perspective of things. Having worked in a payments team, security is a much stronger factor that motives such decisions. Lets say you have the following code:
if( "Prod".equals(stage) )
callBankFunction ( creditCardInput )
else
callMockBankFunction ( creditCardInput )
Now lets say you have this code is not working due to some internal problem. You want to check the input. So you make the following change:
if( "Prod".equals(stage) )
callBankFunction ( creditCardInput )
else
callMockBankFunction ( creditCardInput )
Logger.log( creditCardInput )
Say you fix the problem and deploy this code (and maybe the reviewer & you think this won't cause a problem since its not inside the 'Prod' condition). Magically, your production logs now print customer credit card information that is visible to all the personnel who can see the logs. God forbid if any of them (with malicious intent) gets hold of this data.
Thus not giving a brace and a little careless coding can often lead to breach of secure information. It is also classified as a vulnerability in JAVA by CERT - Software Engineering Institure, CMU.
This is a question of style that applies to a number of languages including Java, C++, C and C#.
When a code block contains only one line the braces can be omitted. This applies to any control structure: if, while, for, do-while.
For example, the two loops below are equivalent.
for(int i=0; i<100; i++)
doSomething(i);
for(int i=0; i<100; i++) {
doSomething(i);
}
Advantage of omitting {}: Your code can be briefer - meaning less line. Some may feel it is more readable.
Disadvantage of omitting {}: If you later modify your code and need to add another line to the code block, you better remember to add those {}. If not and you write the code below:
for(int i=0; i<100; i++)
doSomething(i);
doSomethingElse(i);
This is really equivalent to:
for(int i=0; i<100; i++) {
doSomething(i);
}
doSomethingElse(i);
The curly braces are usually for having a block of statements. Without braces, only the first line will be executed in the if()
statement. Not the entire block that starts with {
and ends with }
if("pie" == "pie") {
System.out.println("Executes if pie==pie");
System.out.println("So does this");
}
and
if("pie" == "pie")
System.out.println("Executes if pie==pie");
System.out.println("Executes, regardless of if pie is equal to pie");
Note however, if you want to compare two String
objects, use .equals()
method in String
. This example still works because it is comparing one constant string with itself, which is always true.
No BUT the real danger occurs when the code is edited later on. It is relatively easy to edit something like:
if (someCondition)
// do something
to
if (someCondition)
// do something
// do something else important
and think the 'do something else important' will only be run when someCondition is true. The indentation misleads :-)
With brackets, this danger isn't present.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With