If statement in Java: Control the logic in our program


Keywords: if statement, conditional statements, boolean, flowchart

if statement Java

This article will cover the if statement in Java. The if statement is a conditional statement that enables us to control the logic of our programs. Since all programming is based on conditions, the if statement can be seen as one of the cornerstones of programming.

What is the if statement in Java?

An if statement in Java determines whether the program should perform one or several operations, depending on whether one or more prespecified conditions are reached or not. The condition specified is a logical expression that is either true or false. In other words, we use a logical expression to decide if our programs should execute a certain code or not. Meaning, by using the if statement, you can specify what should happen if a condition is met or not. This creates conditional programming, which is the basis of all logic in a program.

In short, the if statement in Java is:

  • A conditional statement that determine what will happen in the program depending on its conditions.
  • Has a condition that always results in a boolean variable (true or false).
  • Forms the basis for logic in our programs.

The if statement in Java determines whether an operation should be performed or not, depending on the condition

How if statement in Java works?

Let’s try and illustrate an if statement using a flow chart. If you don’t know what a flow chart is, or need to refresh your memory, you can read more about flow charts in the article on algorithms.

If statements Java programming

Figure 1: If statement in Java illustrated with a flowchart

What figure one shows is that: 

  • First, the program starts and arrives at the if condition.
  • When the if condition is true, that is, the condition is met, then the program proceeds and performs one or more operations that we have specified.
  • But if the condition is not met, in other words false, then the program skips the operations and moves on.

Remember: It is possible to use one or more conditions that indicate whether the program should perform the operation or not.

How to create an if statement in Java?

  • The if statement is easily declared by the reserved word if followed by a logical expression in parentheses ( )
  • The operations within the curly brackets { } are the program section that belongs to the if statement and that the program runs if the condition is true (fulfilled condition).
  • When the if statement is false (condition not fulfilled), the program will continue to run after the curly brackets.

Syntax: Declare if statement in Java

If we use the points above and enter it in the code editor, we get:

if (logical expression) {
         
      // Code block 

}

Examples: If statement in Java

Let’s look at a few examples of how to create and use an if statement in Java. We will first take a simple example to show how the if statement works. Then we will see two examples of how we can use the if statement, the first one with a boolean variable and the second one where we check the value of an int variable.

Example 1: Declare an if statement

In the following program, we show an example of how the if statement only runs the operations when the condition is true. Finally, the program continues as usual after the if statement.

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

      // if statement is true, therefore, be executed
      if(true){
        System.out.println("if statement run");
      }

      // if statement not true, therefore, not executed
      if(false){
          System.out.println("if statement not executed");
      }

      // The program continues
      System.out.println("The program continues");

  }
}

Resulting in

if statement run
The program continues

If you want to test the code above yourself, click on the button below. Try replacing the logical condition and add variables and conditional operators.

Example 2: Use an if statement with a Boolean variable

The second example we are going to look at uses a Boolean variable, that is, a variable that only can have the values; true or false.

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

    // Variable assigned the value true
    boolean sayHelloWorld = true;              

    // If the variable is true, execute the command
    if(sayHelloWorld){        
                        
      // Print the text
      System.out.println("Hello World!"); 
    }
  }
}

What this example shows is that if the variable sayHelloWorld is true, then the program prints the text line Hello World! in the terminal window. However, if we change row 5 to

boolean sayHelloWorld = false;

and run the program, we will not get the Hello World! in the terminal window.

Example 3: If statement with conditional and relational operators

The third and final example will use conditional and relational operators to see if the value of an integer variable is within a range between 0 and 200. What we want to do is that if the variable num is greater than 0 and less than 200, we get a text in the terminal window stating: Number: num if an int variable is within a range e.g. between 0 and 200.

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

    int num = 100;

    if(num > 0 && num < 200){  
      System.out.println("Number: " + num);
    }
  }
}

Resulting in

Number: 100

Why use the if statement in Java?

You could say that the conditional statements in programming, and more specifically the if statement, are used as a decision point to control several different conditions. Based on these conditions, you can then take a different action for each condition depending on the result.

The if statements are similar to loops (as we will see in the next chapter) because they both control a given condition. However, the if statement only checks the condition once, while the loop continues to check the condition until it is no longer true. Remember: It is possible to use one or more conditions that indicate whether the program should perform the operation.

Example: When to use an if statement?

For example, if you want to execute something in your program depending on the input, you get from the user. Then the if statements implement perfectly. For example, say you want to show an introductory video to a user using your program for the first time. Of course, you do not want to show the introductory film if the user has already seen the video. You can easily control the logic in your program by taking in information from the user and based on the answer; you show the introductory video in the program.

This was just a short example; there are countless possibilities to use if statements. Remember, in all programming, the logic of the program is controlled using if statements.

Common errors when using the if statement in Java

Let’s look at a few common and simple mistakes that are easy to make. Note that these are just a few common mistakes that we have noted, there are, of course, more mistakes that can happen.

Furthermore, remember that your compiler will help you and warn you before you move on, but it is always good to be attentive and careful.

Besides more straightforward declaration errors, for example, that you forget one of the curly brackets to close the code block, it is mainly in the condition of the if statement that errors usually occurs. Let’s have a look at what we mean.

Equal-to-comparison operand is expressed with double equals, i.e. ==, not a single =. A simple equal sign = is an assignment. For example, to compare if two variables are equal to each other, we use ==. See the example below where we compare if x is equal to 1.

if(x = 1)  // error
if(x == 1) // valid comparison

Furthermore, incorrect use of the or operand, ||. The conditions must be tested with separate comparisons.

if(input == 'y' || 'Y')            // error
if(input == 'y' || input == 'Y')   // valid comparison

Finally, incorrect use of the && operator. These conditions must also be tested with separate comparisons. For example, to test if the value of x is greater than 0, but also smaller than 31:

if (0 < x < 31)        // error
if (0 < x && x < 31)   // valid comparison

In general, incorrect use of an operator can be avoided by always placing the variable to be evaluated on the left side of the expression. The compiler will then mark the mistakes that trigger an invalid assignment.

Summary: If statement in Java

The if statement in Java is a conditional statement that determines whether the program should perform an operation, or several operations, depending on whether one or more specified conditions are met or not. The condition is a logical expression that is either true or false.

  • The condition statements, and more specifically the if statement, are used as a decision point to check a number of different conditions.
  • The if statement enables us to control the logic of our programs.
  • It is possible to use one or more conditions that indicate whether the program should perform the operation.

Syntax: Declaring if statement in Java

if (logical expression) {
         
      // Code block 

}

Frequently asked questions: If statement in Java

How to declare the if statement in Java?

The if statement is easily declared by using the reserved word if followed by a logical expression in parentheses (). After that, you declare the program section that belongs to the if statement using seagull wings. Finally, inside the curly brackets, you state code block that is performed if the conditions of the if set are met

What are conditional statements in programming?

This means that with the help of a condition statement you can control how the flow in the program should move when a certain condition is met. In other words, with the help of conditions, you can control the direction of the programs and perform different things depending on whether these conditions are met or not.

If I want to evaluate the condition in the if statement several times, how do I declare that?

The easiest way is presumably that you use a loop or a method. A loop allows you to run part of your program as long as the condition is met, compared to the if statement that only evaluates it once. Additionally, a method allows you to use the same code, such as an if statement, several times without rewriting it over and over again. We will, of course, look closer at both loops and methods in future chapters.

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?