1.switch statement in Java
Lets get started
In Java, the switch statement is used for flow control based on the value of an expression. It allows you to write more concise and readable code when you have multiple conditions to check against a single variable. The basic syntax of a switch statement looks like this:
syntax :
switch (expression) { case value1: // Code to execute if expression matches value1 break; case value2: // Code to execute if expression matches value2 break; // More case statements... default: // Code to execute if none of the cases match }
Elaborate with a simple example :
- /*Now we are going to design a simple code in switch case in java
- here we will take the month number number as the input from the user
- and then we will check each case and print the appropriate month name
- */
- import java.util.* ;
- public class MINtech{
- public static void main(String args[]){
- // calling the scanner class
- Scanner sc = new Scanner(System.in);
- System.out.println("Enter Month numebr(1-12) : ") ;
- // taking int as a input
- int num = sc.nextInt();
- // Initializing switch condition
- switch(num){
- // checking whether the num is equals to 1 or not
- case 1 :
- // Printing month name
- System.out.println("Jan");
- //Using break to exit case
- break ;
- // checking whether the num is equals to 1 or not
- case 2 :
- // Printing month name
- System.out.println("Feb");
- //Using break to exit case
- break;
- case 3 :
- System.out.println("Mar");
- break ;
- case 4:
- System.out.println("Apr");
- break;
- case 5 :
- System.out.println("May");
- break ;
- case 6 :
- System.out.println("Jun");
- break;
- case 7 :
- System.out.println("Jul");
- break ;
- case 8 :
- System.out.println("Aug");
- break;
- case 9 :
- System.out.println("Sep");
- break ;
- case 10 :
- System.out.println("Oct");
- break;
- case 11 :
- System.out.println("Nov");
- break ;
- case 12 :
- System.out.println("Dec");
- break;
- // default will executed if num is not matched with
- //the anyone of the above mentioned cases
- default:
- System.out.println("Inavalid month");
- break ;
- }
- }
- }
Output
Enter Month numebr(1-12) : 3 Mar Enter Month numebr(1-12) : 5 May Enter Month numebr(1-12) : 12 Dec Enter Month numebr(1-12) : 14 Inavalid month
No comments:
Post a Comment