Java If Else: An Exercise in Flow Control

javaifelseA Java program executes sequentially unless you add code that breaks up this natural flow, and makes it more dynamic. For example, a section of your program may execute code that prints a specific message if the user is younger than 65 years old , and present a different message if they are over 65. You would handle this in your program by adding decision-making logic in the form of control flow or conditional statements. For this tutorial we are going to explore how to control the flow of Java programs using if else statements. This concept is considered a basic concept of the Java language. If you want to enhance your knowledge to include other core concepts, a course in Java fundamentals is recommended.

Before we jump into learning about the if else statement, let’s start with the concept on which it is built–the if statement.

An if statement looks like this:

int Age = 70;
if (Age > 65)
      {
      System.out.println {“You are ready for retirement!”);
      }

This snippet of code contains an initialization of a variable Age that is set to the number 70. The condition tests for when Age is greater than the number 65. If this statement returns true, the message, “You are ready for retirement!” is printed on the screen. If the condition is not met, then the program ignores the code block and continues program execution. Since our variable is currently set to a number that is greater than the 65, the message would be displayed.

You are not limited to a single if statement. The following example shows what Java code with multiple if statements looks like.

Example 1: Multiple if Statements

public static void main (String[ ] args)
{
int Age = 18;
if (Age <  65)
      {
      System.out.println {“You are too young to retire!”);
      }
if (Age >= 65)
      {
      System.out.println {You are ready for retirement!”);
      }
)

This example contains two tests and possible outputs:

  • If Age is less than 65, print “You are too young to retire!” to the screen.

  • If Age is greater than or equal to 65, print “You are ready for retirement!”

The program starts with the first condition to test if it is true, and executes the output for only one of the conditions, depending on the value of Age.

In the if statement, conditions that return false values are ignored and program execution continues. If you want Java to do some more decision making, you can add if else logic.

Like the if statement, if else tests for specific conditions. However, it goes a step further and gives the program something to do in both true and false cases.

The if else statement syntax looks like this:

if (condition)
     {
     Statement to execute if condition is true;
     }
else
     {
     Statement to execute if condition is false;
     }

The first half mimics the syntax for the if statement. The if keyword indicates a change in program flow is about to change, which is followed by a condition (Boolean expression) that is enclosed in parentheses. You then create your first code block that includes the statement that you want to execute if the condition returns true (all enclosed in brackets). The second code block is similar to the first, but contains a statement that executes if the condition returns false (again all in brackets). The code blocks can contain any expression that returns a Boolean (true or false) value. The expressions always ends with a semicolon.

Formatting tips:

  • Extra whitespace is ignored in Java programs, so you can add indentations as needed to aid readability. You can learn more interesting information in an introduction to Java programming course.

  • Curly brackets that enclose the statement to execute are optional when there is only a single statement. However, it is good programming practice to add them to make the program easy to read.

Example 2: Basic if else Statement

This example contains an if else statement that prints a classic message on the screen.

int num = 4;
if (num >=3)
     {
     System.out.println(“Hello World!”);
     }
else
     {
     System.out.println(“Sorry. No printout!”);
     }

This code creates a variable called num and gives it a starting value of 1. The program continues the loop as long as the value of num is less than 5. At the end of each the loop, the program increases the value of num by one. For each loop the program prints “Hello world!”

Here’s the output:

Hello world!

Hello world!

Hello world!

Hello world!

Hello world!

The words “Hello world!” are printed to the screen five times.

Example 3: Compound Statements

Example 3 contains a single statement within a code block. Java also supports compound statements within a single code block.

This is what the syntax looks like:

if (condition)
     {
     Statement 1 to execute;
     Statement 2 to execute;
     Statement 3 to execute;
     }
else
     {
     Statement 4 to execute;
     }

Here’s an example:

