Conditions

When we need to execute a set of statements based on a condition then we need to use control flow statements. For example, if a number is greater than zero then we want to print “Positive Number” but if it is less than zero then we want to print “Negative Number”.

If statement

If statement consists of a condition, followed by statement or a set of statements as shown below:

if(condition){
  Statement(s);
}

The statements gets executed only when the given condition is true. If the condition is false then the statements inside if statement body are completely ignored.

Example: This condition slows down the speed if a car is moving:

if (isMoving){ 
   currentSpeed--;
}

Nested if statement

When there is an if statement inside another if statement then it is called the nested if statement. The structure of nested if looks like this:

if(condition_1) {
   Statement1(s);

   if(condition_2) {
      Statement2(s);
   }
}

Statement1 would execute if the condition_1 is true. Statement2 would only execute if both the conditions(condition_1 and condition_2) are true.

If-else statement

This is how an if-else statement looks:

if(condition) {
   Statement(s);
}
else {
   Statement(s);
}

The statements inside “if” would execute if the condition is true, and the statements inside “else” would execute if the condition is false.

Example: This condition slows down the speed if a car is moving. Otherwise it will print that the car has already stopped:

if (isMoving) {
   currentSpeed--;
} else {
   System.err.println("The car has already stopped!");
}

If-else-if statement

if-else-if statement is used when we need to check multiple conditions. In this statement we have only one “if” and one “else”, however we can have multiple “else if”. This is how it looks:

if(condition_1) {
   statement(s);
}
else if(condition_2) {
   statement(s);
}
else if(condition_3) {
   statement(s);
}
.
.
.
else {
   statement(s);
}

Note: The most important point to note here is that in if-else-if statement, as soon as the condition is met, the corresponding set of statements get executed, rest gets ignored. If none of the condition is met then the statements inside “else” gets executed.

Example: This condition assigns a grade based on the value of a test score:

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);

Source:

results matching ""

    No results matching ""