हिंदी

Define the concept of multi-way decision-making using the switch statement in Java.

Advertisements

प्रश्न

Define the concept of multi-way decision-making using the switch statement in Java.

कोड लेखन
परिभाषा
Advertisements

उत्तर

Multi-way decision-making using the switch statement in Java is a process that allows a program to select and execute one block of code from several alternatives based on the value of an expression. It is useful when a program needs to choose among multiple possible options.

Working of the switch Statement:

  1. The switch statement evaluates an expression and compares its value with different case labels.
  2. If a matching case is found, the statements associated with that case are executed.
  3. The break statement terminates the switch block and prevents the execution of subsequent cases.
  4. If no matching case is found, the default block is executed, if present.

Example Program:

class SwitchExample 
{
    public static void main(String[] args) 
    {
        int day = 2;
        switch (day) 
        {
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            case 3:
                System.out.println("Wednesday");
                break;
            default:
                System.out.println("Invalid Day");
        }
    }
}

Output:

Tuesday

 
shaalaa.com
  क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
अध्याय 7: Statements and their Scope - EXERCISE [पृष्ठ १६३]

APPEARS IN

धीरज मेहरोत्रा Computer Science [English] Class 12
अध्याय 7 Statements and their Scope
EXERCISE | Q 3. (i) | पृष्ठ १६३
Advertisements
Share
Notifications



      Forgot password?
Use app×