If Then & If Then Else

If Then Statement

The Java if-then statement is the most commonly used of all the control flow statements. The if-then statement controls the flow of your Java program by deciding whether or not to execute a section of code based on a true evaluation.

Take a look at a very basic if-then code block below. If the employee ID exists, then let’s execute the code to retrieve employee ID and then print it out to the screen.

//Java Code Depot If-Then Sample Code

if(employeeIDExists) {
     int employeeID = getEmployeeID(lastName);
     System.out.println("Employee ID: "+employeeID);
}


If employee ID does not exist, then code execution jumps to the end of the if-then code block.


If Then Else Statement

The Java if-then-else statement provides an alternate path of program execution when an “if” evaluates to false. When the “if” statement is not true, then the program needs to execute the code contained within the “else” code block.

The Java code below is a good sample on how to use the if-then-else control flow statement. Just as with the previous code snippet, we check to see if the employee ID exists. In this case, the flow moves to the else code block. The else section will create the employee ID and then print out the employee ID to the screen.

//Java Code Depot If-Then-Else Sample Code

if(employeeIDExists) {
     int employeeID = getEmployeeID(lastName);
     System.out.println("Employee ID: "+employeeID);
}
else {
     int employeeID = createEmployeeID(lastName);
     System.out.println("Employee ID: "+employeeID);
}


Remember that the if code block section and the else code block section are mutually exclusive, meaning only one of them will be executed.

You can also have multiple if-then-else statements that evaluates multiple conditions. Because these are mutually exclusive, only one code block section will be executed based on the test score.

if(testScore >= 90) {
     grade = 'A';
}
else if(testScore >= 80)  {
     grade = 'B';
}
else if(testScore >= 70)  {
     grade = 'C';
}
else if(testScore >= 60)  {
     grade = 'D';
}
else {
     System.out.println("Sorry, but you Failed! What happened? Sleeping in class?");
}


Now that your done with lesson 8.1, let’s move onto the next lesson on the switch statement.



Add a Comment

Your email address will not be published. Required fields are marked *