public static void main(String[] args)
{
if (num < 0)
     {
     System.out,println(“Your value is a negative number.”;
     System.out.println(“Try another number:”);
     num = keyboard.nextInt ( );
     }
else
     {
     System.out.println(“You did not enter a negative number. Good job!”);
     }
}

This example does the following:

  • The variable num is being evaluated.

  • The condition checks if the num variable is less than zero.

  • If the condition returns true, the program prints “Your value is a negative number. Try another number.” to the screen.

  • The “num = keyboard.nextInt ( );” statement gets the next value of num, and the condition is evaluated again with the new value.

  • If the condition returns false, the program prints “You did not enter a negative number. Good job!” to the screen.

Best practices for if else statements with compound statements:

  • Make sure all of your statements are enclosed in brackets. As mentioned previously, this aids readability.

  • Position the opening and closing brackets for a code block, with appropriate indentation, on a separate line. This adds a bit more coding, but aids readability.

Example 4: Saving Time with Boolean Operators

The examples so far include less than (<) and greater than or equal to (>=) operators to test the conditions, and for good reason. These relational operators work best to test a single condition. If your if else logic requires testing multiple conditions (also called a compound condition), Boolean operators called short-circuiting operators are ideal to use instead of coding a string of conditions (that could become messy!). The short-circuiting operators get their name from how quickly they can evaluate conditions. For example, in some cases Java does not have to evaluate the second condition. In Java, && (Logical AND) and II (Logical OR) are short-circuit operators.

The following table shows when each operator returns a Boolean (true or false) value.

Logical Operator

True when…

False when…

&&

Both conditions return true

  • At least one condition returns false

II

At least one condition returns true

  • Both conditions returns true

  • Both conditions return false

The syntax for a Java if else statement that contains a compound condition looks like this:

if ((condition 1) logical operator (condition 2))
     {
     Statement to execute if condition is true;
     }
else
    {
    Statement to execute if condition is false;
}

In addition to the placement of the logical operator between the conditions, you should also notice another difference right away. A set of parentheses is placed around each condition as well as the entire compound condition. These are the only two differences in comparison to a statement with a single condition.

Here’s an example if else statement that contains a compound condition that uses the && operator:

if ((a < 5) && (b > 5))
     {
     System.out.println(“This is true!”);
     }
else
    {
    System.out.println (“This is false!”);
    }

In this example, Java evaluates the first condition and then the second according to the following:

  • First condition true, second condition true; statement returns true.

  • First condition false, Java skips second condition; statement returns false.

  • First condition true, second condition false; statement returns false.

If the statement returns true, Java prints “This is true!” on the screen. Otherwise, “This is false!” is printed on the screen.

In this next if else statement we use the II operator to combine conditions:

if ((a == 5) || (b == 10)
     {
     System.out.println(“This is true!”);
     }
else
     {
     System.out.println(“This is false!”);
}

In this example, the decision making works like this:

  • First condition true, Java skips second condition; statement returns true.

  • First condition false, second condition true; statement returns true.

  • First condition false, second condition false; statement returns false.

If the statement returns true, Java prints “This is true!” on the screen. Otherwise, “This is false!” is printed on the screen.

Learning how operators work in Java is essential to programming in the language. You may want to consider a course in Java for complete beginners that teaches the core aspects of the programming language.

Example 5: Nested if else Statements

The examples so far have contained a single condition statement to test. If your program requires a test of multiple conditions, then nested if else statements are what you need. A nested statement is also referred to as a multibranch.

The syntax for nested if else statements:

if (condition)
     {
     Statement to execute if condition is true;
     }
     else if
          {
          Statement to execute if condition is true;
          }
     else if
          {
          Statement to execute if condition is true;
          }
else
     {
     Statement to execute if condition is false;
     }

The following example contains two else if statements.

public static void main (String args[ ])
    {
int score = 85;
if (score < 70)
    {
    System.out.println(“You did not receive a passing score!”);}
         else if (score = = 85)
               {
         System.out.println(“You received a passing score!”);
               }
         else if (score = = 100)
               {
               System.out.println (“You received a perfect score!”); }
else
     {
     System.out.printlin (“I don’t know your score!”);
     }

Here’s the output:

You received a passing score!

In this example, the variable score is set to 30. There are four conditions (tests), each with an output if the condition returns true. The final statement is the output if neither of the conditions returns true:

  • Test 1: If score is less than 70. If true, “You did not receive a passing score!“ is printed to the screen.

  • Test 2: If score equals 85. If true, “You received a passing score! “ is printed to the screen.

  • Test 3: If score is equal to 100. If true, “You received a perfect score! “ is printed to the screen.

  • Test 4: If score does not return true for tests 1-3. If true, “I don’t know your score!” is printed to the screen.

There is no limit to the number of else if statements you can add to a program. However, it is always a good idea to write out and test your logic to discover the most efficient method to achieve the goal of the program. Too many nested if else statements can easily become confusing. Creating a flow diagram of your program is one way to test your logic. This method of testing allows you to visualize the flow of your logic.

Closing Thoughts

This tutorial explained different ways to use if else logic in a Java program. Try modifying the examples or create new ones to practice what you have learned. The if else statement is just one type of condition that you can use in Java. You can also use the following control statements:

  • Conditional statements: In addition to if and if else, there is also the switch statement that tests a condition against several statements.

  • Repetition statements: Loops such as while, for, and do-while.

  • Special control statements: These include the break, continue, and return statements.

The samples in this tutorial contain snippets of code. A course that enables you to learn to program in Java is recommended to give you hands-on experience with the programming language.