Switch statement in Java;
In this section we are going to discuss about switch statement in Java.
- Switch statement allows us to execute one statement from many statement and the statements are termed as case.
- Inside the body of switch there will be many number of cases and there is a single number is passed at the place of parameter to select and execute the case.
Syntax;
- In the switch statement a value/number is passed in the place of parameter and the case from which the parameter is matched is executed.
- If none of the case is matched with parameter then default case will be executed.
Example 1:
class Easy
{
public static void main(String[] args)
{
int day=2;
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("Thrusday");
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("No case matched");
}
}
}
/ ### Output ###
Tuesday because day is equal to 2 and it matches with case 2 so the output is Tuesday
Example 2: Check given Alphabet is vowel or consonant.
import java.util.Scanner;
class Easy
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
char ch;
System.out.println("Enter any alphabet");
ch=in.next().charAt(0);
switch(ch)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
System.out.println("Vowel");
break;
default:
System.out.println("Consonant");
}
}
}
/ ### Output ###
Enter any alphabet m.
Consonant /
For Videos Join Our Youtube Channel: Join NowThank you!