Enum and Annotation

Java 10 min min read Updated: Mar 31, 2026 Intermediate
Enum and Annotation
Intermediate Topic 24 of 25

Enum and Annotation

In Java, enum and annotation are two important language features that help developers write cleaner, safer, and more expressive code. Enums are used to represent a fixed set of constants, while annotations are used to provide metadata about classes, methods, variables, and other program elements.

Both features were added to make Java programming more structured and powerful. Enums reduce errors caused by invalid constant values, and annotations help frameworks, tools, and compilers understand additional information about the code.

Key Concept: Enum is used for a fixed set of named constants, and annotation is used to provide metadata or special instructions about Java code.

What is Enum in Java?

Enum stands for enumeration. It is a special data type used to represent a fixed set of constants.

For example:

  • days of the week
  • months of the year
  • directions like NORTH, SOUTH, EAST, WEST
  • order status like PENDING, SHIPPED, DELIVERED

Instead of using plain strings or integers, Java enums provide type safety and clarity.

Why Enum is Needed

Before enums, programmers often used integer constants or strings to represent fixed values.

Without Enum

java String status = "DELIVERED";

The problem here is that anyone could accidentally write:

java String status = "DELIVRED"; // typo

This kind of mistake may not be caught easily.

Enum solves this by restricting values to a fixed set.

Basic Enum Syntax

An enum is declared using the enum keyword.

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

Here, Day is an enum type and each item is a constant.

Using Enum in Java

java enum Day { MONDAY, TUESDAY, WEDNESDAY } public class Main { public static void main(String[] args) { Day today = Day.MONDAY; System.out.println(today); } }

Output

text MONDAY

Here, today can only hold one of the constants defined in the Day enum.

Enum Improves Type Safety

Since enums are types, invalid values cannot be assigned to them.

java Day today = Day.MONDAY; // Valid // Day today = "MONDAY"; // Invalid

This prevents many common programming mistakes.

Enum Inside a Class and Outside a Class

Enums can be declared:

  • outside a class
  • inside a class

Enum Outside Class

java enum Color { RED, GREEN, BLUE }

Enum Inside Class

java class Test { enum Color { RED, GREEN, BLUE } }

Enum with Switch Statement

Enums are commonly used with switch.

java enum Day { MONDAY, TUESDAY, WEDNESDAY } public class Main { public static void main(String[] args) { Day today = Day.TUESDAY; switch (today) { case MONDAY: System.out.println("Start of week"); break; case TUESDAY: System.out.println("Second day"); break; case WEDNESDAY: System.out.println("Mid week"); break; } } }

Enum Methods

Java provides some built-in methods for enums.

  • values()
  • ordinal()
  • valueOf()
  • name()

1. values()

Returns all enum constants as an array.

java enum Day { MONDAY, TUESDAY, WEDNESDAY } public class Main { public static void main(String[] args) { for (Day d : Day.values()) { System.out.println(d); } } }

2. ordinal()

Returns the position of the enum constant starting from 0.

java System.out.println(Day.MONDAY.ordinal()); // 0 System.out.println(Day.TUESDAY.ordinal()); // 1

3. valueOf()

Converts a string into the corresponding enum constant.

java Day d = Day.valueOf("MONDAY"); System.out.println(d);

4. name()

Returns the exact name of the enum constant.

java System.out.println(Day.MONDAY.name());

Enum with Constructor and Variables

Enums in Java are more powerful than simple constants. They can have fields, constructors, and methods.

Example

java enum Level { LOW(1), MEDIUM(2), HIGH(3); private int code; Level(int code) { this.code = code; } int getCode() { return code; } } public class Main { public static void main(String[] args) { System.out.println(Level.HIGH.getCode()); } }

Output

text 3

This shows that enums can behave like full classes.

Important Rules About Enums

  • Enum constants are public, static, and final by default
  • Enum constructors are always private or package-private
  • Enums cannot extend another class
  • Enums can implement interfaces

Real-World Example of Enum

Let us take an order tracking example.

java enum OrderStatus { PLACED, SHIPPED, DELIVERED, CANCELLED } class Order { OrderStatus status; } public class Main { public static void main(String[] args) { Order order = new Order(); order.status = OrderStatus.SHIPPED; System.out.println(order.status); } }

This is much safer and cleaner than using plain strings for order status.

What is Annotation in Java?

An annotation is a special form of metadata that provides additional information about Java code. Annotations do not directly change the logic of the program, but they are used by:

  • the compiler
  • the JVM
  • frameworks and tools

