×

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like Byte, Short, Int, and Long are all supported in a switch statement.

Starting with Java 7, you can now use strings in switch statements. In other words, the switch statement compares variables for equality with different sets of values. Remarks A switch expression can contain 1 or N case values. A case value can only be of the switch expression type. Case values must be either literals or constants. He doesn't allow factors. A unique case value is required. A compile-time error occurs if there are duplicate values.

Java switch expressions must use byte, short, int, long (including wrapper types), enums, and strings. An optional break statement can accompany each case statement. After the switch expression, the control jumps when the break statement is reached. If there is no break statement, the following cases are executed: Optionally, you can assign standard designations to case 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;  
}   
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");  
    }  
}  
}

Output:

20

Finding Month Example:

//Java Program to demonstrate the example of Switch statement  
//where we are printing month name for the given number  
public class SwitchMonthExample {    
public static void main(String[] args) {    
    int month=7;    
    String monthString="";  
    switch(month){    
    case 1: monthString="1 - January";  
    break;    
    case 2: monthString="2 - February";  
    break;    
    case 3: monthString="3 - March";  
    break;    
    case 4: monthString="4 - April";  
    break;    
    case 5: monthString="5 - May";  
    break;    
    case 6: monthString="6 - June";  
    break;    
    case 7: monthString="7 - July";  
    break;    
    case 8: monthString="8 - August";  
    break;    
    case 9: monthString="9 - September";  
    break;    
    case 10: monthString="10 - October";  
    break;    
    case 11: monthString="11 - November";  
    break;    
    case 12: monthString="12 - December";  
    break;    
    default:System.out.println("Invalid Month!");       }
    //Printing month of the given number  
    System.out.println(monthString);  }  }

Output:

1 January

Program to check Vowels or Consonants: 

public class SwitchVowelExample {    
public static void main(String[] args) {    
    char ch='O';    
    switch(ch)  
    {  
        case 'a':   
            System.out.println("Vowel");  
            break;  
        case 'e':   
            System.out.println("Vowel");  
            break;  
        case 'i':   
            System.out.println("Vowel");  
            break;  
        case 'o':   
            System.out.println("Vowel");  
            break;  
        case 'u':   
            System.out.println("Vowel");  
            break;  
  case 'A':   
            System.out.println("Vowel");  
            break;  
        case 'E':   
            System.out.println("Vowel");  
            break;
        case 'I':   
            System.out.println("Vowel");  
            break;  
        case 'O':   
            System.out.println("Vowel");  
            break;  
        case 'U':   
            System.out.println("Vowel");  
            break;  
        default:   
            System.out.println("Consonant");  
    }  
}    
}

Output:

Vowel

Enum can be used in a switch statement in Java. The Java enum class represents the constants group. Change less like the last factors).The constants are separated by a comma and enclosed in curly braces by the keyword enum.

/Java Program to demonstrate the use of Enum  
public class JavaSwitchEnumExample {      
       public enum Day {  Sun, Mon, Tue, Wed, Thu, Fri, Sat  }    
       public static void main(String args[])     {
         Day[] DayNow = Day.values();    
           for (Day Now : DayNow)    
{
switch (Now)    
                {    
                    case Sun:    
                        System.out.println("Sunday");    
                        break;    
                    case Mon:    
                        System.out.println("Monday");    
                        break;    
                    case Tue:    
                        System.out.println("Tuesday");    
                        break;         
                    case Wed:    
                        System.out.println("Wednesday");    
                        break;    
                    case Thu:    
                        System.out.println("Thursday");    
                        break;    
                    case Fri:    
                        System.out.println("Friday");    
                        break;    
                    case Sat:    
                        System.out.println("Saturday");    
                        break;    
                }    
            }    
        }    
}    

Output:

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

In this Switch case study, we created an enumeration of the days of the week representing all days. For example, use a loop to iterate over each enum instance. Additionally, strings have been supported in the Switch case since Java7. Similarly, using Java, you can cast an enum to a string.

I used an Enum in Java in the circle collection to create a switch-case declaration. This switches the current enum instance, and each CASE statement is its enum instance. DAY.MONDAY or DAY.TUESDAY. Since we declared the Enum in the same class, we can use the instance without using the class name, like "Monday".

