SELECTION STATEMENTS

 
A selection statement is a control statement that allows choosing between two or more execution paths in a program. The selection statements are
If statement
If-else
Switch or case statement
 
a) If Statement:
This is a control statement to execute a single statement or a block of code, when the given condition is true and if it is false then it skips if block and rest code of program is executed .
 
Syntax:
if (boolean-expression ){
then-clause }
 
Example:
1
2
3
4
if ( grade >= 90 )
{
    System.out.println( “You are an excellent student!” );
}

Here it evaluates grade is greater or equal to 90 so if block is execute. Hence”You are an excellent student!" is printed on the screen.

b) If-else Statement:
The "if-else"statement is an extension of if statement that provides another option when 'if'   statement evaluates to "false" i.e. else block is executed if "if" statement is false.

 Syntax:

1
2
3
4
5
6
if(boolean-expression)
{
    then-clause
}
else {
      else-clause}

Example:

1
2
3
4
5
6
7
8
9
int dayOfTheWeek=4;
if ( dayOfTheWeek > 5 )
{
    System.out.println( “Weekend.”);
}
else
{
    System.out.println( “Workday.”);
}

If dayOfTheWeek doesn't greater than evaluate to 5 then else block is executed. Here dayOfTheWeek less than 5 then it execute else block. So ”Workday" is printed on the screen.

c) Switch Statement:
Sometimes it becomes cumbersome to write lengthy programs using if and if-else statements. To avoid this we can use Switch statements in Java. The expression must be of type int,short,byte or char. The selection in the switch statement is determined by the values between the parenthesis after the keyword switch and the expression.

Syntax:

1
2
3
4
5
6
switch(control_expression){
    case expression 1:<statement>;
    case expression 2:<statement>;
    case expression n:<statement>;
    default:<statement>;
}

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
switch ( C )
 {
      case ‘A’ : System.out.println( “Excellent student”);
              break;
      case ‘B’ : System.out.println( “Good student”)
              break;
      case ‘C’ : System.out.println( “Average student”);
              break;
      case ‘D’ : System.out.println( “Bad student”);
              break;
      default : System.out.println(“Failed student”);
              break;
  }