Sunday, 22 January 2017

SWITCH STATEMENT IN JAVA

If several options are available then it isn't recommended to take nested if-else. We should go for switch statement so that readability of the code will be improved. 'switch' is a keyword, by which we can create a selection statement with multiple choices. Multiple choices can be constructed by using 'case' keyword. Syntax -
switch(expression)
{
case expr1 :
statements;
break;
case expr2 :
statements;
break;
---------
---------
case exprn:
statements;
break;
default :
statements;
}

In the above syntax, switch, case, break are keywords. expr1, expr2 are known as 'case labels'. Statements inside case expression need not to be closed in braces. break statement causes an exit from switch statement.

The valid argument types for the switch statements are -
1.4 version - byte, short, char, int
1.5 version - byte, short, char, int, Byte, Short, Character, Integer
1.7 version - byte, short, char, int, Byte, Short, Character, Integer, String


The following rules apply to a switch statement :

  • We 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 constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.
  • 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 flow of control jumps to the next line following the switch statement.
  • Not every case needs to contain a break. If no break appears, the flow of control 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.

Example
import java.util.Scanner;
public class Switch1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the day of the week[1-7]");
int day = scan.nextInt();
switch(day)
{
case 1:
System.out.println("Monday");
break;
case 2 :
System.out.println("Tuesday");
break;
case 3 :
System.out.println("Wednesday");
break;
case 4 :
System.out.println("Thursday");
break;
case 5 :
System.out.println("Friday");
break;
case 6 :
System.out.println("Saturday");
break;
case 7 :
System.out.println("Sunday");
break;
default :
System.out.println("OOPS sorry day not found");
}
}
}

Output -
Enter the day of the week[1-7]
3
Wednesday
Enter the day of the week[1-7]
0
OOPS sorry day not found

No comments:

Post a Comment