{ } not required for one statementtrue or false part of
and if statement has only one statement,
you do not need to use braces (also called "curly brackets").
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
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);
}
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).
x = 1;).g.setColor(Color.red);).if statement.if
statement uses braces.