The switch statement is Java's multi-way branch statement. It is used to take the place of long if-else chains, and make them more readable. However, unlike if statements, one may not use inequalities; each value must be concretely defined.
There are three critical components to the switch statement:
Syntax:
switch ( expression )
{
case 1 :
// Block of Statement
break;
case 2 :
// Block of Statement
break;
case 3 :
// Block of Statement
break;
case 4 :
// Block of Statement
break;
.
.
default :
// Block of Statement
break;
}
This is a Java program that demonstrates the use of the switch statement. The program prompts the user to choose an operation to perform (addition, subtraction, multiplication, or division), and then prompts the user to enter two numbers. The program then performs the selected operation on the two numbers and prints the result. Here's how the program works:
import java.util.Scanner; //Switch Case Statement in Java public class switch_demo { public static void main(String args[]) { int a,b,c,ch; System.out.println("1.Addition"); System.out.println("2.Subtraction"); System.out.println("3.Multiplication"); System.out.println("4.Division"); System.out.println("Enter Your Choice : "); Scanner in =new Scanner(System.in); ch=in.nextInt(); System.out.println("Enter 2 Nos : "); a=in.nextInt(); b=in.nextInt(); switch (ch) { case 1: c=a+b; System.out.println("Addition : " +c); break; case 2: c=a-b; System.out.println("Subtraction : "+c); break; case 3: c=a*b; System.out.println("Multiplication : "+c); break; case 4: c=a/b; System.out.println("Division : "+c); break; default: System.out.println("Invalid Selection"); break; } } }
1.Addition 2.Subtraction 3.Multiplication 4.Division Enter Your Choice : 3 Enter 2 Nos : 12 8 Multiplication : 96To download raw file Click Here
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions