If, Else and Else If Statements

Introduction: Hello. In this tutorial you will learn about the if, else and else if statements. When are these statements used? The if statement is used to check if certain conditions are true. For example, just like we would say in English, if the time of day is noon we should eat lunch, else we shouldn't. So, what is else if? Since the if statement is used to check if certain conditions are true and else is for the opposite, what else do we need? To be able to check multiple times if certain conditions are true, but not the same. Makes sense? Here's an (English) example: If the time of day is noon we should eat lunch, else if the time of day is between 8am and 11am we should eat breakfast. What's that? You don't eat breakfast at 11am? Neither to do I... It was an example.. ok?! What is the syntax used in the statements? We will need to use Equality and Relational Operators to check if our conditions are true. There are a few types of these but I will save those for the next tutorial and just teach you the basic and most commonly used one for now. The most commonly used and most basic Equality and Relational Operator is the sign which checks if two variables are the same. This operator is used as "==" (without quotes, two (2) equal signs). If, Else and ElseIf Example: The below example has an if statement, followed by and if, else statement and ends with an if, else and else if statement. If the conditions checked are true, it will run the code block directly encased with the braces following the statement conditions...
  1. int time = 9;
  2. if (time == 12) {
  3. System.out.println("Noon!");
  4. }else if(time == 9) {
  5. System.out.println("Breakfast!");
  6. } else {
  7. System.out.println("Snack!");
  8. }
The above script sets a "time" int variable to 9 then checks whether it should output "Noon!" if the time is 12, "Breakfast!" if the time is 9 or "Snack!" if the time is NOT 9 or 12. Of course, it outputs 9. Try it yourself and change the time value between running the program. Finished!

Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
17 + 3 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.