Decision Controls

Conditional Operator ( ? : )

Conditional operator is also known as the ternary operator. This operator, is applied on a Boolean expressions. Based on the evaluation of the boolean expression, one of the two possible choices will be assigned to a variable which is using this operator. The operator is written as:

variable x = (expression) ? value if true : value if false

Following is the example:

import java.util.Scanner; 

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

        Scanner sc = new Scanner(System.in);
        System.out.println(
                "Please enter a number and our little program will tell you if you entered an odd or even number");
        int a = sc.nextInt(); // this method will expect you to input an integer value on the console.
        String kind = (a % 2 == 0) ? "even" : "odd";

        System.out.println(a + " is an " + kind + " number");
    }
}

The if Statement:

When you write a logic, there will be instances when the execution of the program should take different paths based on certain conditions. In such cases you will need to use a control statement which makes a decision on which path to take. In Java you have two types of controls statements:

  • if, if-else statements
  • switch statements

An if statement consists of a Boolean expression followed by one or more statements. Syntax:

if (boolean_expression)
{
  //Statements will execute if the Boolean expression is true
}

If the Boolean expression evaluates to true then the block of code inside the if statement is executed. If not the first statement onwards after the end of the if statement (after the closing curly brace) will be executed. Example:

import java.util.Scanner;
public class Test {

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please input a number");

        int x = sc.nextInt();

        if (x % 2 == 0) {
            System.out.println("You have input an even number");
        }

        System.out.println("Good bye!");
    }
}

Run the above code twice; first time with an even number input from console and second time with an odd number input and study how the program of execution selects statements based on the result of the boolean expression inside the if statement.

The following flowchart depicts the control flow of the program based on the result of the boolean expression

x % 2 == 0

image alt text

The if...else Statement:

An if statement can be followed by an optional else statement, which executes when the boolean expression is false.

The syntax of an if...else is:

if (boolean_expression) {
  //Executes when the Boolean expression is true
} else {
  //Executes when the Boolean expression is false
}

Example:

import java.util.Scanner;
public class Test {

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please input a number");

        int x = sc.nextInt();

        if (x % 2 == 0) {
            System.out.println("You have input an even number");
        } else {
            System.out.println("You have input an odd number");
        }

        System.out.println("Good bye!");
    }
}

Run the above code and input an even and odd number and study how the if or else block gets executed based on boolean expression evaluation. The same execution can be visualized with the flow chart below.

image alt text

The if...else if...else Statement:

An if - else statement can be followed by an optional else if...else statement. When using if , else if , else statements there are few points to keep in mind. An if can have zero or one else and it must come after any else if's. An if can have zero to many else if's and they must come before the else. Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax: The syntax of an if...else is:

if (boolean_expression 1) {
  //Executes when the Boolean expression 1 is true
} else if (boolean_expression 2){
  //Executes when the Boolean expression 2 is true
} else if (boolean_expression 3){
  //Executes when the Boolean expression 3 is true
} else {
  //Executes when the none of the above condition is true.
}

1. Example:

import java.util.Scanner;
public class Test {

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please input your score");

        int score = sc.nextInt();

        if (score > 90) {
            System.out.println("Congratulations! You scored an 'A' grade");
        } else if (score > 80) {
            System.out.println("Congratulations! You scored a 'B' grade");
        } else if (score > 70) {
            System.out.println("Congratulations! You scored a 'C' grade");
        } else {
            System.out.println("Sorry, you failed.");
        }
    }
}

Run the above program by giving values ranging from 100 to 20 for the score and study the logic flow by understanding which if else block is executed for each value.

Critical Thinking

Remove the else block in the above code and what the results when the input is 92, 82, 50?

How do you fix the code without adding the else block? Hint: How about adding additional relational operators in the if block?

Another example:


import java.util.Scanner;

public class MultipleIfElse {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("please input your age");
        short age = sc.nextShort();

        if (age == 13) {
            System.out.println("Hey you are the youngest teenager I know!");
        } else if (age == 14) {
            System.out.println("Hey, this is the age of pimples and spots. Hope you are managing it well.");
        } else if (age == 15) {
            System.out.println("Hey, you are now surfing the teen years!");
        } else if (age == 16) {
            System.out.println("Hey, you are in sweet sixteen!");
        } else if (age == 17) {
            System.out.println("Hey, one more year to vote..");
        } else if (age == 18) {
            System.out.println("Hey, You can vote now!!");
        } else if (age == 19) {
            System.out.println("Hey, you are the oldest teen I know!");
        } else {
            System.out.println("Glad to know you are " + age + " years old!");
        }
        sc.close();

    }
}

Study the above example.

Do you really need the else block for all the if blocks?

Not really, it is sufficient to keep the last else block and the rest can be removed. Here is the modified version with only the last else block and both the code work with the same functionality.


