Java Switch Statement

Hello there, fellow coder! Today, we’re going to dive into the world of Java and explore the switch statement. Buckle up, because this is going to be a fun ride!

Introduction

Ever found yourself at a crossroads, unsure of which path to take? Well, your program feels the same way sometimes. That’s where the Java switch statement comes in. It’s like a traffic cop, directing your code down the right path. Let’s find out more!

Understanding the Java Switch Statement

The switch statement in Java is a type of control flow statement that allows a variable to be tested for equality against a list of values. Each value is a case, and the variable we’re switching on is checked against each case.

switch(variable) {
  case value1:
    // code to be executed if variable equals value1;
    break;
  case value2:
    // code to be executed if variable equals value2;
    break;
  // You can have any number of case statements.
  default:
    // code to be executed if variable does not match any cases;
}
Java

 Flow of a Java Switch statement
Flow of a Java Switch statement

Working with Java Switch Case

In a switch statement, the case keyword is used to specify the values that the variable will be compared against. If a match is found, the code block following the case is executed.

int day = 3;
switch(day) {
  case 1:
    System.out.println("Monday");
    break;
  case 2:
    System.out.println("Tuesday");
    break;
  case 3:
    System.out.println("Wednesday");
    break;
  // And so on...
}
Java

The Role of Break in Java Switch

The break keyword is used to exit the switch statement. Without it, the program would continue executing the next case even if a match has already been found. It’s like telling your code, “Okay, we’ve found what we’re looking for. You can stop now.”

int day = 3;
switch(day) {
  case 1:
    System.out.println("Monday");
    break;
  case 2:
    System.out.println("Tuesday");
    break;
  case 3:
    System.out.println("Wednesday");
    // Without break, the program would continue to the next case
    break;
  // And so on...
}
Java

Java Switch Case Fall Through

But what if we want our code to continue executing the next case? That’s where the concept of ‘fall through’ comes in. By omitting the break statement, we can make our program ‘fall through’ to the next case.

int day = 3;
switch(day) {
  case 1:
  case 2:
  case 3:
  case 4:
  case 5:
    System.out.println("It's a weekday");
    break;
  case 6:
  case 7:
    System.out.println("It's a weekend");
    break;
  default:
    System.out.println("Invalid day");
}
Java

Java Switch with String

Starting from Java 7, we can use switch with String variables. This opens up a whole new world of possibilities!

String day = "Wednesday";
switch(day) {
  case "Monday":
    System.out.println("Start of the work week");
    break;
  case "Tuesday":
    System.out.println("At least it's not Monday");
    break;
  case "Wednesday":
    System.out.println("Hump day!");
    break;
  // And so on...
}
Java

Java Switch vs If-Else

switch and if-else statements are like two sides of the same coin. They both allow your program to choose a path based on certain conditions. However, switch is more efficient and easier to read when dealing with a variable that can take on a small, fixed set of values.

// Using if-else
if(day.equals("Monday")) {
  System.out.println("Start of the work week");
} else if(day.equals("Tuesday")) {
  System.out.println("At least it's not Monday");
} else if(day.equals("Wednesday")) {
  System.out.println("Hump day!");
} // And so on...

// Using switch
switch(day) {
  case "Monday":
    System.out.println("Start of the work week");
    break;
  case "Tuesday":
    System.out.println("At least it's not Monday");
    break;
  case "Wednesday":
    System.out.println("Hump day!");
    break;
  // And so on...
}
Java

Code Examples

Let’s put everything we’ve learned into practice with two complete code examples.

Example 1: Day of the Week

int day = 3;
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");
}
Java

This code will output Wednesday because the value of day is 3.

Example 2: Calculator

char operator = '+';
int num1 = 5, num2 = 3;

switch(operator) {
  case '+':
    System.out.println(num1 + num2);
    break;
  case '-':
    System.out.println(num1 - num2);
    break;
  case '*':
    System.out.println(num1 * num2);
    break;
  case '/':
    if(num2 != 0) {
      System.out.println(num1 / num2);
    } else {
      System.out.println("Cannot divide by zero");
    }
    break;
  default:
    System.out.println("Invalid operator");
}
Java

This code will output 8 because the operator is + and the sum of num1 and num2 is 8.

Wrapping Up

And that’s a wrap on the Java switch statement! It’s a powerful tool in your coding arsenal, allowing your program to choose from multiple paths based on a variable’s value. Remember to use break to exit the switch statement, unless you want your program to ‘fall through’ to the next case.

Frequently Asked Questions (FAQ)

  • What are the rules for switch in Java?

    The switch expression must be of byte, short, int, char, enum, or String type. The case values must be constant or literal. Variables are not allowed. The case values must be unique. Duplicate values are not allowed. The switch statement can have an optional default case, which must appear at the end of the switch. The default case is used when none of the case values match the switch expression.

  • Should we use switch in Java?

    Yes, the switch statement is a powerful control flow statement in Java that can make your code more efficient and easier to read when dealing with a variable that can take on a small, fixed set of values.

  • How to use switch operator in Java?

    The switch operator in Java is used by providing a variable to the switch statement and then defining different case values that this variable will be compared against. If a match is found, the code block following the case is executed.

  • How to use switch case instead of if-else in Java?

    switch case can be used instead of if-else when you have a variable that can take on a small, fixed set of values. Each value is a case, and the variable being switched on is checked against each case.

  • What is the default case in Java Switch?

    The default case in a Java switch statement is used when none of the case values match the switch expression. It’s like the “else” in an if-else statement.

  • Can we use Switch with Strings in Java?

    Yes, starting from Java 7, we can use switch with String variables. This opens up a whole new world of possibilities!

  • What is a ‘fall through’ in Java Switch?

    ‘Fall through’ in a Java switch statement refers to the scenario where the program continues executing the next case even if a match has already been found. This happens when the break statement is omitted.

  • How does ‘break’ work in Java Switch?

    The break keyword is used to exit the switch statement. Without it, the program would continue executing the next case even if a match has already been found.

  • Can we use Switch without ‘break’ in Java?

    Yes, we can use switch without break in Java. This is known as ‘fall through’, where the program continues executing the next case even if a match has already been found.

  • What is the difference between Switch and If-Else in Java?

    switch and if-else statements are both control flow statements in Java. However, switch is more efficient and easier to read when dealing with a variable that can take on a small, fixed set of values. On the other hand, if-else is more flexible and can handle more complex conditions.

  1. Java If-Else Statement: Dive into the basics of control flow in Java with the if-else statement. Learn how to guide your program down different paths based on specific conditions.
  2. Java Loops: Get to grips with for, while, and do-while loops in Java. Discover how to perform repetitive tasks efficiently in your code.
  3. Java Methods: Learn about methods in Java, the building blocks of any Java program. Understand how to define your own methods and use built-in Java methods.
  4. Java Arrays: Explore the world of Java arrays. Learn how to declare, initialize, and manipulate arrays in Java.
  5. Java Strings: Master the String class in Java. Learn how to create, concatenate, compare, and convert strings, and much more.
  6. Java Exception Handling: Get a handle on errors in your Java code with exception handling. Learn about try, catch, finally, and throw statements, and how to create your own exceptions.

Remember, practice makes perfect. So, don’t forget to try out the examples and exercises in these tutorials. Happy coding!

Scroll to Top