Else statement Java: performs operations when the conditions of the if statement are false


Keywords: else statements, if statements, conditional statements

if else statement Java

This article will look at the else statement in Java, also referred to as the if-…else statement in Java. An else statement is used in conjunction with the if statement (as we looked at in the previous article) when you want to perform one or more operations when the conditions in the if statement is false.

What is else statement in Java?

The else statement in Java is used to specify a block of code to be executed if the condition in the if statement is false. Additionally, the else statement is an optional feature that must be used in conjunction with an if statement. Thus, you cannot only use the else statement.

The keywords used for the if statement and else statement describes their relationship quite well. “If this condition is true, perform the associated code block, else, execute this code block”. However, the else statement does not have a condition that it evaluates before performing the operations in the associated code block.

Short summary, the else statement:

  • Must be used in conjunction with an if statement.
  • Executes when the condition in the if statement is false.
  • The else statement has no condition that it evaluates and is executed based on the result of the if statements condition.

How the else statement in Java works?

Similar to what we did in the previous article on if statements, let us use a flow chart to illustrate the else statement and how it operates.

Else statement Java programming

Figure 1: Else statement in Java illustrated with a flowchart

The flow chart illustrates ….Flödesschemat visar hur if-villkoret avgör om if-satsens operationer ska utföras om if-villkoret är true eller om else-operationerna ska utföras om if-villkoret inte är uppfyllt. Det vi ser helt enkelt är att ifall if-villkoret inte är uppfyllt så utför programmet else-satsens kodblock innan det det fortsätter vidare.

How to create else statement in Java?

The else statement is declared using the reserved word else followed by curly brackets { } containing the code block belonging to the else statement. Remember that the else statement does not evaluate a logical condition like the if statement. Therefore, we are not using the parentheses that the if statement has.

Syntax: Declare else statement in Java

Since the else statement always has to be used in conjunction with an if statement, we will show the syntax for them both

if (logical expression) {

     // if statements code block
}

else {

     // else statements code block
}

Examples: Else statement in Java

Let’s look at two examples on how to use the else statement combined with the if statement. First, we will start with an example where we create an else statement and print a text. The second example, we will program a fictional lamp that is controlled with the help of an on/off button.

Example 1: Create else statement in Java

This example clearly shows how the else statement complements the if statement and how they work together.

public class Example{
  public static void main(String[] args) {

    int number = 5; 

    if (number > 6) {
      System.out.println("This is the IF statement"); 
    } 

    else {
      System.out.println("This is the ELSE statement");
    }
  }
}

Since the variable number is not greater than the value 6 (if statement condition), the result will be:

This is the ELSE statement

However, if we change the value of number to

int number = 8;

We get the result

This is the IF statement

To conclude, it becomes evident that the else statement only performs the operations when the if statement’s conditions are false. If you want to test the code in the example yourself, click on the button below. Feel free to try changing the terms and add several different comparisons to the if statement.

Example 2: Use the if statement and else statement to control a lamp

You can imagine that you want to program a lamp.

  • If the light is off and we press the light button, we want to turn on the lamp.
  • On the other hand, if the light is already on, we want to turn off the light – even though we press the same button.
  • Hence, the same button can execute different commands, depending on the current condition we have. In this case, we have two conditions: on or off.

Let’s illustrate the example by using a flow chart

Else statement example Java

Figur 2: Else statement example

We will start by declaring a Boolean variable to track whether the lamp is on or off.

// The variable is declared false, so the lights is off
boolean isLampOn = false; 

Furthermore, we want the program to turn off the light if the lamp is on, and on the contrary turn on the light if the lamp is turned off. It is not possible to turn on the lamp if it is already on or turn off the lamp when it is already off.

// If the lamp variable is true, thus lights are on
if(isLampOn == true){    

   // Set the variable to false; the light turned off
   isLampOn = false;     
} 

// When the if statements condition is false, thus lights are off
else{                  

    // Set the variable to true; the light turned on
    isLampOn = true;       
}

That is, when the variable isLampOn is true, we will change the value of the variable to false. Correspondingly, we set the variable to true when the if statement is false by using the else statement.

Why use else statement in Java?

I’m sure you already have got an understanding of why the else statement in Java is so useful. But to be extra clear; what if we want our program to perform an operation when the if statements condition is false, this is where the else statement comes to use. Hence, we can use the else statement together with the if statement to execute a code block when the If statement’s conditions are false.

Common errors and mistakes when using the else statement in Java

Finally, let us briefly look at a couple of simple and common mistakes. Note that these are just a few common errors that we have noted, there are, of course, more mistakes you can make.

  • A common mistake is actually not being aware that an else statement is needed. You may be at a “crossroads” in your program and, for example, asking the user for input. But if you only specify what should happen in one of the cases (if) and not what occurs otherwise (else), it may end up that you don’t proceed in the program. For example, if you ask the user to enter the password and only states what will happen when the user enters the right password (if statement), and not what will happen otherwise (else statement).
  • Try using a condition in the else statement. Remember, an else statement has no condition. If we instead want more conditions to evaluate after the if statement, we can use an else-if statement that we will explain in the next article.
  • Finally, accidentally use a semi-colon after the If statement, perhaps not as common but it can happen. However, your compiler will most likely warn you to this error. The example below shows what it might look like:
int x = 5;

if( x > 10) {
    System.out.print("X is larger than 10");
};
            
else {
    System.out.print("X is not larger than 10");
}

Summary: Else statement in Java

The else statement in Java is used to specify a block of code to be executed if the condition in the if statement is false. The keywords used for the if statement and else statement describes their relationship quite well. “If this condition is true, perform the associated code block, else, execute this code block”.

  • The else statement must be used in conjunction with the if statement.
  • The else statement is declared using the reserved word else followed by curly brackets { } containing the code block belonging to the else statement.
  • Else statement has no condition that it evaluates and is executed based on the result of the if statements condition.

Syntax: Declaring else statement

if (logical expression) {

     // if statements code block
}

else {

     // else statements code block
}

Frequently asked questions: Else statement in Java

Do you have to use the else statement?

No, It’s not required to write the else statement when using the if statement. However, it should be said that it can be advantageous to use an else statement, especially when there is a risk that the program “gets stuck” if the conditions of the if statement are not met.

Is it possible for the else statement to evaluate a condition?

No. The else statement in Java has no condition.

Can you perform both the if statement and the else statement?

No. Your program will perform either the if statement or the else statement, it’s not possible to execute both of them.

How useful was this article?

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?