Java switch

Switch Case in Java

In Java, the switch statement is a control statement that allows you to select one of many code blocks to be executed. It is often used when you have a single expression (variable or value) that you want to compare against multiple possible values and execute different blocks of code based on which value matches the expression.

Basic Structure :

switch (expression) {
    case value1:
        // code to be executed;
break;
    case value2:
        // code to be executed;
break;
        // more cases…
    default:
        // code to be executed if all cases are not matched;
        break;
}

Scenario: Write a Java program to simulate a pricing system using a switch statement. The program should take the name of the car as Mustang, Ford, or any other car and output the corresponding price. If the value doesn’t match any of the available car names, it should output “Invalid car name”.
Scenario 1: When car = “Ford”

public class Program {
    public static void main(String[] args) {
        String car = “Ford”;
        switch (car) {
            case “Mustang”:
                System.out.println(“Price is 1cr”);
                break;
            case “Ford”:
                System.out.println(“Price is 50Lakhs”);
                break;
            default:
                System.out.println(“Invalid car”);
                break;
        }
    }
}

Output: Price is 50Lakhs

Code Explanation

public class Program {

This defines a public class named Program. A class is a blueprint for creating objects, and public means that this class can be accessed from outside its containing package.

public static void main(String[] args) {

This is the entry point of your Java program. The main method is where execution begins. It takes an array of strings (args) as its parameter, which allows you to pass command-line arguments to your program.

String car = “Ford”;

This line declares a String variable named car and initializes it with the value “Ford”.

switch (car) {

This is a switch statement that performs different actions based on the value of the car variable. Each case represents a possible value for car, and the code within that case is executed if car matches the case.

case “Mustang”

The case value is “Mustang”. Since the car variable value is “Ford” (not “Mustang”), this case block of code is skipped, and the switch statement checks the next case.

case “Ford”

The case value is “Ford”. Since the car variable value is “Ford”, this case block of code is executed. It prints “Price is 50Lakhs” to the console and then exits the switch statement because of the break keyword.

default

The default block is executed if none of the case values match the car variable. In this case, it is not executed because the car value matched one of the cases.

System.out.println(“Price is 50Lakhs”);

This line prints “Price is 50Lakhs” to the console, which is the output you will see.
Scenario2 : When car = Mustang

public class Program {
    public static void main(String[] args) {
        String car = “Mustang”;
        switch (car) {
            case “Mustang”:
                System.out.println(“Price is 1cr”);
                break;
            case “Ford”:
                System.out.println(“Price is 50Lakhs”);
                break;
            default:
                System.out.println(“Invalid car”);
                break;
        }
    }
}

Output:
Price is 1cr

Code Explanation

public class Program {

This defines a public class named Program. A class in Java is a blueprint for creating objects, and public means that this class can be accessed from outside its containing package.

public static void main(String[] args) {

This is the entry point of your Java program. The main method is where execution begins. It takes an array of strings (args) as its parameter, which allows you to pass command-line arguments to your program.

String car = “Mustang”;

This line declares a String variable named car and initializes it with the value “Mustang”.

switch (car) {

This is a switch statement that performs different actions based on the value of the car variable. Each case represents a possible value for car, and the code within that case is executed if car matches the case.

case “Mustang”:
System.out.println(“Price is 1cr”);
break;

The case value is “Mustang”, and since the car variable value is “Mustang”, this block of code is executed. It prints “Price is 1cr” to the console and then exits the switch statement because of the break keyword. This means that the subsequent cases will not be executed.

case “Ford”:
System.out.println(“Price is 50Lakhs”);
break;

This case block is not executed because the car value matched the previous case (Mustang), and the switch statement has already exited.

default:
System.out.println(“Invalid car”);
break;

The default block is executed if none of the case values match the car variable. In this scenario, it is not executed because the car value matched the first case.

 

Output:
Price is 1cr

Scenario3 : When car = Ferrari

public class Program {
    public static void main(String[] args) {
        String car = “Ferrari”;
        switch (car) {
            case “Mustang”:
                System.out.println(“Price is 1cr”);
                break;
            case “Ford”:
                System.out.println(“Price is 50Lakhs”);
                break;
            default:
                System.out.println(“Invalid car”);
                break;
        }
    }
}

Output:
Invalid car

Code Explanation

public class Program {

This defines a public class named Program. A class in Java is a blueprint for creating objects, and public means that this class can be accessed from outside its containing package.

public static void main(String[] args) {

This is the entry point of your Java program. The main method is where execution begins. It takes an array of strings (args) as its parameter, which allows you to pass command-line arguments to your program.

String car = “Ferrari”;

This line declares a String variable named car and initializes it with the value “Ferrari”.

switch (car) {

This is a switch statement that performs different actions based on the value of the car variable. Each case represents a possible value for car, and the code within that case is executed if car matches the case.

case “Mustang”:
    System.out.println(“Price is 1cr”);
    break;

The case value is “Mustang”, but since the car variable value is “Ferrari”, this block of code is skipped, and the switch statement checks the next case.

case “Ford”:
    System.out.println(“Price is 50Lakhs”);
    break;

The case value is “Ford”, but since the car variable value is “Ferrari”, this block of code is also skipped, and the switch statement checks the default case.

default:
    System.out.println(“Invalid car”);
    break;

Since the car variable value doesn’t match any of the case values, the default case is executed, printing “Invalid car” to the console.

Output:
Invalid car

Tasks:
1. Write a java program to simulate a simple calculator. The program should prompt the user to enter two numbers and an arithmetic operation choice.
Output:

2. Day of the Week:
Create a method that takes an integer (1 to 7) representing the day of the week.
Use a switch statement to print the name of the day (e.g., 1 = Sunday).
Inside each case, use an if-else statement to print if the day is a weekday or weekend.

3. Grade Classification:
Create a method that takes a char (A, B, C, D, F) representing a grade.
Use a switch statement to print the full form of the grade (e.g., A = “Excellent”).
Inside the switch cases for A, B, and C, use an if-else statement to print a motivational message if the grade is A or B.

4. Season Checker:
Create a method that takes a string representing a season (Winter, Spring, Summer, Fall).
Use a switch statement to print an activity associated with that season.
Inside the switch cases, use an if-else statement to check if the season is “Summer” and print an additional message about staying hydrated.

5. Employee Role:
Create a class Employee with properties Name and Role.
In the main method, create an Employee object and use a switch statement on the Role property to print different messages for different roles (e.g., Manager, Developer, Intern).
Inside each switch case, use an if-else statement to print a different message if the Name is “John”.

6. Traffic Light:
Create a method that takes a string representing a traffic light color (Red, Yellow, Green).
Use a switch statement to print actions for each color (e.g., Red = “Stop”).
Inside the switch case for Yellow, use an if-else statement to print a different message if a boolean variable isPedestrian is true.

7. Shopping Discount:
Create a method that takes a string representing the type of customer (Regular, Member, VIP).
Use a switch statement to apply different discount percentages.
Inside each switch case, use an if-else statement to apply an additional discount if the purchase amount is over $100.

8. Browser Type:
Create a method that takes a string representing a browser name (Chrome, Firefox, Safari, Edge).
Use a switch statement to print the developer of the browser.
Inside the switch case for Chrome, use an if-else statement to check the version number and print if it is up-to-date.

9. Month Days:
Create a method that takes an integer (1 to 12) representing a month.
Use a switch statement to print the number of days in the month.
Inside the switch case for February, use an if-else statement to print if it is a leap year.

Course Video

YouTube Reference :

Frequently Asked Questions

Still have a question?

Let's talk

It allows testing a variable against multiple values, executing the matching block of code.

It supports byte, short, char, int, enums, strings, and wrapper classes.

Yes, the tutorial is available for free on Iqra Technology Academy.

It is designed for beginners learning Java programming.

The default case executes if no other cases match the switch expression.

The break statement terminates the switch block, preventing fall-through to other cases.

Yes, the tutorial is beginner-friendly and explains concepts step by step.

The tutorial focuses on free learning and does not mention a certificate.

Yes, the tutorial is available online and accessible 24/7.

Chatbot