switch statement

In Java, a switch statement is used for decision-making based on the value of an expression. It allows you to test the value of a variable or expression against multiple possible constant values. Here’s the basic syntax of a switch statement:

switch (expression) {
    case value1:
        // code to be executed if expression matches value1
        break;
    case value2:
        // code to be executed if expression matches value2
        break;
    // more cases as needed
    default:
        // code to be executed if none of the cases match
}Code language: JavaScript (javascript)

Here’s a simple example using a switch statement to determine the day of the week based on a numeric code:

public class SwitchExample {
    public static void main(String[] args) {
        int dayOfWeek = 3;
        switch (dayOfWeek) {
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            case 3:
                System.out.println("Wednesday");
                break;
            case 4:
                System.out.println("Thursday");
                break;
            case 5:
                System.out.println("Friday");
                break;
            case 6:
                System.out.println("Saturday");
                break;
            case 7:
                System.out.println("Sunday");
                break;
            default:
                System.out.println("Invalid day of the week");
        }
    }
}

Here’s another simple example using a switch statement to determine the Telugu Season  based on a numeric code

import java.util.Scanner;
public class TeluguSeasons {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a month (1-12): ");
        int month = scanner.nextInt();
        String season;
        switch (month) {
            case 1:
            case 2:
                season = "Hemanta (Late Autumn/Winter)";
                break;
            case 3:
            case 4:
                season = "Shishira (Pre-Spring)";
                break;
            case 5:
            case 6:
                season = "Vasanta (Spring)";
                break;
            case 7:
            case 8:
                season = "Grishma (Summer)";
                break;
            case 9:
            case 10:
                season = "Varsha (Rainy)";
                break;
            case 11:
            case 12:
                season = "Sharad (Autumn)";
                break;
            default:
                season = "Invalid month";
                break;
        }
        System.out.println("The Telugu season for month " + month + " is " + season);
       scanner.close();
    }
}
Scroll to Top