Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Java Enums


Java Enums

In Java, an enum (enumeration) is a special type that defines a set of constants. Enums are used to represent fixed sets of values, such as days of the week, months, status codes, etc. Enum constants are implicitly public, static, and final. They are typically used when a variable can only take one of a few predefined values. Here's an overview of Java enums:

Declaring Enums:

Example of declaring an enum:

        public enum Day {
            MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
        }
     

Using Enums:

Example of using enums:

        public class Main {
            public static void main(String[] args) {
                Day today = Day.MONDAY;
                System.out.println("Today is " + today); // Output: Today is MONDAY
                
                // Enums can be used in switch statements
                switch (today) {
                    case MONDAY:
                        System.out.println("It's the first day of the week");
                        break;
                    case FRIDAY:
                        System.out.println("It's almost the weekend");
                        break;
                    default:
                        System.out.println("Just another day");
                }
            }
        }
     

Enum Constructors and Methods:

Example of enums with constructors and methods:


        public enum Day {
            MONDAY("Monday"), TUESDAY("Tuesday"), WEDNESDAY("Wednesday"),
            THURSDAY("Thursday"), FRIDAY("Friday"), SATURDAY("Saturday"), SUNDAY("Sunday");
            
            private final String displayName;
            
            private Day(String displayName) {
                this.displayName = displayName;
            }
            
            public String getDisplayName() {
                return displayName;
            }
        }
        
        public class Main {
            public static void main(String[] args) {
                Day today = Day.MONDAY;
                System.out.println("Today is " + today.getDisplayName()); // Output: Today is Monday
            }
        }
     

Benefits of Enums:



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java