Switch Case in Java
Definition - switch is a decision-making statement (like if-else) that lets you choose one
option out of many based on the value of a variable.
It’s best used when you’re comparing one value against fixed constants (not ranges or
conditions).
Syntax of Switch in java :
switch (expression) {
case value1:
// Code block if expression == value1
break;
case value2:
// Code block if expression == value2
break;
case value3:
// Code block if expression == value3
break;
default:
// Code block if no case matches
}
Q1. Write a java program to calculate grade when percentage is given
import java.util.Scanner;
public class GradeCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input percentage
System.out.print("Enter your percentage: ");
int percentage = sc.nextInt();
// Store Grade
char grade;
switch (percentage / 10) {
case 10: // 100%
case 9: // 90 - 99
grade = 'A';
break;
case 8: // 80 - 89
grade = 'B';
break;
case 7: // 70 - 79
grade = 'C';
break;
case 6: // 60 - 69
grade = 'D';
break;
case 5: // 50 - 59
grade = 'E';
break;
default: // Below 50
grade = 'F';
break;
}
// Output result
System.out.println("Your grade is: " + grade);
}
}
Output –
Q2. Write a Java program that takes a number (1–7) as input from the user and prints the
corresponding day of the week using a switch-case statement.
Ans 2.
import java.util.Scanner;
public class Days {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input Date
System.out.print("Enter number : ");
int day = sc.nextInt();
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("Wrong Input");
}
}
}
Output –