20. Coding Conventions

20.4. Use of Braces

 

 

Curly braces { } are used to mark the beginning and end of a block of code. They are used to demarcate a class body, a method body, or simply to combine a sequence of statements into a single code block. There are two conventional ways to align braces and we have used both in the text. The opening and closing brace may be aligned in the same column with the enclosed statements indented:

,,

 

 

 

J

This is the style that’s used in the first part of the book, because it’s easier for someone just learning the syntax to check that the braces match up.

Alternatively, the opening brace may be put at the end of the line where the code block begins, with the closing brace aligned under the beginning of the line where the code block begins:

,,

 

 

J

This is the style that’s used in the last two parts of the book, and it seems the style preferred by professional Java programmers.

 

Sometimes even with proper indentation, it it difficult to tell which closing brace goes with which opening brace. In those cases, you should put an end- of-line comment to indicate what the brace closes:

,,

 

 

 

J