Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
64 views26 pages

7.0java Switch Statement

Uploaded by

robsonchungu5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views26 pages

7.0java Switch Statement

Uploaded by

robsonchungu5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

SWITCH STATEMENT IN JAVA

Java Switch Statement:

Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which is
being switched. The switch statement is easier to use instead of if-else-if statements. It also
enhances the readability of the program.

Points to be noted about switch statement:

o The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of expression.
It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value.

 The Java switch statement executes one statement from multiple conditions.
It is like if-else-if ladder statement.

 The switch statement works with byte, short, int, long, enum types, String
and some wrapper types like Byte, Short, Int, and Long. Since Java 7, you
can use strings in the switch statement. In other words, the switch statement
tests the equality of a variable against multiple values.

Points to Remember
o There can be one or N number of case values for a switch expression.
o The case value must be of switch expression type only. The case value must
be literal or constant. It doesn't allow variables.
o The case values must be unique. In case of duplicate value, it renders
compile-time error.
o The Java switch expression must be of byte, short, int, long (with its
Wrapper type), enums and string.
o Each case statement can have a break statement which is optional. When
control reaches to the break statement, it jumps the control after the switch
expression. If a break statement is not found, it executes the next case.
o The case value can have a default label which is optional.

Syntax:

1. switch(expression) {

2. case value1:

3. //code to be executed;

4. break; //optional

5. case value2:

6. //code to be executed;

7. break; //optional

8. ......

9. default:

10. code to be executed if all cases are not matched;

11. }
SWITCH STATEMENT
The Java switch statement executes one statement from multiple conditions. It is like if-
else-if ladder statement. The switch statement works with byte, short, int, long, enum
types, String and some wrapper types like Byte, Short, Int, and Long. Since Java 7, you
can use strings in the switch statement.
NOTE: While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value. The switch permits only int,
string, and Enum type variables to be used.

In other words, the switch statement tests the equality of a variable against multiple
values.

Syntax:

switch(expression){
case value1:
//code to be executed;
break;
//optional
case value2:
//code to be executed; break;
//optional
......

default:
code to be executed if all cases are not matched;
}

Example:
public class SwitchExample {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30:
System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or 30");
}
}
}

Example1:

1. public class SwitchExample {


2. public static void main(String [] args) {
3. int number=20; //Declaring a variable for switch expression
4. switch(number) { //Switch expression
5. //Case statements
6. case 10: System.out.println("10");
7. break;
8. case 20: System.out.println("20");
9. break;
10. case 30: System.out.println("30");
11. break;
12. //Default case statement
13. default:
14. System.out.println("Not in 10, 20 or 30");
15. }}}
Output:
20

Consider the following example to understand the flow of the switch statement.

Student.java

1. public class Student implements Cloneable {

2. public static void main(String[] args) {

3. int num = 2;

4. switch (num){

5. case 0:

6. System.out.println("number is 0");
7. break;

8. case 1:

9. System.out.println("number is 1");

10. break;

11. default:

12. System.out.println(num);

13. }

14. }

15. }

Output: 2

Example2:
Program to check Vowel or Consonant:

If the character is A, E, I, O, or U, it is vowel otherwise consonant. It is not case-sensitive .


1. public class SwitchVowelExample {
2. public static void main(String [] args) {
3. char ch='O';
4. switch(ch){
5. case 'a':
6. System.out.println("Vowel");
7. break;
8. case 'e':
9. System.out.println("Vowel");
10. break;
11. case 'i':
12. System.out.println("Vowel");
13. break;
14. case 'o':
15. System.out.println("Vowel");
16. break;
17. case 'u':
18. System.out.println("Vowel");
19. break;
20. case 'A':
21. System.out.println("Vowel");
22. break;
23. case 'E':
24. System.out.println("Vowel");
25. break;
26. case 'I':
27. System.out.println("Vowel");
28. break;
29. case 'O':
30. System.out.println("Vowel");
31. break;
32. case 'U':
33. System.out.println("Vowel");
34. break;
35. default:
36. System.out.println("Consonant");
37. }}}

Output:

Vowel

Java Switch Statement is fall-through


The Java switch statement is fall-through. It means it executes all statements after the first match if
a break statement is not present.

Example3:

1. //Java Switch Example where we are omitting the


2. //break statement
3. public class SwitchExample2 {
4. public static void main(String[] args) {
5. int number=20;
6. //switch expression with int value
7. switch(number) {
8. //switch cases without break statements
9. case 10: System.out.println("10");
10. case 20: System.out.println("20");
11. case 30: System.out.println("30");
12. default:
13. System.out.println("Not in 10, 20 or 30");
14. }}}
15.
Output:

20
30
Not in 10, 20 or 30

Finding Month

Example 4:

//Java Program to demonstrate the example of Switch statement


//where we are printing month name for the given number
1. public class SwitchMonthExample {
2. public static void main(String [] args) {
3. //Specifying month number
4. int month=7;
5. String monthString="";
6. //Switch statement
7. switch(month){
8. //case statements within the switch block
9. case 1: monthString="1 - January";
10. break;
11. case 2: monthString="2 - February";
12. break;
13. case 3: monthString="3 - March";
14. break;
15. case 4: monthString="4 - April";
16. break;
17. case 5: monthString="5 - May";
18. break;
19. case 6: monthString="6 - June";
20. break;
21. case 7: monthString="7 - July";
22. break;
23. case 8: monthString="8 - August";
24. break;
25. case 9: monthString="9 - September";
26. break;
27. case 10: monthString="10 - October";
28. break;
29. case 11: monthString="11 - November";
30. break;
31. case 12: monthString="12 - December";
32. break;
33. default: System.out.println("Invalid Month!");
34. }
35. //Printing month of the given number
36. System.out.println(monthString);
37. }}

Output:
7 – July

Java Switch Statement with String


Java allows us to use strings in switch expression since Java SE 7. The case statement should be
string literal.
Example 5:
1. //Java Program to demonstrate the use of Java Switch
2. //statement with String
3. public class SwitchStringExample {
4. public static void main(String[] args) {
5. //Declaring String variable
6. String levelString="Expert";
7. int level=0;
8. //Using String in Switch expression
9. switch(levelString){
10. //Using String Literal in Switch case
11. case "Beginner": level=1;
12. break;
13. case "Intermediate": level=2;
14. break;
15. case "Expert": level=3;
16. break;
17. default: level=0;
18. break;
19. }
20. System.out.println("Your Level is: "+level);
21. }}
Output:

Switch Month

Scanner scan = new Scanner(System.in);


System.out.println(“Enter the number to display the month name: ”);

int month = scan.nextInt();


Switch(month){
Case1:
System.out.println(“January”);
Break;
Case2:
System.out.println(“February”);
Break;
Case2:
System.out.println(“March”);
Break;
Case2:
System.out.println(“April”);
Break;
Case2:
System.out.println(“May”);
Break;
Case2:
System.out.println(“June”);
Break;
Case2:
System.out.println(“July”);
Break;
Case2:
System.out.println(“August”);
Break;
Case2:
System.out.println(“September”);
Break;
Case2:
System.out.println(“October”);
Break;
Case2:
System.out.println(“November”);
Break;
Case2:
System.out.println(“December”);
Break;
Default:
System.out.println(“Invalid Month”);
}

SWITCH –USING SCANNER


Inport java.util.Scanner;
Public class{
Public static void main(String[]args){

Int num1, num2;

Scanner input = new Scanner(System.in);


System.out.println(“Enter first and second number: ”);
num1=input.nextInt();
num2=input.nextInt();
int ans:
System.out.println(“Enter your selection: 1 for Addition”);
System.out.println(“Enter your selection: 2 for Subtraction”);
System.out.println(“Enter your selection: 3 for Multiplication”);
System.out.println(“Enter your selection: 4 for Division”);

Int choose:
Choose = input.nextInt();

switch(choose){
case 1:
System.out.println(add(num1,num2));
Break;
Case 2:
System.out.println(sub(num1,num2));
Break;
Case 3:
System.out.println(mult(num1,num2));
Break;
Case 4:
System.out.println(div(num1,num2));
Break;
Default;
System.out.println(“Invalid operation ”);
}
}
Java Nested Switch Statement
We can use switch statement inside other switch statement in Java. It is known as nested switch
statement.

Example 6:

1. //Java Program to demonstrate the use of Java Nested Switch


2. public class NestedSwitchExample {
3. public static void main(String args[]){
4. //C - CSE, E - ECE, M - Mechanical
5. char branch = 'C';
6. int collegeYear = 4;
7. switch( collegeYear ){
8. case 1:
9. System.out.println("English, Maths, Science");
10. break;
11. case 2:
12. switch( branch ){
13. case 'C':
14. System.out.println("Operating System, Java, Data Structure");
15. break;
16. case 'E':
17. System.out.println("Micro processors, Logic switching theory");
18. break;
19. case 'M':
20. System.out.println("Drawing, Manufacturing Machines");
21. break;
22. }
23. break;
24. case 3:
25. switch( branch )
26. {
27. case 'C':
28. System.out.println("Computer Organization, Multi-Media");
29. break;
30. case 'E':
31. System.out.println("Fundamentals of Logic Design, Microelectronics");
32. break;
33. case 'M':
34. System.out.println("Internal Combustion Engines, Mechanical Vibration");
break;
35. }
36. break;
37. case 4:
38. switch( branch ){
39. case 'C':
40. System.out.println("Data Communication and Networks, Multi-
Media");
41. break;
42. case 'E':
43. System.out.println("Embedded System, Image Processing");
44. break;
45. case 'M':
46. System.out.println("Production Technology, Thermal Engineering");
47. break;
48. }
49. break;
50. }}}

Output:

Data Communication and Networks, Multi-Media

JAVA SWITCH CASE 7.

SWITCH CASE - The Java switch statement executes one statement from multiple conditions. It
is like if-else-if ladder statement.
- In other words, the switch statement tests the equality of a variable against
multiple values.
- A Switch statement allows a variable to be tested for equality against a list of
values. Each value is called a CASE, and the variable being switched
on is checked for each case.

int j=2;
Switch(j){ //compiler checks here and look for the case that matches it
case 0;
System.out.println("Value is 0");
break;
case 1:
System.out.println("Value is 1");
break;
case 2:
System.out.println("Value is 2"); //This will be printed out to the console
break;// but if you do not break case 3.
case 3:
System.out.println("Value is 3");
break;
default:
System.out.println("No Value");
break;
}}

//Switch case statement is mostly used with Break Statement even though it is optional.
A Simple Switch Case Example

public class SwitchCaseExample {


public static void main (String [] args){

int num = 2;
Switch(num+2){
case1:
System.out.println("Case1: Value is: "+num);
case2:
//break;
System.out.println("Case2: Value is: "+num);
case3
//break;
System.out.println("Case3: Value is: "+num);
default:
System.out.println("Default: Value is: "+num);
}}}

Java Enum in Switch Statement


Java allows us to use enum in switch statement.

Example 8:

1. //Java Program to demonstrate the use of Enum


2. //in switch statement
3. public class JavaSwitchEnumExample {
4. public enum Day {Sun, Mon, Tue, Wed, Thu, Fri, Sat}
5. public static void main (String args []){
6. Day[] DayNow = Day.values();
7. for (Day Now : DayNow){
8. switch (Now){
9. case Sun:
10. System.out.println("Sunday");
11. break;
12. case Mon:
13. System.out.println("Monday");
14. break;
15. case Tue:
16. System.out.println("Tuesday");
17. break;
18. case Wed:
19. System.out.println("Wednesday");
20. break;
21. case Thu:
22. System.out.println("Thursday");
23. break;
24. case Fri:
25. System.out.println("Friday");
26. break;
27. case Sat:
28. System.out.println("Saturday");
29. break;
30. }
31. }
32. }}

Output:

Sunday

Monday

Tuesday

Wednesday

Thursday

Friday

Saturday

Java Wrapper in Switch Statement


Java allows us to use four wrapper classes: Byte, Short, Integer and Long in switch statement.

Example 9:

1. //Java Program to demonstrate the use of Wrapper class


2. //in switch statement
3. public class WrapperInSwitchCaseExample {
4. public static void main (String args []){
5. Integer age = 18;
6. switch (age){
7. case (16):
8. System.out.println("You are under 18.");
9. break;
10. case (18):
11. System.out.println("You are eligible for vote.");
12. break;
13. case (65):
14. System.out.println("You are senior citizen.");
15. break;
16. default:
17. System.out.println("Please give the valid age.");
18. break;
19. }}
Output:
You are eligible for vote.

Example 10:

SWITCH STATEMENT

class switchCaseDemo{
public static void main(String[]args){
char grade='c';
switch(grade){
case'A':
System.out.println("Exellent!");
break;
case'B':
System.out.println("Good!");
Break;
Case'C':
System.out.println("Well done!");
Break;
Case'D':
System.out.println("You passed!");
Break;
Case'F':
System.out.println("Better try a gain!");
Break;
Default:
System.out.println("Invalid grade!");
}
System.out.println("Your grade is "+grade);
}}
Java Switch Statement is fall-through
The Java switch statement is fall-through. It means it executes all statements after the first match
if a break statement is not present.

Example:

SwitchExample2.java

1. //Java Switch Example where we are omitting the

2. //break statement

3. public class SwitchExample2 {

4. public static void main(String[] args) {

5. int number=20;

6. //switch expression with int value

7. switch(number){

8. //switch cases without break statements

9. case 10: System.out.println("10");

10. case 20: System.out.println("20");

11. case 30: System.out.println("30");

12. default:System.out.println("Not in 10, 20 or 30");

13. }

14. }

15. }

Output:

20

30
Not in 10, 20 or 30

Java Switch Statement with String


Java allows us to use strings in switch expression since Java SE 7. The case statement should be
string literal.

Example:

SwitchStringExample.java

1. //Java Program to demonstrate the use of Java Switch

2. //statement with String

3. public class SwitchStringExample {

4. public static void main(String[] args) {

5. //Declaring String variable

6. String levelString="Expert";

7. int level=0;

8. //Using String in Switch expression

9. switch(levelString){

10. //Using String Literal in Switch case

11. case "Beginner": level=1;

12. break;

13. case "Intermediate": level=2;

14. break;

15. case "Expert": level=3;

16. break;

17. default: level=0;

18. break;
19. }

20. System.out.println("Your Level is: "+level);

21. }

22. }

Output:

Your Level is: 3

Java Nested Switch Statement


We can use switch statement inside other switch statement in Java. It is known as nested switch
statement.

Example:

NestedSwitchExample.java

1. //Java Program to demonstrate the use of Java Nested Switch

2. public class NestedSwitchExample {

3. public static void main(String args[]){

4. //C - CSE, E - ECE, M - Mechanical

5. char branch = 'C';

6. int collegeYear = 4;

7. switch( collegeYear ){

8. case 1:

9. System.out.println("English, Maths, Science");

10. break;

11. case 2:

12. switch( branch ){

13. case 'C':


14. System.out.println("Operating System, Java, Data Structure");

15. break;

16. case 'E':

17. System.out.println("Micro processors, Logic switching theory");

18. break;

19. case 'M':

20. System.out.println("Drawing, Manufacturing Machines");

21. break;

22. }

23. break;

24. case 3:

25. switch( branch ){

26. case 'C':

27. System.out.println("Computer Organization, MultiMedia");

28. break;

29. case 'E':

30. System.out.println("Fundamentals of Logic Design, Microelectronics");

31. break;

32. case 'M':

33. System.out.println("Internal Combustion Engines, Mechanical Vibration")

34. break;

35. }

36. break;
37. case 4:

38. switch( branch )

39. {

40. case 'C':

41. System.out.println("Data Communication and Networks, MultiMedia");

42. break;

43. case 'E':

44. System.out.println("Embedded System, Image Processing");

45. break;

46. case 'M':

47. System.out.println("Production Technology, Thermal Engineering");

48. break;

49. }

50. break;

51. }

52. }

53. }

Output:

Data Communication and Networks, MultiMedia

Java Enum in Switch Statement


Java allows us to use enum in switch statement. Java enum is a class that represent the group of
constants. (immutable such as final variables). We use the keyword enum and put the constants
in curly braces separated by comma.

Example:
JavaSwitchEnumExample.java

1. //Java Program to demonstrate the use of Enum

2. //in switch statement

3. public class JavaSwitchEnumExample {

4. public enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat }

5. public static void main(String args[]){

6. Day[] DayNow = Day.values();

7. for (Day Now : DayNow){

8. switch (Now){

9. case Sun:

10. System.out.println("Sunday");

11. break;

12. case Mon:

13. System.out.println("Monday");

14. break;

15. case Tue:

16. System.out.println("Tuesday");

17. break;

18. case Wed:

19. System.out.println("Wednesday");

20. break;

21. case Thu:

22. System.out.println("Thursday");

23. break;
24. case Fri:

25. System.out.println("Friday");

26. break;

27. case Sat:

28. System.out.println("Saturday");

29. break;

30. }

31. }

32. }

33. }

Output:

Sunday

Monday

Twesday

Wednesday

Thursday

Friday

Saturday

Java Wrapper in Switch Statement


Java allows us to use four wrapper classes: Byte, Short, Integer and Long in switch statement.

Example:

WrapperInSwitchCaseExample.java

1. //Java Program to demonstrate the use of Wrapper class


2. //in switch statement

3. public class WrapperInSwitchCaseExample {

4. public static void main(String args[]){

5. Integer age = 18;

6. switch (age){

7. case (16):

8. System.out.println("You are under 18.");

9. break;

10. case (18):

11. System.out.println("You are eligible for vote.");

12. break;

13. case (65):

14. System.out.println("You are senior citizen.");

15. break;

16. default:

17. System.out.println("Please give the valid age.");

18. break;

19. }

20. }

21. }

Output:

You are eligible for vote.

You might also like