08 Java Fundamentals | Switch statements in Java | By Dummy for Dummies
INTRODUCTION:
Switch is another way to handle more than one pathways a code can take. When the conditions are more than just few then it is prefered to use Switches . There are few differences based on which programmer can decide when to use if-else or Switch statements.
KEY FEATURES OF SWITCHES
⦿ Unlike if-else , Switch does not perform operations for conditions
⦿ Switch is applied on one single variable
⦿ All possible values that variable may contain are listed as cases
⦿ Each case must contain value NOT variable
⦿ A default case is added at the ended, executes if none matches
Demonstration:
public class Main {
public static void main(String[] args) {
int n = 2; // Variable to test
switch (n) { // Applying switch on n variable
case 1: // Case for value 1
System.out.println("The value in variable is 1");
break;
case 2: // Case for value 2
System.out.println("The value in variable is 2");
break;
case 3: // Case for value 3
System.out.println("The value in variable is 3");
break;
default: // Default case for any other value
System.out.println("None of the cases matches");
}
}
}
OUTPUT:
Here n contains 2, it will match the second case and execute the print code inside it
CODE WITHOUT BREAK STATEMENT
public class Main {
public static void main(String[] args) {
int n = 2; // Variable to test
switch (n) {
case 1:
System.out.println("The value in variable is 1");
case 2:
System.out.println("The value in variable is 2");
case 3:
System.out.println("The value in variable is 3");
default:
System.out.println("None of the cases match");
}
}
}
Without break, there is not stopping them. And execution of one triggers execution of all remaining statements. Therefore using break becomes extremely necessary.
GROUPED CASES
Sometimes we want multiple cases to run same code. One way is to put same code inside all those cases. But a cleaner method is below:
public class Main {
public static void main(String[] args) {
int day = 5; // 1 = Monday, 7 = Sunday
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("It's not a day!");
}
}
}
OUTPUT (for 6,7)
OUTPUT (for any other number)
It's not a day!
POINTS TO REMEMBER
EXERCISE
Let's do an exercise for what we studied in this post. Study this code, break it down, analyze it and identify the concepts used here. It would be even better if you write down your observations and make a mini report on it.
import java.util.Scanner;
public class SwitchExercise {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("=== SWITCH STATEMENT EXERCISE ===");
System.out.print("Enter a day number (1-7): ");
int day = input.nextInt();
// --- Simple switch with grouped cases ---
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("It's a weekday. Time to study and work!");
break;
case 6:
case 7:
System.out.println("It's the weekend. Enjoy your rest!");
break;
default:
System.out.println("Invalid day number! Please enter 1 to 7.");
}
// --- Switch on characters ---
System.out.print("Enter a grade (A, B, C, D, F): ");
char grade = input.next().charAt(0);
switch (grade) {
case 'A':
System.out.println("Excellent!");
break;
case 'B':
System.out.println("Good job");
break;
case 'C':
System.out.println("Fair, but can improve");
break;
case 'D':
System.out.println("Needs improvement");
break;
case 'F':
System.out.println("Failed");
break;
default:
System.out.println("Invalid grade input!");
}
// --- Switch on strings ---
System.out.print("Enter your favorite fruit: ");
String fruit = input.next().toLowerCase(); // Convert to lowercase for consistency
switch (fruit) {
case "apple":
case "banana":
case "orange":
System.out.println("That's a healthy choice! ");
break;
case "burger":
case "pizza":
System.out.println("That's tasty but not healthy! ");
break;
default:
System.out.println("Interesting choice!");
}
input.close();
}
}
MINI PROJECT: (Simple Banking System)
Your project is to create a simple Java program that works like a small banking system using a menu. The program should display the following menu to the user:
1. Check Balance
2. Deposit Money
3. Withdraw Money
4. Exit
The user should enter a choice, and the program should use a switch statement to handle that choice. If the user selects Deposit Money or Withdraw Money, the program should update the balance variable accordingly.
If the user enters an invalid choice, the program should display “Invalid Option.”
Finally, the program should continue until the user chooses Exit.
While writing the program, make sure you use:
⦿ Scanner for input
⦿ A switch statement with multiple cases
⦿ A variable to keep track of balance
⦿ At least one printf statement for formatted output
EXAMPLE OUTPUT: