Decision making statement in Java

Java decision-making statements allow you to make the decision, based upon the result of a condition given. There are one or more conditions to be evaluated by the program, along with a statement or statements that are to be executed if the condition is found to be true, and optionally, other statements to be executed if the condition is found to be false.

Here is the flow diagram of decision-making technique in java:

Decision Making Technique

Java’s Selection Statements:

  • The if Statement

The if statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true.

void applyBrakes() {
    // the "if" clause: bi-cycle must be moving
    if (isMoving){ 
        // the "then" clause: decrease current speed
        currentSpeed--;
    }
}

If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end of the if-then statement.
In addition, the opening and closing braces are optional, provided that the “then” clause contains only one statement:

void applyBrakes() {
    // same as above, but without braces 
    if (isMoving)
        currentSpeed--;
}

Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more brittle. If a second statement is later added to the “then” clause, a common mistake would be forgetting to add the newly required braces. The compiler cannot catch this sort of error; you’ll just get the wrong results.

  • The if-else Statement

The if-else statement provides a secondary path of execution when an “if” clause evaluates to false.

void applyBrakes() {
    if (isMoving) {
        currentSpeed--;
    } else {
        System.err.println("The bicycle has " + "already stopped!");
    } 
}

The following program, IfElseDemo, assigns a grade based on the value of a test score: an A for a score of 90% or above, a B for a score of 80% or above, and so on.

class IfElseDemo {
    public static void main(String[] args) {
        int testscore = 76;
        char grade;
        if (testscore >= 90) {
            grade = 'A';
        } else if (testscore >= 80) {
            grade = 'B';
        } else if (testscore >= 70) {
            grade = 'C';
        } else if (testscore >= 60) {
            grade = 'D';
        } else {
            grade = 'F';
        }
        System.out.println("Grade = " + grade);
    }
}

Output:

Grade = C

You may have noticed that the value of testscore can satisfy more than one expression in the compound statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the appropriate statements are executed (grade = ‘C’;) and the remaining conditions are not evaluated.

  • The nested-if  Statement

Nested if statements mean an if statement inside an if statement. Yes, Java allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.

public class nestedIfExample{
        public static void main(String args[]){
        int x=30;
        int y=10;
          if(x==30){
            if(y==10){
              System.out.println("X = 30 and Y = 10");
            }
          }
      }
  }

Output:

X = 30 and Y = 10 
  • The If-else-If Statement

Here, a user can decide among multiple options. The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.

public class If_Else_If_Statement {
     public static void main(String args[]){
     int age = 25;
     if(age>=30){
        System.out.println("Age is greater than 25");
     }else if(age>=28){
        System.out.println("Age is greater than 25");
     }else if(age>=19){
        System.out.println("Age is greater than 19");
     }else{
        System.out.println("Failed Condition");
     }

Output:

Age is greater than 19
  • The switch Statement

Unlike if and if-else statements, the switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer

Example of Switch Statements:

public class SwitchDemoFallThrough {
   public static void main(String args[]) {
        java.util.ArrayList futureMonths = new java.util.ArrayList();
        int month = 8;
        switch (month) {
            case 1:  futureMonths.add("January");
            case 2:  futureMonths.add("February");
            case 3:  futureMonths.add("March");
            case 4:  futureMonths.add("April");
            case 5:  futureMonths.add("May");
            case 6:  futureMonths.add("June");
            case 7:  futureMonths.add("July");
            case 8:  futureMonths.add("August");
            case 9:  futureMonths.add("September");
            case 10: futureMonths.add("October");
            case 11: futureMonths.add("November");
            case 12: futureMonths.add("December");
                     break;
            default: break;
        }
        if (futureMonths.isEmpty()) {
            System.out.println("Invalid month number");
        } else {
            for (String monthName : futureMonths) {
               System.out.println(monthName);
            }
        }
    }
}

Output:

August
September
October
November
December

The following code example, SwitchDemo2, shows how a statement can have multiple case labels. The code example calculates the number of days in a particular month:

class SwitchDemo2 {
    public static void main(String[] args) {
        int month = 2;
        int year = 2000;
        int numDays = 0;
        switch (month) {
            case 1: case 3: case 5:
            case 7: case 8: case 10:
            case 12:
                numDays = 31;
                break;
            case 4: case 6:
            case 9: case 11:
                numDays = 30;
                break;
            case 2:
                if (((year % 4 == 0) && 
                     !(year % 100 == 0))
                     || (year % 400 == 0))
                    numDays = 29;
                else
                    numDays = 28;
                break;
            default:
                System.out.println("Invalid month.");
                break;
        }
        System.out.println("Number of Days = "
                           + numDays);
    }
}

Output:

Number of Days = 29

Example of use of String in Switch Statements:

public class StringSwitchDemo {
    public static int getMonthNumber(String month) {
        int monthNumber = 0;
        if (month == null) {
            return monthNumber;
        }
        switch (month.toLowerCase()) {
            case "january":
                monthNumber = 1;
                break;
                 case "february":
                monthNumber = 2;
                break;
            case "march":
                monthNumber = 3;
                break;
            case "april":
                monthNumber = 4;
                break;
            case "may":
                monthNumber = 5;
                break;
            case "june":
                monthNumber = 6;
                break;
            case "july":
                monthNumber = 7;
                break;
            case "august":
                monthNumber = 8;
                break;
            case "september":
                monthNumber = 9;
                break;
            case "october":
                monthNumber = 10;
                break;
            case "november":
                monthNumber = 11;
                break;
            case "december":
                monthNumber = 12;
                break;
            default: 
                monthNumber = 0;
                break;
        }
        return monthNumber;
    }
    public static void main(String[] args) {
        String month = "August";
        int returnedMonthNumber =
            StringSwitchDemo.getMonthNumber(month);
        if (returnedMonthNumber == 0) {
            System.out.println("Invalid month");
        } else {
            System.out.println(returnedMonthNumber);
        }
    }
}

Output:

8 
  • Jump Statements

    Java supports three jump statements break, continue and return. These statements transfer control to that part of the program of which condition is satisfied.

    • breakstatement: The break statement is used to terminate statement sequence. If the break statement is not written, then all statement execute after match statement. Also, they are used to exit from a loop.
public class BreakStatementSample{
    public static void main(String args[]){
    //the for loop suppose to iterate 10 times but when i=5, the loop breaks
    for(int i=0;i<10;i++){
     if(i==5){
       System.out.println("loop breaks here");
     break;
  }
   System.out.println(i);
  }
 }
}

Output:

0
1
2
3
4
loop breaks here
      • Continue Statement: It is used to skip the part of a loop. Unlike break statement it does not terminate the loop, instead it skips the remaining part of the loop and control again goes to check the condition again.Hence, the continue statement skips the current iteration and re-executes loop with a new condition.
class ContinueStatementDemo{
    public static void main(String args[]){
        for(int i=1; i<10; i++){
        if(i>4&&i<9){
        continue;
       }
    System.out.println(i);
      }
   }
}

Output:

1
2
3
4
9
1
    • return Statement: The Return keyword is used to explicitly return from a method when its execution is completed. That is, it causes a program control to transfer back to the caller of the method. If a method doesn’t return a value, the method must be declared void and it doesn’t need to contain a return statement. Else, if a method declares to return a value then it must use the return statement within the body of a method.
class ReturnDemo{
   public static void main(String args[]){ 
   boolean flag=true;
   System.out.println("Before the return");
     if(flag)
     return;
//compiler will bypass every statement after return
System.out.println("This won't execute");
}
}

Output:

Before the return

Octocat - CodedBug github

To find the working example, please refer to CodedBug GitHub repo