Develop programs to demonstrate use of- a) Switch - Case statement b) Conditional if (? :) in Java

Demonstrating Switch-Case and Conditional Operator:

public class SwitchAndConditionalDemo {

    public static void main(String[] args) {

        int choice = 2;

        // Example 1: Switch-Case statement

        switch (choice) {

            case 1:

                System.out.println("You chose option 1");

                break;

            case 2:

                System.out.println("You chose option 2");

                break;

            case 3:

                System.out.println("You chose option 3");

                break;

            default:

                System.out.println("Invalid choice");

        }


        // Example 2: Conditional (Ternary) Operator

        String result = (choice == 2) ? "Option 2 selected" : "Option 2 not selected";

        System.out.println(result);

    }

}


Output:

You chose option 2
Option 2 selected

Comments