import java.util.Scanner;

public class MultipleIfElse {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("please input your age");
        short age = sc.nextShort();

        if (age == 13) {
            System.out.println("Hey you are the youngest teenager I know!");
        }
        if (age == 14) {
            System.out.println("Hey, this is the age of pimples and spots. Hope you are managing it well.");
        }
        if (age == 15) {
            System.out.println("Hey, you are now surfing the teen years!");
        }
        if (age == 16) {
            System.out.println("Hey, you are in sweet sixteen!");
        }
        if (age == 17) {
            System.out.println("Hey, one more year to vote..");
        }
        if (age == 18) {
            System.out.println("Hey, You can vote now!!");
        }
        if (age == 19) {
            System.out.println("Hey, you are the oldest teen I know!");
        } else {
            System.out.println("Glad to know you are " + age + " years old!");
        }
        sc.close();

    }
}

Point to note: Be thoughtful when you use the else if statement. Many a times the else if statement can be replaced with just another if statement. Using just the if statement reduces the clutter in your code so it is advisable to use just that. Also the above example is also good candidate to use switch statement instead of the if statement. You will learn more on switch statement below.

Nested if...else Statement:

It is legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement.

The syntax for a nested if...else is as follows:

if (boolean_expression 1) { //Executes when the Boolean expression 1 is true if(boolean_expression 2) { //Executes when the Boolean expression 2 is true } }

public class NestedIfExample {

   public static void main(String args[]) {
      int x = 30;
      int y = 10;

      if (x == 30) {
         if (y == 10) {
             System.out.print("X = 30 and Y = 10");
          }
       }
    }
}

The switch Statement:

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case. Although it jumps to the specific case based on the value, after executing a specific case, it will move on to the next case if there is no break keyword used to come out of the case switch block. Syntax:

switch(expression) {
  case value :
    //Statements
    break; //optional
  case value :
    //Statements
    break; //optional
//You can have any number of case statements.v   default : //Optional
    //Statements
}


import java.util.Scanner;

public class Test {

    public static void main(String args[]) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Please input your letter grade");

        String grade = sc.nextLine().toUpperCase();

        switch (grade) {
        case "A":
            System.out.println("Excellent!");
            break;
        case "B":
        case "C":
            System.out.println("Well done");
            break;
        case "D":
            System.out.println("You passed");
            break;
        case "F":
            System.out.println("Better try again");
            break;
        default:
            System.out.println("Invalid grade");
        }
        System.out.println("Your grade is " + grade);
        sc.close();
    }
}

Run the above program, by inputting your grade for any subject and see what the message would be. Study the code to understand which path the program took for execution.

In the above program what happens if toUpperCase() is not added to sc.nextLine()?

If toUpperCase is not added then if the input is in lower case, it jumps to the default case If toUpperCase() is not added, it still works as expected

How does the program execution flow when you key in 'b'?

It jumps to case "B" and then flows to case "C" and prints out "Well done" It jumps to case "B" and since there is no other statement, nothing happens The program of execution jumps to case "B" and since there is no break, it also executes case "C" and prints out "Well done" and after that it encounters break which makes it to come out of the switch case block

Which one to use? if or switch?

Many an if else construct can be replaced with a switch statement. A switch statement is cleaner and easier to understand than a chained if else block. If a switch statement meets your need then use the switch statement instead of multiple if else blocks. The above if else example can be replaced with an equivalent functionality switch statement


import java.util.Scanner;

public class MultipleIfElse {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("please input your age");
        short age = sc.nextShort();

        switch (age) {
        case 13: {
            System.out.println("Hey, you are the youngest teenager I know!");
            break;
        }
        case 14: {
            System.out.println("Hey, this is the age of pimples and spots. Hope you are managing it well.");
            break;
        }
        case 15: {
            System.out.println("Hey, you are now surfing the teen years!");
            break;
        }
        case 16: {
            System.out.println("Hey, you are in sweet sixteen!");
            break;
        }
        case 17: {
            System.out.println("Hey, one more year to vote..");
            break;
        }
        case 18: {
            System.out.println("Hey, You can vote now!!");
            break;
        }
        case 19: {
            System.out.println("Hey, you are the oldest teen I know!");
            break;
        }
        default: {
            System.out.println("Glad to know you are " + age + " years old!");
        }
        }
        sc.close();

    }
}

The following rules apply to a switch statement:

  • The variable used in a switch statement could be a byte, short, int, char, enums or Strings.
  • You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon (:).
  • The value for a case must be the same data type as the variable in the switch.
  • When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
  • When a break statement is reached, the switch terminates, and the program of execution jumps to the next line following the switch statement.
  • Not every case needs to contain a break. If no break appears, the program of execution will fall through to subsequent cases until a break is reached.
  • A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

results matching ""

    No results matching ""