Java 05: Selection

Selection statement is used to do some action only under certain condition. Condition like only write text to a text file only if the text file that you are trying to write does not exist. Selection statement are used for decision making like for robotic, if there is obstacle on path go to clearer path and so on.

Like most programming language the keyword if is used in Java to begin writing the selection statement. Thus, selection statement is fondly known as if statement.

if(condition){
    // statement to do when condition is true
}

Following diagram show the flow of if statement.

In the syntax above, the condition is a Boolean expression. A Boolean expression is an expression that produce TRUE or FALSE result. This expression consists of comparison operator that compare two values such as shown in the table below:

OperatorDescription
> More than
< Less than
>=More than or equal to
<=Less than or equal to
==Equal to
!=Not equal to

Let's see some examples to understand the if statement and how it works.

Example 1

public static void main(String[] args){

    int height = 167;
           
    if(height > 160){
        System.out.println("You are qualified for army");
    }
}

This if statement only display "You are qualified for army" if the height is more than 160. According to this source code, value of variable height is 167. and this evaluates to true. if the value of the height not more than 160, this condition will evaluate to false and so this message will not be displayed.

If we write program like this, the program does not know what to do if the condition is false. One of the side effect is the user might not know if there is something going wrong. With first version of our coding we don't have action for following situation.

Example 2

public static void main(String[] args){

int height = 156;
       
    if(height > 160){
        System.out.println("You are qualified for army");
    }
           
    if(height <= 160){
        System.out.println("Not qualified for army");
    }

}

the second if statement in example 2 prints the message if the height is less than 160.

if...else statement

In most programming language there is another keyword called else for dealing with this kind of situation, so we can write combination of the first and second if statement like this.

Example 3

public static void main(String[] args){

    int height = 167;
           
    if(height > 160){
        System.out.println("You are qualified for army");
    }else{
        System.out.println("Not qualified for army");
    }

}

Now we have second syntax for the selection statement also known as if else statement

if(condition) {
    // statement to do when condition is true
}else{
    // statement to do when condition is false

}

following shows flow of the if and else statement.

Nested if statement

Sometimes we need to compare more than condition to check the most appropriate action to take. One of the solution is nested if statement. Nested means we place a block of code inside of another block. Thus we have inner block and outer block.

It is said that the inner block is nested inside of outer block. Nested if statement means we write a if statement inside of another if statement.

Example 4

public static void main(String[] args){
    int height = 167;
           
    if (height > 160) {
        if (age > 21) {
            System.out.println("You are qualified for army");
        }
    }

}

This statement means that if the value of height is more than 160 and age is more that 21 than display the message "You are qualified for army".

Another way to write this is using logical operator &&. Logical operators are used to write more complex Boolean expression.

if(height > 160 && age > 21){
    System.out.println("You are qualified for army");
}

We can also nest another if statement inside else portion of if else statement.

Example 5

public static void main(String[] args){
    int height = 167;

    if(height > 160){
        System.out.println("You are qualified for army");
    }else{
        if(age > 21){
            System.out.println("Please come for further evaluation");
        }else{
            System.out.println("Not qualified for army");
        }
    }
}

if...else if statement

In our programming language there is another more neat way of writing this program.

Example 6

public static void main(String[] args){
    int height = 156;
    int age = 23;
           
    if(height > 160{
        System.out.println("You are qualified for army");
    }else if(age > 21){
        System.out.println("Please come for further evaluation");
    }else{
        System.out.println("Not qualified for army");
    }

}

Syntax

if(condition1) {
// statement to do when condition 1 is true
}else if (condition2){
      // statement to do when condition 2 is true
}
…
}else if (conditionN){
      // statement to do when condition N is true
}else{
// statement to do when all conditions are false

}

Switch statement

Now time for switching

The syntax

switch(variable_to_check){
    case value1:    statement(s) value1;
                    break;
    case value2:    statement(s value2;
                    break;
          ...
    case valueN:    statement(s)  valueN;
                    break;

    default:        default statement(s)  
}
Example 7
int direction = 0;

switch(direction){
    case 1: printMessage("Go straight");
            break;
    case 2: printMessage("Go back");
            break;
    case 3: printMessage("Go left");
            break;
    case 4: printMessage("Go right");
            break;
    default:displayError("Unknown direction entered");
}

if the value of direction is 1 than the output is :

Go straight

The statement start with switch keyword. Next the name of variable that we wanted to check before deciding what action to take. All the possible values and actions are written inside the curly bracket. the keyword that is used for specify possible values are is case. After this keyword, a value is written.

The statement continues with a colon that separate the possible value and the action that you want your program to perform.The action could me a arithmetic expression, assignment expression, input or output statement, you may have if statement and in this example we a calling a method to display message that we give.

The last keyword is break which terminates the switch statement and continue with other statements that follows. This keyword is very important because, if we did not write the following lines will be executed until it find another break statement elsewhere or until the last curly bracket.

Example 8

public static void main(String[] args){
    int direction = 1;

    switch(direction){
        case 1: printMessage("Go straight");
        case 2: printMessage("Go back");
        case 3: printMessage("Go left");
        case 4: printMessage("Go right");
        default:displayError("Unknown direction entered");
    }

}

If the value of direction is 1 this will produce following output:

Go straight
Go back
Go left
Go right
Unknown direction entered

Once again it is up to us to decide how our program behave. Writing break keyword is optional, that means this situation can be use to our advantage when designing our program.

Example 9
switch(input){
    case 'A': printMessage("a");                
    case 'a': printMessage("a");
              break;
    case 'B': printMessage("b");
    case 'b': printMessage("b");
              break;
    default: displayError("Unknown input");
}

writing switch case like this is one way to make our program case insensitive (that means program accepts lower and upper case of particular alphabet).

output if input value is 'A'

A
a

output if input value is 'a'

a

Conditional expression

Conditional expression is used when we need to assign value to a variable, restricted by condition. This is alternative for if…else statement. Following is syntax for conditional expression.

variable = boolean-expression? expression1: expression2;

This statement returns expression1 if the boolean-expression is true and returns expression2 if the boolean-expression is false.

Example 10

public static void main(String[] args){
    int max, num1, num2;
    max = 0;
    num1 = 4;
    num2 = 8;
           
    max = (num1 > num2)? num1: num2;
           
    System.out.println("Num1 : " + num1);
    System.out.println("Num2 : " + num2);
    System.out.println("Max value : " + max);
}

the condition num1 > num2 is checked first. Since num1 is 4 and num2 is 8, the expression 4 > 8 is false. This cause this statement to return the value of num2 which is 8 and assigned to variable max. So, value of max is 8 as expected.

Following is output for the Example 10

Num1 : 4
Num2 : 8
Max value : 8

A post by Cuber

Comments

Popular posts from this blog

Drawing Simple Pie Chart

VB.net connecting to SQL Server

VB.net