Conditional Statements in Java

Ever had to make a decision in Programming using Java? For making decisions based on different conditions in Java is done through Conditional Statements. Conditional Statements within Java are the main building blocks of a Program or anything related to Java. Conditional Statements are easy to understand. So, let’s start.

Following are the conditional statements within Java:

  1. if statement
  2. if else statement
  3. if else if statement
  4. switch statement

if statement

Let’s take an example making if statement easy to understand. Consider a program where the user is requested to input their name which is validated before printing. The Validation criteria depend on the length of the user’s name. If the user’s name is greater than 20 characters including spaces print “Name too long” and if the user’s name is less than 20 characters then print the name. Before converting the example into Java code, let’s go through if statement syntax

if (condition) { code block }
  • if – this is the keyword within Java indicating that an if statement is going to be implemented
  • condition – after the if statement, comes the condition which either can accumulate to true or false and depending on the condition compiler executes the code.
  • code block – code block includes the code to be executed depending on the condition

Note: code block needs to be covered with curly brackets {} if there are more than two lines of codes to be executed and if a single line has to be executed then no curly braces are recommended.

import java.util.Scanner;

public class IfStatement {

    public static void main(String[] args) {

        // Calling the Scanner class
        Scanner scanner = new Scanner(System.in);

        /*
        * Requesting user's name and scanning the input
        * Validating name length
        * Outputting user's name
        * */
        System.out.println("What is your Name?");
        String nameInput = scanner.nextLine();
        if (nameInput.length() > 20) {
            System.out.println("Name too long");
            return;
        }
        System.out.println("Hello, " + nameInput);
    }
}

Output

What is your Name?
This is a test to produce an error
Name too long

Challenge: Try optimizing the above code by adding functions to it.

So, we have converted our example into code and now let’s break it down.

  • Line 8
    • Calling the Scanner class. A Scanner Class in Java enables developers to take input from users within the console.
  • Line 15
    • Printing a string requesting user’s name within the console which makes interaction easy.
  • Line 16
    • Requesting user’s name using Scanner class instance and saving it within a String variable.
  • Line 17 – Line 20
    • Validating the user’s input by checking the length of the input String. If the condition “nameInput.length() > 20” becomes true then Line 18 & 19 will be executed and if the condition becomes false then Line 21 will be executed and further execution will take place.
  • Line 19
    • return is a keyword in Java which passes the execution back to the program rather than moving forward.

if else statement

Moving to the next condition statement, while using the above example. What if we want to know the age of the user. And based on the age output we have to print either the user is an adult or a teenager? Here we have multiple conditions requesting that a user can either be a teenager or an adult. We use the if else statement here which helps us understand dual conditions easily. Let’s update the above example.

import java.util.Scanner;

public class IfElseStatement {

    public static void main(String[] args) {

        // Calling the Scanner class
        Scanner scanner = new Scanner(System.in);

        /*
        * Requesting user's name and scanning the input
        * Validating name length
        * Outputting user's name
        * */
        System.out.println("What is your Name?");
        String nameInput = scanner.nextLine();
        if (nameInput.length() > 20) {
            System.out.println("Name too long");
            return;
        }
        System.out.println("Hello, " + nameInput);

        /*
         * Requesting user's age and scanning the input
         * Validating age
         * Outputting result according to condition
         * */
        System.out.println("How old are you?");
        int ageInput = scanner.nextInt();
        if (ageInput > 18)
            System.out.println("You're an adult");
        else
            System.out.println("You're a teenager");
    }
}

Output

What is your Name?
Dwayne Johnson
Hello, Dwayne Johnson
How old are you?
47
You're an adult

Challenge: Try requesting user to enter their gender and find out either the user is a male or female

Let’s break down the above code to understand what was updated

  • Line 29
    • We are receiving age from the user within the console and saving to an int data type. As age is a number, it is recommended to choose a data type which deals with numbers. As it is possible to store an age within a String data type but not recommended because it is better to use the preferred data type according to the situation. And on the other hand “scanner.nextInt()” returns an integer so it won’t be possible to save the age within the String data type.
  • Line 30 – Line 33
    • Here is the if else condition which checks for the age input within the console and decides whether the user is an adult or a teenager. If you look closely, I haven’t used any brackets and indented the code within the if block because there is a single line of code to be executed within the code block. And one more thing to notice is that there isn’t any return statement written. The reason is simple because we are not returning the execution to the program, as it is the end of the program, the execution will automatically return to the program.

Note: If the first condition on Line 17 becomes true, the program doesn’t continue because of the return statement.


if else if statement

If else if condition statement enables developers to implement multiple conditional statements with if else if statements. Taking the above example and adding another feature to it which lets the user pick a color from a provided list of colors. Here is the syntax for if else if statement

if (condition) {
    // code block
} else if (condition) {
    // code block
} else {
    // code block
}

The else if block also takes a condition if there are multiple conditions to be handled. Using the if else if statement syntax template let’s update the above example with color selection feature.

import java.util.Scanner;

public class IfElseIfStatement {

