switch Statement in Java

In Java, the switch statement is used for multi-branch decision-making based on the value of an expression. It's an alternative to using multiple if-else statements when you want to compare a single value to multiple possible constant values. 

Here's the basic syntax of a switch statement:

switch (expression) { case value1: // Code to execute if expression equals value1 break; case value2: // Code to execute if expression equals value2 break; // Additional cases for other values default: // Code to execute if none of the cases match }






Here's a breakdown of the components:

  • switch: This is the keyword that initiates the switch statement.
  • expression: This is the value or expression you want to compare. It should evaluate to a primitive data type (e.g., int, char, byte) or an enumerated data type (enum) in Java.
  • case: This keyword is used to define a specific value or constant that you want to compare against the expression.
  • value1, value2, etc.: These are the values or constants you want to compare with the expression. You can have multiple case statements.
  • break: This keyword is used to terminate the switch statement and exit to the end of the switch block when a match is found. It's important to include break statements to prevent fall-through to subsequent cases.
  • default (optional): This is an optional case that is executed if none of the other cases match. It serves as a default option.

Here's a practical example of a switch statement in Java:

package example; import java.util.Scanner; public class Example { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter number of month (1-12): "); int monthNumber = scanner.nextInt(); String monthName; switch (monthNumber) { case 1: monthName = "January"; break; case 2: monthName = "February"; break; case 3: monthName = "March"; break; case 4: monthName = "April"; break; case 5: monthName = "May"; break; case 6: monthName = "June"; break; case 7: monthName = "July"; break; case 8: monthName = "August"; break; case 9: monthName = "September"; break; case 10: monthName = "October"; break; case 11: monthName = "November"; break; case 12: monthName = "December"; break; default: monthName = "Invalid month"; } System.out.println("The month is " + monthName); } }






















In this example:

  • We have an int variable monthNumber representing the month's number (1 for January, 2 for February, and so on).
  • The switch statement compares the value of monthNumber to various cases (values 1 to 12) and assigns the corresponding monthName.
  • The break statement is used after each case block to exit the switch statement when a match is found.
  • If monthNumber doesn't match any of the cases, the default block is executed, assigning "Invalid month" to monthName.
  • Finally, we print the value of monthName.

This code determines the name of the month based on the monthNumber using a switch statement.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

EXERCISES

Here are some exercises to help you practice using the switch statement in Java:

  1. Day of the Week: Write a program that takes a number from 1 to 7 as input and uses a switch statement to display the corresponding day of the week (e.g., 1 for "Sunday," 2 for "Monday").
  2. Month Name: Create a program that takes a number from 1 to 12 as input and uses a switch statement to display the corresponding month name (e.g., 1 for "January," 2 for "February").
  3. Simple Calculator: Build a calculator program that takes two numbers and an operator (+, -, *, /) as input and uses a switch statement to perform the selected operation and display the result.
  4. Grade Calculator: Write a program that calculates a student's letter grade (A, B, C, D, or F) based on their numerical score. Use a switch statement to handle different score ranges.
  5. Traffic Light Simulator: Simulate a traffic light system with red, yellow, and green lights. Use a switch statement to control the sequence of lights and their durations.
  6. Menu Selection: Create a text-based menu with different options (e.g., for a restaurant menu or a game menu). Use a switch statement to execute the selected option.
  7. Season Identifier: Develop a program that identifies the season (e.g., winter, spring, summer, fall) based on a user-entered month. Use a switch statement to determine the season.
  8. Character Classification: Write a program that classifies a character entered by the user as a vowel, consonant, digit, or special character using a switch statement.
  9. Day Counter: Create a program that takes a month and year as input and uses a switch statement to calculate and display the number of days in that month. Handle leap years accordingly.
  10. Language Translator: Build a simple language translator program that takes a word in English and uses a switch statement to display its translation in another language (e.g., English, Roman Urdu).
  11. File Type Identifier: Write a program that takes a file extension as input and uses a switch statement to determine the type of file (e.g., text, image, video) based on the extension.
  12. Color Mixer: Create a program that takes two primary colors (e.g., red, blue, yellow) as input and uses a switch statement to mix and display the resulting secondary color (e.g., purple, green, orange).
  13. Unit Converter: Build a unit converter program that converts between different units of measurement (e.g., length, weight, temperature) using a switch statement to select the conversion type.

These exercises will help you become more comfortable and skilled in using the switch statement for various decision-making scenarios in Java programs.


Comments

Popular posts from this blog

Lecture 2 - How to Take Input From User in Java

Programming Conventions in Java

Why Java is Called Java?