switch case statements can be used to execute a specific for a certain parameter or condition. The usage os switch case statement is demonstrated in the below code:
It is not possible in Java to provide a range in each case. But it can be achieved by using a set of if-else statements:
public class AgeCategory { public static void main(String[] args) { int age_1 = 25; String category = getCategory(age_1); switch (category) { case "Child": System.out.println("You are a child."); break; case "Teen": System.out.println("You are a teenager."); break; case "Adult": System.out.println("You are an adult."); break; default: System.out.println("Invalid Age"); break; } } |
public static String getCategory(int age_2) { if (age_2 >= 0 && age_2 <= 12) { return "Child"; } else if (age_2 >= 13 && age_2 <= 19) { return "Teen"; } else if (age_2 >= 20 && age_2 <= 64) { return "Adult"; } else if (age_2 >= 65) { return "Senior"; } else { return "Invalid"; } } } |