Semicolon and Curly Brace Usage | Heaton Research

Semicolon and Curly Brace Usage

Get the entire book!
Java for the Beginning Programmer

As you have been looking through these examples, it may be somewhat confusing as to when semicolons are used and when curly braces are used. You probably have also noticed that not all source code lines are left justified. The program code is indented. These three topics will be discussed in this section.

Semicolon Usage

If you have never worked with a language that requires semicolon terminated lines, it can be a confusing idea. In Java, the semicolon ends an idea. So if you were going to print “Hello World”, such as follows.

System.out.println("Hello World");

You would use a semicolon. The idea of this line has ended, it has done its job, and the next line is a new idea. However, consider an if-statement.

if(i<10)
{
  System.out.println("Hello");
}

The if-statement does NOT have a semicolon. The idea of the if-statement is not yet done, the lines that follow will only be executed if the if-statement is true.

Here is a very simple rule-of-thumb, which is almost always true. To determine if a line should have a semicolon, look at the next line. If the next line is an open curly brace then the line should NOT have a semicolon. There are exceptions to this rule, but it generally holds true.

The case where this rule does not work is when you begin to leave out curly braces as a shortcut. This is discussed in the next section.

When Curly Braces are not Needed

If there is just one line of code in an if-statement, while-loop, for-loop or do/while loop you can leave off the curly braces. For example consider the following if statement.

if( i<10 )
  System.out.println("i is less than 10");
else
  System.out.println("i is not less than 10");

Because there is only one line in the code block, the curly braces can be omitted. If you add another line of code to either block, that block must now use curly braces.

Indenting Code

You have probably noticed that the code examples that I give you are indented. This makes the source code much easier to read than if the entire file were left-justified. The rules for indenting are pretty simple. It is based on where curly braces are located, or could have been located. Consider the following program, which is indented, shown in Figure 3.1.

Figure 3.1: How indenting works

How indenting works

You will notice that there are four levels of indention. The first level is left justified and is denoted by my left most vertical line above. Then, each time there is an opening curly brace the indention level goes over by one. A closing curly brace will bring it back by one. Did you notice my dashed vertical line? The if-statement does not have a curly brace, but it could have. Because of this, we indent to the fourth level.

Copyright 2005-2008 by Heaton Research, Inc.