Java
Module 25: Enums & AnnotationsBeginner22 min read

Java Enums & Custom Annotations

Build rich Enums with constructors/methods and create custom runtime Annotations using @Retention and @Target.

Key Takeaways & Core Concepts
  • Built-in: @Override (compile-time check), @Deprecated, @SuppressWarnings, @FunctionalInterface.
  • Meta-Annotations: * @Target(ElementType.METHOD): Restricts where the annotation can be placed.

Enums in Java

Unlike C/C++ where enums are just named integers, every Java enum is a full-fledged class that implicitly extends java.lang.Enum.

  • Enum constants are public static final singleton instances created once when the enum class loads.
  • Enums can declare private final fields, private constructors, and abstract/concrete methods—making them ideal for type-safe Singletons and state machines.
  • Use `EnumSet` and `EnumMap` for enum collections: they are backed by compact bit-vectors and arrays, making them dramatically faster than HashSet/HashMap.
Enum with Fields & Custom Annotation
1import java.lang.annotation.*;
2
3@Retention(RetentionPolicy.RUNTIME)
4@Target(ElementType.METHOD)
5@interface ApiEndpoint { String path(); }
6
7enum HttpStatus {
8 OK(200), NOT_FOUND(404), SERVER_ERROR(500);
9 private final int code;
10 HttpStatus(int code) { this.code = code; }
11 public int getCode() { return code; }
12}
13
14public class Main {
15 @ApiEndpoint(path = "/api/v1/java")
16 public static void handler() {}
17
18 public static void main(String[] args) throws Exception {
19 for (HttpStatus s : HttpStatus.values()) {
20 System.out.println(s + " -> " + s.getCode());
21 }
22 ApiEndpoint ann = Main.class.getMethod("handler").getAnnotation(ApiEndpoint.class);
23 System.out.println("Annotated Path: " + ann.path());
24 }
25}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
25 lines
Note: `RetentionPolicy.RUNTIME` keeps the annotation metadata in the `.class` file so it can be read at runtime.

Annotations & Meta-Annotations

Annotations attach structured metadata to classes, methods, fields, and parameters:

  • Built-in: @Override (compile-time check), @Deprecated, @SuppressWarnings, @FunctionalInterface.
  • Meta-Annotations:
  • @Target(ElementType.METHOD): Restricts where the annotation can be placed.
  • @Retention(RetentionPolicy.RUNTIME): Preserves metadata in bytecode so frameworks (Spring, JUnit, Jackson) can read it via Reflection.
Practice & AssessmentJava Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)