Switch:
- A conditional control statement used to execute a block based on value of expression.
- Expression can be byte, short, char and int primitive types.
- It can work with Strings and Wrapper objects also.
Syntax:
switch(expression)
{
case value1 :
statements;
break;
case value2 :
Statements;
break;
default :
Statements
}
Code program:
import java.util.Scanner ;
class SwitchStatement
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a character : ");
char ch = sc.nextLine().charAt(0);
switch(ch)
{
case 'r' : System.out.println("Red");
break;
case 'g' : System.out.println("Green");
break;
case 'b' : System.out.println("Blue");
break;
default : System.out.println("Weird color");
break;
}
}
}
Code Program:
class SwitchStatement
{
public static void main(String[] args)
{
int x=1 ;
switch(x)
{
case 0 : x++ ;
case 1 : x+=3 ;
case 2 : x=2 ;
default : --x ;
}
System.out.println("X value : "+x);
}
}
Menu Driven Program:
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int ch, a=0, b=0;
while(true)
{
System.out.println("Arithmetic operations : ");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Exit");
System.out.print("Enter your choice : ");
ch = scan.nextInt();
if(ch>=1 && ch<=3)
{
System.out.println("Enter 2 numbers : ");
a = scan.nextInt();
b = scan.nextInt();
}
switch(ch)
{
case 1 : Calc.add(a, b);
break;
case 2 : Calc.subtract(a, b);
break;
case 3 : Calc.multiply(a,b);
break;
case 4 : System.exit(0);
default: System.out.println("Invalid choice");
}
}
}
}
class Calc
{
static void add(int a, int b){
System.out.println("Add result : " + (a+b));
}
static void subtract(int a, int b){
System.out.println("Subtract result : " + (a-b));
}
static void multiply(int a, int b){
System.out.println("Multiply result : " + (a*b));
}
}