Annotations start with the @ symbol.

Examples:

  • @Override
  • @Deprecated
  • @SuppressWarnings

Why Annotations are Needed

Annotations make code more informative and help tools or frameworks apply special behavior automatically.

  • tell compiler about special instructions
  • mark old APIs as deprecated
  • reduce XML/configuration in frameworks
  • support code generation and processing

Built-in Annotations in Java

Java provides some commonly used built-in annotations:

  • @Override
  • @Deprecated
  • @SuppressWarnings
  • @FunctionalInterface

1. @Override

This annotation tells the compiler that a method is meant to override a method from the parent class.

Example

java class Animal { void sound() { System.out.println("Animal sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Dog barks"); } }

If the method signature is wrong, the compiler will show an error. This helps prevent mistakes.

2. @Deprecated

This annotation marks a method or class as outdated and not recommended for use.

Example

java class Demo { @Deprecated void oldMethod() { System.out.println("Old method"); } }

Using this method may show a compiler warning.

3. @SuppressWarnings

This annotation tells the compiler to ignore specific warnings.

Example

java @SuppressWarnings("unchecked") public class Demo { public static void main(String[] args) { } }

4. @FunctionalInterface

This annotation is used with interfaces that are intended to have exactly one abstract method.

Example

java @FunctionalInterface interface MyInterface { void show(); }

If another abstract method is added, the compiler shows an error.

Custom Annotation

Java also allows programmers to create their own annotations.

Syntax

java @interface MyAnnotation { }

Example

java @interface Author { String name(); } @Author(name = "Amit") class Book { }

Here, @Author is a custom annotation with one element called name.

Annotation Elements

An annotation can have elements that look similar to methods.

java @interface Info { String author(); int version(); }

Usage:

java @Info(author = "Amit", version = 1) class Demo { }

Meta-Annotations

Meta-annotations are annotations used on annotations. They define how custom annotations behave.

Common meta-annotations:

  • @Target
  • @Retention
  • @Documented
  • @Inherited

@Target

Specifies where the annotation can be applied.

Example

java import java.lang.annotation.ElementType; import java.lang.annotation.Target; @Target(ElementType.TYPE) @interface MyAnnotation { }

This means the annotation can be applied only to classes, interfaces, or enums.

@Retention

Specifies how long the annotation should be retained.

  • SOURCE
  • CLASS
  • RUNTIME

Example

java import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation { }

This means the annotation is available at runtime, often used with reflection.

Annotation and Reflection

Annotations become very powerful when combined with Reflection API. A program can inspect annotations at runtime and behave accordingly.

This is how many Java frameworks work internally.

Simple Reflection-Based Annotation Example

java import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) @interface Author { String name(); } @Author(name = "Amit") class Book { } public class Main { public static void main(String[] args) { Author a = Book.class.getAnnotation(Author.class); System.out.println(a.name()); } }

Enum vs Annotation

Point Enum Annotation
Purpose Represents fixed constants Provides metadata
Keyword enum @interface
Used for Status, levels, directions, constants Compiler hints, framework configuration, metadata
Runtime behavior Actual type with constants Extra information for tools/JVM/frameworks

Common Mistakes

  • Using strings instead of enum where fixed values are expected
  • Assuming enum is only a list of constants and cannot have methods
  • Thinking annotations directly change logic like methods do
  • Using the wrong retention policy in custom annotations
  • Confusing annotation syntax with method calls

Best Practices

  • Use enum for fixed sets of values
  • Use meaningful names for enum constants, usually uppercase
  • Use built-in annotations properly to improve code safety
  • Create custom annotations only when there is a clear use case
  • Use runtime retention only when annotation access is needed during execution

Interview-Oriented Points

  • Enum is used for fixed sets of constants
  • Enum constants are public, static, and final by default
  • Enums can have constructors, methods, and fields
  • Annotations provide metadata about code
  • @Override checks correct method overriding
  • @Deprecated marks old code
  • @Retention and @Target are meta-annotations
  • Annotations are heavily used in frameworks like Spring and Hibernate

Conclusion

Enum and annotation are two powerful Java features that improve code clarity, safety, and maintainability. Enums make fixed-value programming cleaner and type-safe, while annotations make code more descriptive and framework-friendly.

Once you understand enums and annotations properly, you can write more expressive Java code and also better understand how modern Java frameworks and tools work internally.

Quick Summary: Enum represents a fixed set of constants, while annotation provides metadata that helps the compiler, JVM, and frameworks understand special information about code.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators