Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Working with Switch Statements in Java

In this lesson, you will learn

  • The switch statement
  • if..else v/s switch statements

 

What is a Switch Statement in Java

The switch statement in Java is a multi-branch decision-making control structure. It allows a variable or expression to be tested against multiple constant values and executes the corresponding block of code.

Each value is called a “case”, and the variable being switched on is checked for each case.

Purpose

  • Simplifies multiple if–else if conditions

  • Improves readability and maintainability

  • Efficient for discrete value comparisons

Syntax

switch (expression) {
    case value1:
        // Code block
        break; // Optional
    
    case value2:
        // Code block
        break; // Optional
    // You can have any number of case statements.
    
    default: // Optional
        // Code block
}

  • expression: This is the value that is compared with the values of each case. It must be a char, byte, short, int, enum, String, or wrapper class like Character, Byte, Short, or Integer.
  • case value: Each case value must be a unique constant or literal.
  • break: It is used to exit the switch statement. If omitted, the execution will continue into the next case. It prevents fall-through.
  • default: It is executed if none of the cases match the expression. It is optional, but it’s usually a good practice to include it.

 

Example-1: Basic Switch with Primitive Data Type

package ch5;

public class CheckDays {

	public static void main(String[] args) {
		int day = 4;
		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

Thursday

 

Example-2: Switch with Strings (Java 7 Features)

package ch5;

public class CheckMonths {

	public static void main(String[] args) {
		String month = "July";
		switch (month) {
		    case "January":
		        System.out.println("Month is January");
		        break;
		    case "February":
		        System.out.println("Month is February");
		        break;
		    case "July":
		        System.out.println("Month is July");
		        break;
		    // Additional cases
		    default:
		        System.out.println("Unknown month");
		}

	}
}

 

Output

Month is July

 

Example-3: Switch Without Break (Fall-through)

package ch5;

public class SwitchFallThrough {

	public static void main(String[] args) {
		int number = 2;
		switch (number) {
		    case 1:
		    case 2:
		    case 3:
		        System.out.println("Number is 1, 2, or 3");
		        break;
		    default:
		        System.out.println("Number is not 1, 2, or 3");
		}
	}
}

 

Output

Number is 1, 2, or 3

 

Example-4: Using Enum in Switch

package ch5;

public class SwitchEnum {
	
	enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }

	public static void main(String[] args) {
		Day day = Day.MONDAY;

		switch (day) {
		    case MONDAY:
		        System.out.println("Today is Monday");
		        break;
		    case FRIDAY:
		        System.out.println("Today is Friday");
		        break;
		    // Other cases
		}
	}
}

 

Output

Today is Monday

 

Example-5: Nested Switch

package ch5;

public class NestedSwitch {

	public static void main(String[] args) {
		char grade = 'B';
		int year = 2;

		switch (year) {
		    case 1:
		        System.out.println("First Year");
		        break;
		    case 2:
		        switch (grade) {
		            case 'A':
		                System.out.println("Excellent");
		                break;
		            case 'B':
		                System.out.println("Very Good");
		                break;
		            // Other grades
		        }
		        break;
		    // Other years
		}
	}
}

 

Output

Very Good

 

Difference b/w if…else and switch statements

Both if-else and switch Statements in Java are used for controlling the flow of execution through a program. However, they have different use cases and characteristics.

Here’s a summary table explaining their differences:

Feature If-Else Switch
Basic Concept Conditional branches are based on true/false evaluations of expressions. A branching mechanism based on matching a variable’s value to specific cases.
Syntax Complexity Can get complicated with nested conditions. Simpler and cleaner, especially with many conditions.
Type Support Can evaluate conditions using any type of expressions that result in a Boolean. Primarily supports integer, enumerated types, or String objects (in newer versions of Java).
Flexibility More flexible, and can evaluate complex and varied conditions. Limited to comparing a single variable’s value against multiple cases.
Default Behavior No default statements Has a default case for handling unmatched cases.
Performance Performance can vary with complexity and the number of conditions. Generally faster for a large number of cases due to optimization.
Use Case Best for conditions that are not solely based on the value of a single variable or where conditions are complex. Best for scenarios where a single variable is compared against multiple constant values.

 


End of the lesson….enjoy learning

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review