SWITCH CASE in JAVA

switchcase
Switch case in Java

Switch case:
A switch statement evaluates a single variable and depending on its value, executes a certain block of code.the general syntax is represented as follows:

switch(variable)
{
case 1: statement;
break;
case 2:statement;
break;
case 3: statement;
break;
-
-
-
default : statement;
} 

The variable that’s evaluated can be a primitive byte, short, char, or int, as well as enumerated types and String.the, switch check the value of the variable for a match in one of the cases. If they are equal, the statements, in that case, will be executed. A switch case organized into case, it makes sense to use it when you have a finite number of expected values. The switch statement is a multi-way decision that tests whether an expression matches one of a number of constant integer values,and branches accordingly.

1.Example for switch case

public class SwitchExample 
{ 
public static void main(String[] args)
 { 
//Declaring a variable for switch expression 
int number=20; 
//Switch expression 
switch(number)
{ 
//Case statements 
case 10: System.out.println("10"); 
break;
 case 20: System.out.println("20");
 break;
 case 30: System.out.println("30");
 break;
 //Default case statement 
default:System.out.println("Not in 10, 20 or 30"); 
} 
}
} 
OUTPUT:
20

2.Display calculator program using switch case

import java.util.*;
import java.util.Scanner;

public class JavaExample {

    public static void main(String[] args) {

    	double num1, num2;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter first number:");

        /* We are using data type double so that user
         * can enter integer as well as floating point
         * value
         */
        num1 = scanner.nextDouble();
        System.out.print("Enter second number:");
        num2 = scanner.nextDouble();

        System.out.print("Enter an operator (+, -, *, /): ");
        char operator = scanner.next().charAt(0);

        scanner.close();
        double output;

        switch(operator)
        {
            case '+':
            	output = num1 + num2;
                break;

            case '-':
            	output = num1 - num2;
                break;

            case '*':
            	output = num1 * num2;
                break;

            case '/':
            	output = num1 / num2;
                break;

            /* If user enters any other operator or char apart from
             * +, -, * and /, then display an error message to user
             * 
             */
            default:
                System.out.printf("You have entered wrong operator");
                return;
        }

        System.out.println(num1+" "+operator+" "+num2+": "+output);
    }
}
Output:
Enter first number:40
Enter second number:4
Enter an operator (+, -, *, /): /
40.0 / 4.0: 10.0
Translate »