how to use a switch statement in java

www.‮tual‬turi.com
how to use a switch statement in java

A switch statement in Java allows you to choose between multiple alternatives based on the value of an expression. Here's the basic syntax of a switch statement:

switch (expression) {
    case value1:
        // Code to execute if expression == value1
        break;
    case value2:
        // Code to execute if expression == value2
        break;
    ...
    default:
        // Code to execute if expression does not match any of the values
}

Here's an example of how you can use a switch statement in Java:

int number = 5;
switch (number) {
    case 1:
        System.out.println("Number is 1");
        break;
    case 2:
        System.out.println("Number is 2");
        break;
    case 3:
        System.out.println("Number is 3");
        break;
    default:
        System.out.println("Number is not 1, 2, or 3");
}

In this example, the switch statement will check the value of the number variable and execute the appropriate code based on its value. If number is 1, it will print "Number is 1". If number is 2, it will print "Number is 2". If number is 3, it will print "Number is 3". If number is any other value, it will print "Number is not 1, 2, or 3".

Note that the break statements are used to exit the switch statement after executing the appropriate code. If you omit the break statements, the code for all the following cases will be executed, regardless of the value of the expression.

You can use the switch statement to compare values of any type that can be used in a switch expression, including int, char, and String. However, you cannot use floating-point values or objects in a switch expression.

Here's an example of how you can use a switch statement with a String expression:

String input = "hello";
switch (input) {
    case "hello":
        System.out.println("Input is hello");
        break;
    case "world":
        System.out.println("Input is world");
        break;
    default:
        System.out.println("Other Input");
        break;
}
Created Time:2017-11-01 22:29:46  Author:lautturi