Java


Java Tutorial


Admission Enquiry Form

  

Switch Statement With Integer

What is Switch statement in Java?

Switch statement is used to select one choice out of many in Java.

Syntax of Switch statement...

switch(expression)
{
case 1:
//statements
break;
case 2:
//statements
break;
default:
//statements
}




Example of switch statement with integer choice :

//Java program of Switch statement with character.
public class SwitchStatement {
public static void main(String[] args)
{
int choice;
System.out.println("Following are the choices of Ice Cream...");
System.out.println("1 for vanilla flavour");
System.out.println("2 for butterscotch flavour");
System.out.println("3 for chocolate flavour");
choice=2;
switch(choice)
{
case 1:
System.out.println("You have got vanilla flavour");
break;
case 2:
System.out.println("You have got butterscotch flavour");
break;
case 3:
System.out.println("You have got chocolate flavour");
break;
default:
System.out.println("Invalid...");
}//end of switch block
}//end of main method
}//end of class SwitchStatement


Output:

Following are the choices of Ice Cream...
1 for vanilla flavour
2 for butterscotch flavour
3 for chocolate flavour
You have got butterscotch flavour

In the above example, case 2: will get executed till break. When break will be encountered the control will get out of the Switch block.The default will only be excecuted if choice does not match any of three cases.