Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » FundamentalRSS Feeds

Switch Statement

Posted By: Taylor White     Category: Java     Views: 5169

This article explains about switch statement in java with examples.

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

 
  
Share: 

 
 

Didn't find what you were looking for? Find more on Switch Statement Or get search suggestion and latest updates.

Taylor White
Taylor White author of Switch Statement is from New York, United States.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!