Switch Statement in java

Switch Statement in java

switch statements is used, when there is multiple alternatives but only one needs to be selected. However, the complexity of such programs increases dramatically, when the number of alternatives increases, then the programs becomes difficult to read and follow. C built a multi-way decision statement known as “switch statement” . It is like if else-if ladder statement.

syantx:

switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}

rules for switch statement:

  • the switch expression must be a character type or integer type
  • the case value must be inter or charcter
  • the case value can be used only inside switch function
  • The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.
  • break is not mandatory for default statement

flowchart:

Switch Statement Flow Chart in java

example:

import java.util.*;
public class Switchcase
{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("enter number 1");
float a=s.nextInt();
System.out.println("enter number 2");
float b=s.nextInt();
System.out.println("\n\n 1. ADDITION\n\n 2. SUBTRACTION\n\n 3. MULTIPLICATION\n\n4. DIVISION ");
System.out.println("\n\n Enter your option: ");
int num=s.nextInt();
//Switch expression
switch(num)
{
//Verify Case and print statement
case 1:
System.out.println(a+"+"+b+"="+(a+b));
break;
case 2:
System.out.print(a+"-"+b+"="+(a-b));
break;
case 3:
System.out.print(a+"*"+b+"="+(a*b));
break;
case 4:
System.out.print(a+"/"+b+"="+(a/b));
break;
//and so on till case 7
//Here is Default case statement
default:System.out.println("Wrong Choice");
}
s.close();
}
}

output:

enter number 1
50
enter number 2
25
1. ADDITION
2. SUBTRACTION
3. MULTIPLICATION
4. DIVISION
Enter your option:
3
50.0*25.0=1250.0
Last updated on by vishal devxo