The if
statement can be used in its simple form, or in its extended if-else form. Here is an example of a simple
if statement:
if(grade > 0) {
sumOfGrades = sumOfGrades + grade;
numberOfGrades++;
}
This statement says, if the variable grade is greater than 0, then add the grade value to the variable
sumOfGrades, and increment the variable numberOfGrades by 1. Otherwise, do nothing. Either both
CHAP. 5] PROGRAMMING IN JAVA 71
statements following the if statement will be executed, or neither will be, because they are both within the
curly brackets which follow the if. The curly brackets mark a code block.
If the tested condition is true, then the code block of the if statement will be executed. If the condition
is false, the code block will be skipped.
Here is the syntax of the simple if statement:
if(
)
The conditional expression must evaluate to either true or false. If the conditional expression is true,
the following statement will be executed, but not otherwise. The can also be a compound
statement, which is another way of saying that can be a code block enclosed in curly braces.
A compound statement or code block is enclosed in curly braces, and each statement inside must be terminated
with a semicolon.
Pages:
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200