Switch Case Statement in java जावा में स्विच केस स्टेटमेंट

The switch statement in Java allows the value of an expression or variable to be compared with multiple constant values. It is a control structure that works only with integer, character, enum, or string types. Each case in a switch is associated with a constant value followed by a colon (:), and if the expression matches a case value, the corresponding block is executed. To prevent the fall-through behavior, the break; statement is used at the end of each case. A special default case (which is optional) runs when no other cases match.

The switch statement is often used as a cleaner alternative to nested if...else statements.

Java में switch स्टेटमेंट का प्रयोग एक वैरिएबल या एक्सप्रेशन की वैल्यू को कई अलग-अलग स्थायी (constant) वैल्यूज से तुलना करने के लिए किया जाता है। यह कंट्रोल स्ट्रक्चर केवल इन्टिजर, कैरेक्टर, एनम, या स्ट्रिंग एक्सप्रेशन पर कार्य करता है। प्रत्येक case के साथ एक निश्चित वैल्यू और : का उपयोग होता है। यदि कोई केस वैल्यू एक्सप्रेशन से मेल खाती है, तो उससे संबंधित कोड रन होता है। हर केस के बाद break; का उपयोग आवश्यक होता है जिससे अगले केस को रोका जा सके। यदि कोई केस मेल नहीं खाता है तो default केस (यदि मौजूद हो) रन होता है।

switch स्टेटमेंट का प्रयोग अक्सर नेस्टेड if...else के स्थान पर किया जाता है ताकि कोड ज्यादा क्लीन और पठनीय हो।


💻 Java Program Example using switch

public class SwitchExample {
    public static void main(String[] args) {
        int day = 3;

        switch (day) {
            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");
        }
    }
}

✅ Output:

Wednesday

📝 Explanation:

In this program, the value of the day variable is 3, so the switch statement matches it with case 3, which prints "Wednesday". The break; ensures no other cases are executed after a match.

Comments

Popular posts from this blog

What is a Web Browser? वेब ब्राउज़र क्या है?

Java's Support System जावा का सहयोगी तंत्र

The Internet and Java इंटरनेट और जावा का सम्बन्ध