Conditional Statements in Java

Control flow statement are nothing but logical statements which will choose the path of the to be executed.

Conditional Statements
  • if
  • if..else
  • if..else..if
  • nested if
  • Switch

if condition in Java

if-else-block-diagram

If statements are used as decision points to check a series of possible conditions, then take a decision to change the path of the program for each condition depending on the outcome.

In layman words: You want to travel to a distance, you could either use train or car, normally what we do is, if the distance is 20 miles we take our car and go there but if the distance is more than 20 miles we take the train and go to destination.

In this example, the distance is the deciding factor, so based on this deciding factor, we will travel.

If condition takes the decision based on the expression given if accepts an expression that would result in either true or false.

The following program takes decision-based on loan; it is a practical example.

public class IfCondition {
    public static void main(String[] args) {
        // distance in miles
        String  loan = "Educational Loan";
        if(loan == "Educational Loan")
        {
            System.out.println("Sorry, we don't provide loans");
        }
    }
}

In the above code, if the loan is "Educational Loan" then expression resolves to true, then we want to print the message "Sorry, we don't provide loans".

Curly brackets are optional if you have only one line of code inside if block.

public static void main(String[] args) {
        // distance in miles
        String  loan = "Educational Loan";
        if(loan == "Educational Loan") System.out.println("Sorry, we don't provide loans");
    }

Sometimes we want to have other option to do something when the expression don't resolve to true.

if..else :

else is the optional block used to execute if the expression in the if doesn't resolve to true.

Either if block gets executed or else block, not both blocks get executed, and one block must get executed.
public class IfCondition {
    public static void main(String[] args) {
        // distance in miles
        String  loan = "Car Loan";
        if(loan == "Educational Loan") {
            System.out.println("Sorry, we don't provide loans");
        }else {
            System.out.println("We provide loan in 10 minutes");
        }      
    }
}

if..else..if :

Sometimes we want to take a decision in else block as well when we have more than one option; In such cases, we can use if..else..if block.

public static void main(String[] args) {
        // distance in miles
        String  loan = "Car Loan";
        if(loan == "Educational Loan") {
            System.out.println("Sorry, we don't provide loans");
        }else if(loan == "Car Loan"){
            System.out.println("We provide loan in 10 minutes");
        }      
    }

if..else..if..else :

We can add more if and else blocks in Java, but one if block can have only one respective else block.

public static void main(String[] args) {
        String loan = "Car Loan";
        if(loan == "Educational Loan")
        {
            System.out.println("Sorry, we don't provide Educational Loan");
        }else if(loan == "Agriculture Loan"){
            System.out.println("We donot provide Agriculture Loan");
        }else{
            System.out.println("We provide only luxury loans");
        }      
    }

Nested if :

Sometimes you have to take multiple decision based on the first decision you might get two paths to choose, and you have to select one in it, again you may need to choose one, and then it goes on.

In such kind of situations, it is better to use nested if statements in Java, you can also have nested if statements in else block as well.

public static void main(String[] args) {
        // distance in miles
        String loanBroadType = "Basic Loan";
        String loanSpcifictype = "Educational Loan";
        if(loanBroadType == "Basic Loan")
        {
            if(loanSpcifictype == "Educational Loan"){
                System.out.println("Sorry, we don't provide Educational Loan");
            }
        }else{
            if(loanSpcifictype == "car Loan"){
                System.out.println("yes, we provide Car loans");
            }
        }      
    }

Switch case in Java

A switch case is used to test variable equality for a list of values, where each value is a case. When the variable is equal to one of the cases, the statements following the case are executed.

The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression. As such, it often provides a better alternative than an extensive series of if-else-if statements.

Java switch Statement contains multiple cases, where each case has a value.

  • The value inside the parenthesis of a switch statement expression is tested for equality against the value of each case.
  • The case has a value matching to the value of switch case is executed.

switch-statement-syntax

Syntax of Switch case statments:

switch(varaible){
    case valueOne:
        // code to execute
        break;
    case valueTwo:
        // code to execute
        break;
    default:
        //optional
}

Example of switch case in java :

import java.util.Scanner;
class example
{
    public static void main(String args[])
    {
        Scanner in=new Scanner(System.in);
        System.out.print("Enter any choice(Ex 'Y for Yes','N for No','M for Maybe') : ");
        char choice=in.next().charAt(0);
        switch(choice)
        {
            case 'Y':
              System.out.println("Yes");
              break;
            case 'N':
              System.out.println("No");
              break;
            case 'M':
              System.out.println("Maybe");
              break;
            default:
              System.out.println("Invalid choice ");
        }
    }
}

output-of-switch-case-java

Importance of break statements in Switch case

When we write if-else block, we do not need to write any break statements, but when we are writing the Switch case, It is optional to write the break statement.

break statements denote the end of execution of a block. Whenever the compiler faces a break, it terminates the block there itself. When it comes to Switch, we usually have more than one Case, so it becomes important to use break statements to avoid the execution of other cases.

If we do not use the break statement in the cases all the cases will be executed which are present after the matching case.

For example, try to remove the break statements in the above program, the program will look like below.

import java.util.Scanner;
public class SwitchCase
{
    public static void main(String args[])
    {
        Scanner in=new Scanner(System.in);
        System.out.print("Enter any choice(Ex 'Y for Yes','N for No','M for Maybe') : ");
        char choice=in.next().charAt(0);
        switch(choice)
        {
            case 'Y':
              System.out.println("Yes");
            case 'N':
              System.out.println("No");
            case 'M':
              System.out.println("Maybe");
            default:
              System.out.println("Invalid choice ");
        }
    }
}

switch-case-without-break

Differences between Switch case and If conditions

The switch statement is used in java to compare different values(cases) of a particular variable while if..else.. is used to control the flow of execution based on relational logic you define.

The important point to note here is that switch can not evaluate relational logic, i.e., you can not use relational operators in a switch statement, therefore, making if..else.. more flexible in terms of condition checking.

Bear in mind if you only want to use equality checks of primitive types, String and enums then using switch case is better because switch uses table lookups which are almost always better performers than a relation evaluation.

Both will do the job, but if you have more than three options, then the switch option makes the code far more manageable/readable.

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions