The if-then
Statement
The if-then
statement is the most basic of all the control flow statements. It
tells your program to execute a certain section of code only if a
particular test evaluates to true
.
if (condition){
do somethingl;
}
else{
do other thing;
}
For example, the Bicycle
class could allow the brakes
to decrease the bicycle's speed only if the bicycle is already
in motion. One possible implementation of the applyBrakes
method could be as follows:
void applyBrakes() {
// the "if" clause: bicycle must be moving
if (isMoving){
// the "then" clause: decrease current speed
currentSpeed--;
}
}
The if-then-else
Statement
The if-then-else
statement provides a secondary path of execution when an
"if" clause evaluates to false
. You could use an if-then-else
statement in the applyBrakes
method to take some action if the
brakes are applied when the bicycle is not in motion. In this case, the action
is to simply print an error message stating that the bicycle has already
stopped.
void applyBrakes() {
if (isMoving) {
currentSpeed--;
} else {
System.err.println("The bicycle has already stopped!");
}
}
Nested if
A nested if statement is an if-else statement with
another if statement as the if body or
the else body.Here's an example:
if ( num > 0 ) // Outer if
if ( num < 10 ) // Inner if
System.out.println( "num is between 0 and 10" ) ;
Here is a example:
class IfElseDemo {
public static void main(String[] args) {
int testscore = 76;
char grade;
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}