Enumerations are unique data types in Java that are generally collections (sets) of constants. More specifically, Java enums are a unique kind of Java class. Enums can contain constants, methods, etc. The enum keyword can be used in if statements, switch statements, iterations, etc

By default, enum constants are public, static, and final. Enum constants are accessed using dot syntax. In addition to constants, enum classes can also have attributes and methods. You cannot create objects of enum classes or extend other classes. Enum classes can only implement interfaces.


Related Topics

Java LDAP Authentication

WHAT IS LDAP? Clients can communicate with directory services by sending requests and receiving responses using the Lightweight Directory Access Protocol (LDAP). The term "LDAP server" refers to a directory service...

7 minutes read.

How to Set Environment Variables for Java

Introduction Java is an object-oriented programming language that is based on classes and can be employed mostly to develop web and desktop applications. No matter the computer architecture, Java applications are...

7 minutes read.

Diffie Hellman Algorithm in Java

In this section, you will be acknowledged about Diffie Hellman algorithm clearly step wise along with an example and also an example program. Diffie Hellman Algorithm One of the most significant algorithms...

3 minutes read.

Exception Handling in Java

Before looking at how exceptions are handled in java, it is necessary to see what an exception is. What is Exception? Whenever a program is written, errors are encountered. Some of these...

6 minutes read.

Difference between print() and println() in Java

In this tutorial, we will discuss the differences between print and println in Java language. There are mainly two methods to display the text on the console printprintln The above two methods are...

4 minutes read.

Java StringBuffer vs StringBuilder

Java StringBuffer vs StringBuilder StringBuffer The StringBuffer class is used to create mutable string. StringBuffer shows writable and growable character sequences. Java StringBuffer program FileName: StringBufferExample.java // A basic program that demonstrates the working...

2 minutes read.

How to calculate time difference in Java

In this tutorial, we learned about how to calculate time differences in java language and which methods use to find the difference and its example. Prerequisite To understand this example, you need...

5 minutes read.

Generic queue in Java

Before understanding how to implement a generic queue in java, one must know about generics and queue in java. Generics in Java Generics are parameterized types. The goal is to enable type...

6 minutes read.

Sorting a String in Java

Sorting a String in Java Sorting is a process of arranging available data objects in a meaningful format that is ascending or descending order. Sorting a string or array of String...

4 minutes read.

The final Keyword in Java

The final keyword is employed in several instances. Firstly, the non-access modifier final only applies to variables, methods, and classes. The final can be used in the following situations. Final Variables When...

6 minutes read.

Iterate JSON array in Java

This article is going to equip the knowledge about what JSON array is and how it works and also how is it distinct with the generic array. Json Array Ordered lists of...

4 minutes read.

How to check Date Null in Java?

In this section, we will be acknowledged about Date Null in Java. The date null in Java is an entity that is used when there is no specified value for...

3 minutes read.

How to Create a Package in Java?

For the most part, how to create a package in Java generally, a package is defined as a collection of relevant or irrelevant items together in a very major way....

7 minutes read.

Permutation Coefficient in Java

In this tutorial, we will get familiar with the permutation coefficient in Java.  We will understand it through examples and see different approaches to solving the problem. A permutation is a...

5 minutes read.

Java Break Keyword

Break: The word Break is a keyword or a statement in a java programming language.This Keyword break is used to stop the execution of the loop or switch statements etc.The loop...

3 minutes read.

Java Pop

The array, linked list, stack, queue, and other data structures are supported by Java programming. The insertion, deletion, and element searching operations are available for every data structure. And Java...

4 minutes read.

Difference Between Java and PHP

The two most used programming languages are PHP and Java. Both of them have a lot of similarities and distinctions. Let's first grasp each of them individually before examining their...

3 minutes read.

Java Get Time in UTC

UTC is the abbreviation for Universal Time Coordinated. Before the beginning of UTC, it is mentioned as the Greenwich Mean Time (GMT) but Now it is mentioned as the universal...

4 minutes read.

Check whether Java is installed or not

As we know that there are various operating systems, to check whether Java is installed or not in Windows and Mac we use the following ways.           Windows Operating System: There are several...

2 minutes read.

Types of JDBC Drivers

JDBC Drivers: A piece of software known as JDBC Driver permits database communication between Java applications and the server. In order to communicate with our database server, JDBC drivers put into practice...

4 minutes read.