Skip to main content
Logo image

Java, Java, Java: Object-Oriented Problem Solving, 2024E

Section A.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:
public void sayHello()
{
    System.out.println("Hello");
}
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:
public void sayHello() {
   System.out.println("Hello");
}
This is the style that’s used in the latter 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:
public void sayHello() {
    for (int k=0; k < 10; k++) {
        System.out.println("Hello");
    } //for loop
} // sayHello()
You have attempted of activities on this page.