Use of Braces


[Page 814 (continued)]

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 is used in the first part of the book, because it is 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"); } 



[Page 815]

This is the style that is used in the second half of the book, and it seems to be the style preferred by professional Java programmers.

Sometimes, even with proper indentation, it is 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() 





Java, Java, Java(c) Object-Orienting Problem Solving
Java, Java, Java, Object-Oriented Problem Solving (3rd Edition)
ISBN: 0131474340
EAN: 2147483647
Year: 2005
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net