Java: 'if' Statement - Braces
Braces { }
not required for one statement
If the true
or false
part of
and if
statement has only one statement,
you do not need to use braces (also called "curly brackets").
Form
The if
statement doesn't need braces if there is only
one statement in a part. Here both the true
and false
parts have only one statement:
if (condition)
one statement to do if condition is true
else
one statement to do if condition is false
Example 1 - true and false parts
Here is a paintComponent()
method both with and without braces
which is possible only because each clause contains only one statement.
public void paintComponent(Graphics g) {
super.paintComponent(g); // call parent to paint background
if (marks < 50) {
g.setColor(Color.red); // bad marks in red
}else{
g.setColor(Color.black); // good marks in black
}
g.drawString("Score = " + marks, 10, 50);
}
and now without braces. Altho correct, it is not as safe a style.
public void paintComponent(Graphics g) {
super.paintComponent(g); // call parent to paint background
if (marks < 50)
g.setColor(Color.red); // bad marks in red
else
g.setColor(Color.black); // good marks in black
g.drawString("Score = " + marks, 10, 50);
}
Example 2 - only a true part
If there is only a true
part of the if
statement, it only needs braces if there is more than one statment.
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (marks < 50)
g.setColor(Color.red); // bad marks in red
g.drawString("Score = " + marks, 10, 50);
}
If the if condition is false, this will not set the color,
so the default color will be used (black).
Should you always use braces?
If there is one statment, many programs use braces
to make the code more robust.
This is a safer practice because any later addition
of a statement to one of the clauses will require
braces. If you don't have the braces with multiple
statements, the compiler may not give any error
message, but your code will not do what was expected.
What is a statement?
A statement is a part of a Java program. We have already
seen some simple statements:
- Assignment statement (eg,
x = 1;
).
- Method call statement (eg,
g.setColor(Color.red);
).
if
statement.
There are about ten kinds of statements. Many of them use braces
for grouping statements in the same way that the if
statement uses braces.