    public static void main(String[] args) {

        // Calling the Scanner class
        Scanner scanner = new Scanner(System.in);

        /*
         * Requesting user's name and scanning the input
         * Validating name length
         * Outputting user's name
         * */
        System.out.println("What is your Name?");
        String nameInput = scanner.nextLine();
        if (nameInput.length() > 20) {
            System.out.println("Name too long");
            return;
        }
        System.out.println("Hello, " + nameInput);

        /*
         * Requesting user's age and scanning the input
         * Validating age
         * Outputting result according to condition
         * */
        System.out.println("How old are you?");
        int ageInput = scanner.nextInt();
        if (ageInput > 18)
            System.out.println("You're an adult");
        else
            System.out.println("You're a teenager");


        /*
         * Requesting color choice from user
         * Validating color choice
         * Outputting result according to condition
         * */
        System.out.println("Pick a color?\n" +
                "1. Black\n" +
                "2. Blue\n" +
                "3. Red\n" +
                "4. Green\n" +
                "5. Yellow");
        int colorInput = scanner.nextInt();
        if (colorInput == 1)
            System.out.println("You like Darkness!");
        else if (colorInput == 2)
            System.out.println("You're Productive!");
        else if (colorInput == 3)
            System.out.println("You\'re a Loving Person!");
        else if (colorInput == 4)
            System.out.println("You're Natural!");
        else if (colorInput == 5)
            System.out.println("You're Bright!");
        else 
            System.out.println("Wrong Selection!");
    }
}

Output

What is your Name?
Dwayne Johnson
Hello, Dwayne Johnson
How old are you?
47
You're an adult
Pick a color?
1. Black
2. Blue
3. Red
4. Green
5. Yellow
4
You're Natural! 

Challenge: Try optimizing the above program with functions and any other conditional statements possible.

Let’s dive deep into the changes made within the above program

  • Line 48 – Line 59
    • There are multiple choices based on user input. If the user chooses a number from 1 to 5, the output is executed according to the color selected but if a number lower than 1 or greater than 5 is selected then else block is executed as written on Line 58 & 59. There is a better way of optimizing this color selection process with the switch statement.

Switch Statement

A switch is a conditional statement in Java which resembles the if else if statement but is different when it comes to execution. The difference between the switch statement and if else if statement is the syntax and the compilation method. Switch statement does not execute every statement to find the true statement like if else if statement, it finds the true statement and then proceeds within the code block and if not found then the default case is executed. Here is the switch statement syntax

switch (expression) {
    case [value]:
        // code block
        break;
    case [value]:
        // code block
        break;
    default:
        // code block
        break;
}
  • switch – switch is the keyword used to implement a switch statement within Java
  • expression – the value within the expression is compared to each case to identify the true statement to be executed.
  • case – case is the keyword which is used to present a choice within the switch statement.
  • value – value is compared with the expression to identify true statement. No conditions or operators are allowed within the value parameter.
  • break – break is also a keyword which enables a developer to break out of a switch statement after a case or the default case is true. If break keyword isn’t written, execution is passed below to the next case statement until a break statement is found and if not found within the switch statement then all cases will be executed.
  • default – default is also a keyword of a switch statement which is used to execute when no case matches the expression provided.

Let’s optimize the above program with the switch statement.

import java.util.Scanner;

public class SwitchStatement {

    public static void main(String[] args) {

        // Calling the Scanner class
        Scanner scanner = new Scanner(System.in);

        /*
         * Requesting user's name and scanning the input
         * Validating name length
         * Outputting user's name
         * */
        System.out.println("What is your Name?");
        String nameInput = scanner.nextLine();
        if (nameInput.length() > 20) {
            System.out.println("Name too long");
            return;
        }
        System.out.println("Hello, " + nameInput);

        /*
         * Requesting user's age and scanning the input
         * Validating age
         * Outputting result according to condition
         * */
        System.out.println("How old are you?");
        int ageInput = scanner.nextInt();
        if (ageInput > 18)
            System.out.println("You're an adult");
        else
            System.out.println("You're a teenager");


        /*
         * Requesting color choice from user
         * Validating color choice
         * Outputting result according to condition
         * */
        System.out.println("Pick a color?\n" +
                "1. Black\n" +
                "2. Blue\n" +
                "3. Red\n" +
                "4. Green\n" +
                "5. Yellow");
        int colorInput = scanner.nextInt();
        switch (colorInput) {
            case 1:
                System.out.println("You like Darkness!");
                break;
            case 2:
                System.out.println("You're Productive!");
                break;
            case 3:
                System.out.println("You\'re a Loving Person!");
                break;
            case 4:
                System.out.println("You're Natural!");
                break;
            case 5:
                System.out.println("You're Bright!");
                break;
            default:
                System.out.println("Wrong Answer!");
                break;
        }
    }
}

Output

What is your Name?
Dwayne Johnson
Hello, Dwayne Johnson
How old are you?
47
You're an adult
Pick a color?
1. Black
2. Blue
3. Red
4. Green
5. Yellow
4
You're Natural! 

Challenge: Tell us in the comments if it is okay to convert every conditional statement to switch within the above program?

  • Line 48 – Line 67
    • Using the switch statement syntax template we have converted the above code which was in if else if statement and now it is optimized through the switch statement. The expression here is the input received by the user and depending on the user’s input the matching case is executed, for example within the output of the program I’ve chosen 4 as my input and the result executes code block under case 4. If I would’ve chosen a wrong number that isn’t related to any case within the switch statement then the default case would have been executed

These are the conditional statements which are used mostly within Java. Using these statements can make decisions really easy within the world of Java Programming.

Code on Github:

Related: