Which of the following could be a reason to use a switch statement in a java program?


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.

Syntax

The syntax of enhanced for loop is −

switch(expression) {
   case value :
      // Statements
      break; // optional
   
   case value :
      // Statements
      break; // optional
   
   // You can have any number of case statements.
   default : // Optional
      // Statements
}

The following rules apply to a switch statement −

  • The variable used in a switch statement can only be integers, convertable integers (byte, short, char), strings and enums.

  • You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.

  • The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal.

  • When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.

  • When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.

  • Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.

  • A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

Flow Diagram

Which of the following could be a reason to use a switch statement in a java program?

Example

public class Test {

   public static void main(String args[]) {
      // char grade = args[0].charAt(0);
      char grade = 'C';

      switch(grade) {
         case 'A' :
            System.out.println("Excellent!"); 
            break;
         case 'B' :
         case 'C' :
            System.out.println("Well done");
            break;
         case 'D' :
            System.out.println("You passed");
         case 'F' :
            System.out.println("Better try again");
            break;
         default :
            System.out.println("Invalid grade");
      }
      System.out.println("Your grade is " + grade);
   }
}

Compile and run the above program using various command line arguments. This will produce the following result −

Output

Well done
Your grade is C

java_decision_making

Java programming language has conditional and control statements which optimizes the logic while writing a program. Hustle free logic building using the switch case results in improved efficiency. Using a switch case in java optimizes the readability of the code while working on multiple test expressions. In this article, you will learn about switch case in java with various examples. Following are the topics discussed in this article:

  • What is a Switch Case In Java?
  • Rules To Remember
  • Flow Chart
  • Examples
  1. Break Statement In Switch Case

2. Nested Switch Case

3. Fall-Through Switch Case

4. Enum In Switch Case

5. String In Switch Case

What Is A Switch Case In Java?

Java switch statement is like a conditional statement which tests multiple values and gives one output. These multiple values that are tested are called cases. It is like a multi-branch statement. After the release of java 7 we can even use strings in the cases. Following is the syntax of using a switch case in Java.

switch(expression)
{
case value:
//statement
break;
case value n :
//statement
break;
default:
//statement
}

Rules To Remember

There are a certain rules one must keep in mind while declaring a switch case in java. Following are a certain points to remember while writing a switch case in java.

  1. We cannot declare duplicate values in a switch case.
  2. The values in the case and the data type of the variable in a switch case must be same.
  3. Variables are not allowed in a case, it must be a constant or a literal.
  4. The break statement fulfills the purpose of terminating the sequence during execution.
  5. It is not necessary to include the break statement, the execution will move to the next statement if the break statement is missing.
  6. The default statement is optional as well, it can appear anywhere in the block.

Flow Chart

Examples

Break Statement In Switch Case

Break statement is used to control the flow of the execution, as soon as the expression is satisfied the execution moves out the switch case block.

public class Example{
public static void main(String args[]){
int month= 7;

switch(month){
case 1 :
System.out.println("january");
break;
case 2:
System.out.println("february");
break;
case 3:
System.out.println("march");
break;
case 4:
System.out.println("april");
break;
case 5:
System.out.println("may");
break;
case 6:
System.out.println("june");
break;
case 7:
System.out.println("july");
break;
case 8:
System.out.println("august");
break;
case 9:
System.out.println("september");
break;
case 10:
System.out.println("October");
break;
case 11:
System.out.println("november");
break;
case 12:
System.out.println("december");
break;
default:
System.out.println("not valid");
}
}
}

Output: july

Nested Switch Case

Nested switch case incorporates another switch case in an existing switch case. Following is an example showing a nested switch case.

public class Example{
public static void main(String args[]){
int tech = 2;
int course = 2;

switch(tech){
case 1:
System.out.println("python");
break;
case 2:
switch(course){
case 1:
System.out.println("J2EE");
break;
case 2:
System.out.println("advance java");
}
}
}
}

Output: advance java

Fall Through Switch Case

Whenever there is no break statement involved in a switch case block. All the statements are executed even if the test expression is satisfied. Following is an example of a fall through switch case.

public class Example{
public static void main( String args[])
{
int courses = 2;

switch(courses){
case 1:
System.out.println("java");
case 2:
System.out.println("python");
case 3:
System.out.println("Devops");
case 4:
System.out.println("Automation testing");
case 5:
System.out.println("Hadoop");
case 6:
System.out.println("AWS");
default:
System.out.println("check out edureka.co for more");
}
}
}

Output: java
python
Devops
Automation testing
Hadoop
AWS
check out edureka.co for more

Enum In Switch Case

Switch case allows enum as well. Enum is basically a list of named constants. Following is an example of the use of enum in a switch case.

public class Example{
public enum day { s , m , t , w , th, fr, sa };
public static void main(String args[]){
course[] c = day.values();
for(day today : c)
{
switch (today){
case s :
System.out.println("Sunday");
break;
case m:
System.out.println("Monday");
break;
case t:
System.out.println("Tuesday");
break;
case w:
System.out.println("Wednesday");
break;
case th:
System.out.println("Thursday");
break;
case fr:
System.out.println("Friday");
break;
case sa:
System.out.println("Saturday");
break;
}
}
}
}
Output: Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

String In Switch Case

After the release of Java 7, a switch case can have strings as a case. Following is an example of using string as cases in a switch statement.

public class Example{
public static void main(String args[]){
String player = "batsmen";

switch(player){
case "batsmen":
System.out.println(" Batsmen are players who plays with a bat");
break;
case "bowler":
System.out.println("who throws the ball");
break;
case "wicket-keeper":
System.out.println("who keeps the ball behind the wickets");
break;
case "fielder":
System.out.println("who fields in the ground");
break;
default:
System.out.println("no entry present");
}
}
}

Output: Batsmen are players who play with a bat

In this article, we have discussed how we can use switch case in java with various examples. With the use of conditional statements it becomes easier to test multiple conditions at once and also generate an optimized solution of rather difficult problem. If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series that will explain the various other aspects of Java.

1. Object Oriented Programming

2. Inheritance in Java

3. Polymorphism in Java

4. Abstraction in Java

5. Java String

6. Java Array

7. Java Collections

8. Java Threads

9. Introduction to Java Servlets

10. Servlet and JSP Tutorial

11. Exception Handling in Java

12. Advanced Java Tutorial

13. Java Interview Questions

14. Java Programs

15. Kotlin vs Java

16. Dependency Injection Using Spring Boot

17. Comparable in Java

18. Top 10 Java frameworks

19. Java Reflection API

20. Top 30 Patterns in Java

21. Core Java Cheat Sheet

22. Socket Programming In Java

23. Java OOP Cheat Sheet

24. Annotations in Java

25. Library Management System Project in Java

26. Trees in Java

27. Machine Learning in Java

28. Top Data Structures & Algorithms in Java

29. Java Developer Skills

30. Top 55 Servlet Interview Questions

31. Top Java Projects

32. Java Strings Cheat Sheet

33. Nested Class in Java

34. Java Collections Interview Questions and Answers

35. How to Handle Deadlock in Java?

36. Top 50 Java Collections Interview Questions You Need to Know

37. What is the concept of String Pool in Java?

38. What is the difference between C, C++, and Java?

39. Palindrome in Java- How to check a number or string?

40. Top MVC Interview Questions and Answers You Need to Know

41. Top 10 Applications of Java Programming Language

42. Deadlock in Java

43. Square and Square Root in Java

44. Typecasting in Java

45. Operators in Java and its Types

46. Destructor in Java

47. Binary Search in Java

48. MVC Architecture in Java

49. Hibernate Interview Questions And Answers