Switch statement is multiple selection statement in java. It is used to select one of several alternative paths in program execution. When a match is found, the statement sequence associated with that match is executed.
Note thatSwitch Statement can only be used to test for equality. Switch will work only with char, byte, short or int types. No two case constants in the same switch can have identical values.
Syntax of Switch Statement
switch(expression)
{
case constant1:
statement sequence
break;
case constant2:
statement sequence
break;
:
:
:
default:
statement sequence
break;
}
If matches found, the statements associated with that case are executed until break is encountered or in the case of default or the last case the end of the switch is reached.
default statement sequence is performed if no matches are found. It is optional. If all matches fail and default is absent, no actin takes place.
Example of Switch Statement
Example 1 : Program to print and count number of vowels and constants in entered word
class VowelConstantLoop
{
public static void main(String args[])
{
int ctrVowel = 0, ctrConst = 0;
char c;
for(int i = 0; i < args[0].length ; i++)
{
c = args[0].charAt(i);
switch(ch)
{
case 'a':
System.out.println("Vowel : " + ch);
ctrVowel++;
break;
case 'e':
System.out.println("Vowel : " + ch);
ctrVowel++;
break;
case 'i':
System.out.println("Vowel : " + ch);
ctrVowel++;
break;
case 'o':
System.out.println("Vowel : " + ch);
ctrVowel++;
break;
case 'u':
System.out.println("Vowel : " + ch);
ctrVowel++;
break;
default:
System.out.println("Constant : " + ch);
ctrConst++;
}
}
System.out.println("");
System.out.println("Number of vowels are " + ctrVowel + " and number of constants are " + ctrConst);
}
}
//Call from command line
java VowelConstantLoop java
Output
Constant : j
Vowel : a
Constant : v
Vowel : a
Number of vowels are 2 and number of constants are 2