Programming and Problem Solving with Java

(やまだぃちぅ) #1
4.3 The if Statement | 171

Braces and Blocks


Java programmers use different styles when it comes to locating the left brace of a block. The
style used in this book puts the left and right braces directly below the words ifand else, with
each brace on its own line:

if(n >= 2 )
{
alpha = 5 ;
beta = 8 ;
}
else
{
alpha = 23 ;
beta = 12 ;
}

Another popular style is to place the statements following ifand elseon the same line as
the left brace; the right braces still line up directly below the left braces.

if(n >= 2 )
{ alpha = 5 ;
beta = 8 ;
}
else
{ alpha = 23 ;
beta = 12 ;
}

It makes no difference to the Java compiler which style you use (and other styles exist as
well, such as placing the left braces at the ends of the lines containing ifand else). It’s a mat-
ter of personal preference. Whichever style you use, though, you should maintain it throughout
the entire application. Inconsistency can confuse a person reading your code and give the im-
pression of carelessness.

to skip a sequence of instructions if a certain condition isn’t met. You could do so by leaving
the elsebranch empty, using only the null statement:


if (a <= b)
c = 20;
else
;

Free download pdf