English

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

Advertisements

Question

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

Code Writing
Definition
Advertisements

Solution

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
  Is there an error in this question or solution?
Chapter 7: Statements and their Scope - EXERCISE [Page 163]

APPEARS IN

Dheeraj Mehrotra Computer Science [English] Class 12
Chapter 7 Statements and their Scope
EXERCISE | Q 3. (i) | Page 163
Advertisements
Share
Notifications



      Forgot password?
Use app×