The Switch Statement
The switch statement is used to pickup or execute a particular group of statements from several available group of statements. It allows us to make a decision from the number of choices.
It is a multi way decision statement, it tests the value of given variable or expression against a list of case values and when a match is found, a block of statements associate with that case is executed.
Syntax:
switch(expression)
{
case 1: statements;
break;
case 2: statements;
break;
case 3: statements;
break;
case n: statements;
break;
default : statements;
break;
}
The integer expression following the key word switch is any ‘C’ expression that must yield an integer value. It must be an integer constant like 1,2,3 or an expression that evaluates to an integer.
The keyword case is followed by an integer or a character constant. Each constant in each case must be different from all the other.
First the integer expressions following the keyword switch is evaluated. The value it gives is we arched against the constant value that follow the case statements. When a match is found, the program executed the statements following the case. If no math is found with any of the case statements, then the statements following the default are executed Rules for writing switch() Statement.
The expression in switch statement must be an integer value or a character constant.
No real numbers are used in expression.
Each case block and default blocks must end with break statements
The default is optional
The case keyword must terminate with colon (:)
No two case constants are identical
Example : For printing Months of a year using switch case statement
public class switchcase
{
public static void main(String args[])
{
int n=6;
switch(n)
{
case 1: System.out.println(“January");
break;
case 2: System.out.println(“Febuary");
break;
case 3: System.out.println(“March");
break;
case 4: System.out.println(“April");
break;
case 5: System.out.println(“May");
break;
case 6: System.out.println(“June");
break;
case 7: System.out.println(“July");
break;
case 8: System.out.println(“August");
break;
case 9: System.out.println(“September");
break;
case 10: System.out.println(“October");
break;
case 11: System.out.println(“November");
break;
case 12: System.out.println(“December");
break;
default: System.out.println(“N Value should be 1-12")
break;
}
}
}
Output will be
Enter the Number of N: 6
June
No comments:
Post a Comment