×

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

Heap Sort in Java

Heap Sort in JavaHeap sort in Java uses the data structure binary heap, min-heap, or max heap to do the sorting of elements. Since min-heap always gives the minimum element first,...

8 minutes read.

Cyclic Barrier in Java

Programmers often find it challenging to run multiple threads simultaneously. Java introduces the idea of concurrency, which enables us to run many threads concurrently, making this work simpler. Concurrent programming...

6 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

Counting sort in Java

An array's elements are sorted using the counting sort method, which counts how many times each distinct element appears in the array. The count is kept in an auxiliary array,...

3 minutes read.

Java If Keyword

Definition: The if statement specifies a section of Java code that will run if an if statement's condition is false. The following conditional statements can be used in Java: To provide a block...

3 minutes read.

How to Convert String to double in Java

How to Convert String to double in java It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from...

3 minutes read.

Packages in Java

Packages in Java can be defined as an assortment for grouping various classes and interfaces based on their performance. It is a catalog for holding various java files. They provide...

4 minutes read.

Methods in Java

The Methods in Java are the collection of statements that are executed when the method is called. By using the methods, the complexity of writing the code decreases. The method consists...

4 minutes read.

Java Boolean toString() Method

The toString() method of Java Boolean class returns a String corresponding to this Boolean object. It returns a string value “true”, if the defined object is true else it returns...

2 minutes read.

How to run Java Program in Eclipse

How to run Java Program in Eclipse In this section, we will learn how to write, save, compile, and execute or run a Java program in Eclipse. Eclipse is one of...

2 minutes read.

How to get the current date and time in Java

Introduction: In this article, we are going to discover many processes for Getting the existing-day Date and Time in Java. Most programs require timestamping events or showing date/times, among many...

3 minutes read.

How to use scanner in Java

Scanner class in Java is the part of java.util package. Java programming language has various ways to read input from the user, Scanner class is one of the classes to...

5 minutes read.

Awesome explanation of Strings in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Bounded buffer problem in Java

The Bounded buffer Problem can also be called a Producer consumer problem. The problem covers two processes—the producer and the consumer—that share a single, fixed-size buffer that serves as a...

4 minutes read.

How to Convert Integer to String in Java

How to Convert int to String in Java It is used when you want to convert an integer to String. You can convert int to String by using the following methods: Using...

3 minutes read.

Set Up the Environment in Java

The Java is regarded as the pure object-oriented programming language. The Java applications are first compiled into the byte-code and then run by using the JVM. The Java is the...

4 minutes read.

Java Thread Priority in Multithreading

As we realise, java, being object-situated, works inside a multithreading climate in which the string scheduler relegates the processor to a string in light of the need for a string....

6 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.

Print Pencil Shape Pattern in Java

Another pattern made from asterisk symbols that use loops and other logical concepts is the pencil pattern. It is usually requested to draw a pattern using a program. To write the...

6 minutes read.

Java AWT

Java AWT Java programming is used to develop different types of applications like window-based applications, web applications, Enterprise applications, or mobile applications. For creating standalone applications, Java AWT API is used....

11 minutes read.