JavaJava Decision Making: IF, THEN, ELSE

Java Decision Making: IF, THEN, ELSE

Java programming tutorial

Usually, statements in Java code are executed in the order in which they appear. However, Java provides statements that can be used to control the flow of code. One of the fundamental features of Java, if statements are known as control flow statements because they help steer the course of program flow. In this programming tutorial, we will learn how to use the if statement and then-else variations with the help of code examples.

Read: Best Tools for Java Mobile Development

The if Statement in Java

The if statement is a decision-driven statement that executes a particular set of code based on a condition. In its simplest form, the if statement helps developers decide whether a certain statement or block of statements will be executed based on the result of a condition. The syntax of the if statement in Java is quite simple:

if(condition) 
{
   // Statements to execute if
   // condition is true
}

Here is a code example showing how to use an if statement in Java:

public class IfExample
{
  public static void main(String[] args) {
    int age = 20;  

    if (age > 18) {  
      System.out.print("You are a grown-up.");  
    }
  }
}

Since the age variable’s value is indeed greater than 18, the if’s code block executes and prints “You are a grown-up.” to the console.

The if-else Statement in Java

The Java if-else statement works exactly in the same way as the simple if statement, except that it includes an else block, which is executed if the test condition evaluates to false.

The following program builds on the previous one by providing an alternate message if the age variable contains a value that is 18 or less:

public class IfElseExample
{
  public static void main(String[] args) {
    int age = 12;  

    if (age > 18) {  
      System.out.print("You are a grown-up.");  
    } else {
      System.out.print("You are still a minor.");  
    }
  }
}

This time, the program displays the “You are still a minor.” message because the condition evaluates to a boolean value of false based on the age of 12.

You can learn more about boolean values in our tutorial: What are Java Booleans?

If-else Versus the Ternary Operator

Both the if-else statement and ternary operator evaluate a condition and contain a true or false component. So, how do programmers decide on which to use? The main difference between the if-else statement and ternary operator is that the former can execute a block of code while the latter can only return a value based on a condition. This makes the ternary operator ideal for setting a variable or as part of an expression that evaluates to a boolean. An if-else statement can also be employed to set a variable based on a condition, but its code is a bit more repetitive and cumbersome. Looking at the code below, which of the two would you prefer?

// Given:
int age = 12;

// Assigning a string value using the ternary operator:
String status = age > 18 ? "adult" : "minor";

// ...using and if-else statement:
String status = "";
if (age > 18) {
  status = "adult";
}
  status = "minor";
}

The if…else (if-then-else) Statement in Java

For more conditions, developers can chain multiple if-else statements together to form an if…else…if ladder, as shown in the code example below:

if (condition1) {
  // code1
}
else if(condition2) {
  // code2
}
else if (condition3) {
  // code3
}
.
.
else {
  // default code
}

As always, if conditions are evaluated from top to bottom. When the test condition is true, code inside that if block is executed and program control jumps outside the if…else…if ladder. The last else statement is optional and acts as a default block that only executes if all test expressions are false.

The following program evaluates an int variable that stores a ranking score out of 100 and prints a message based on its value:

public class IfThenElseExample {  
  public static void main(String[] args) {  
    int ranking = 76;  
      
    if(ranking < 50){  
      System.out.println("You are a bottom feeder.");  
    }  
    else if(ranking >= 50 && ranking < 60){  
      System.out.println("Could be worse.");  
    }  
    else if(ranking >= 60 && ranking < 70){  
      System.out.println("Not bad, but you could do better.");  
    }  
    else if(ranking >= 70 && ranking < 80){  
      System.out.println("This is a middling ranking.");  
    }  
    else if(ranking >= 80 && ranking < 90){  
      System.out.println("Good job!");  
    } else if(ranking >= 90 && ranking < 100){  
      System.out.println("You scored at the top of the heap!");  
    } else {  
      System.out.println("Invalid ranking score!");  
    }  
  }  
}  

The above program prints “This is a middling ranking.” because the score falls in between 70 and 80.

If-then-else Versus the Java Switch Statement

You may have noticed that the if-then-else statement does essentially the same thing as a switch statement; both test multiple conditions and have a default block. When deciding which to use in a given situation, keep in mind that the if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object.

Another point worth considering is that many developers consider the switch statement to be more error prone than the if-then-else statement, and not without reason. You probably would not have to look to far to find someone who forgot to include a break statement and introduced a bug in the process (ok, it was me).

You can learn more about the switch statement in our tutorial: Overview of the Java Switch Statement. If you want to learn more about the break statement, check out: Java Break and Continue Statements.

Nesting if Statements in Java

The code blocks of if-else statements may contain any legal Java code, including other if and/or if-else statements. Here is what the syntax for a nested if…else would look like in Java:

if(Boolean_expression 1) {
   // Executes when the Boolean expression 1 is true
   if(Boolean_expression 2) {
      // Executes when the Boolean expression 2 is true
   }
}

The following program is based on the earlier one that prints a message based on an age variable. This one displays a second message depending on the result of a more stringent condition:

public class NestedIfExample {    
  public static void main(String[] args) {    
    //Creating two variables for age and weight  
    int age = 10, weight = 49;  
    
    if (age > 18) {  
      System.out.println("You are a grown-up.");  
    } else {
      System.out.println("You are still a minor.");  
      
      if(age >= 10 && weight < 50){  
        System.out.println("You are a little light based on your age.");  
      } 
    }   
  }
}  

In the above code, the System.out.println statement inside the else block prevents us from evaluating the second condition as part of the outer else statement, making it necessary to nest the second if statement.

Final Thoughts on Java Decision Making: IF, THEN, ELSE

In this programming tutorial we learned how to use the if statement and if-then-else variations. In Java these are your best choice when writing decision-driven statements that execute a particular block of code based on one or more conditions.

Read: Top Collaboration Tools for Software Developers

Get the Free Newsletter!
Subscribe to Developer Insider for top news, trends & analysis
This email address is invalid.
Get the Free Newsletter!
Subscribe to Developer Insider for top news, trends & analysis
This email address is invalid.

Latest Posts

Related Stories