Java Notes

Braces are your friend

Braces { } not required for one statement (but are always good)

If the true or false clause of an if statement has only one statement, you do not need to use braces (also called "curly brackets"). This braceless style is dangerous, and most style guides recommend always using them.

Braceless 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:

// Legal, but dangerous.
if (condition)
    Exactly one statement to execute if condition is true
else
    Exactly one statement to execute if condition is false

Examples showing what can go wrong

A sample written with braces.

//... Good style - Indented with braces.
String comment = "Not so bad.";
if (marks < 60) {
    comment = "This is terrible.";
}
System.out.println(comment);

Without braces it's still correct, but not as safe.

//... Less good style - Indented but without braces.
String comment = "Not so bad.";
if (marks < 60) 
    comment = "This is terrible.";
System.out.println(comment);

What can go wrong?

Q1: What does this "legal" version print?

//... What does this print?
String comment = "Not so bad.";
if (marks < 60);
    comment = "This is terrible.";
System.out.println(comment);

A: it always prints "This is terrible" because of that semicolo after the if clause. The semicolon indicates an empty statement, which satisfies the compiler, but is surely not what you intended. Putting a beginning brace after the if condition prevents programmers from also adding a semicolon and creating this kind of error.

Q2: What's wrong with this?

So your program is working OK without the braces and you decide to add a grade. The compiler is very happy with this, but you won't be. Why?

//... What does this print?
String comment = "Not so bad.";
String grade   = "A";
if (marks < 60)
    comment = "This is terrible.";
    grade   = "F";
System.out.println("Your grade is " +grade);
System.out.println(comment);

A: Although the comment will be appropriate to the score, the grade will always be "F". Although the second grade assignment is indented, it isn't inside the if because the unbraced clause only includes one statement! This appearance of being included is a major source of programming errors.

Other Java constructions use braces

There are many kinds of Java statements that use braces to group things. You've already seen class and method (eg, main) declarations, which enclose their contents in braces. In addition to ifs, you'll learn about loops (for, while, and do), try...catch, and switch statements which use braces to enclose other statements.

References