Enum And Annotations

Let’s explore two very powerful features in Java that often go underutilized by beginners but are essential in enterprise Java, frameworks like Spring, and clean design:
βœ… Enums (Enumerations)
βœ… Annotations


πŸ”’ Java Enums (Enumerations)


πŸ” What is an Enum?

An enum is a special class that represents a group of constant values.
Instead of writing:

int MONDAY = 1;

You write:

enum Day { MONDAY, TUESDAY, ... }

This adds type safety, readability, and lets you bundle logic with constants.


βœ… Why Use It?

  • Enforces fixed set of values
  • Avoids errors with invalid values (type-safe!)
  • Allows behavior like a class (can have fields, methods, constructors!)
  • Great for state machines, commands, config, etc.
  • Used heavily in Spring Boot, JPA, and REST APIs

πŸ“¦ Basic Enum Example

public enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY;
}

public class TestEnum {
    public static void main(String[] args) {
        Day today = Day.MONDAY;

        switch (today) {
            case MONDAY:
                System.out.println("Start of the week");
                break;
            case FRIDAY:
                System.out.println("Weekend loading...");
                break;
        }
    }
}

πŸš€ Enum with Fields & Methods

public enum Status {
    SUCCESS(200), ERROR(500);

    private final int code;

    Status(int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }
}

public class Test {
    public static void main(String[] args) {
        System.out.println(Status.SUCCESS.getCode()); // 200
    }
}

You can even override methods per enum constant if needed.


🎯 Enterprise Use-Cases

  • REST API: map enum to HTTP status or JSON value
  • JPA: map enum fields to DB columns
  • State Machines: manage state transitions (ORDER_STATUS)
  • Avoid String or int constants everywhere

🧷 Java Annotations


πŸ” What is an Annotation?

An annotation is metadata that provides information about your code.
It does not change logic but gives instructions to:

  • Compiler
  • Frameworks (e.g., Spring, Hibernate)
  • Tools (e.g., Lombok, Swagger)

Think of it like tagging a method or class with a special label.


βœ… Why Use It?

  • Reduces boilerplate
  • Declarative programming
  • Drives frameworks like Spring, JUnit, JPA
  • Helps with validation, logging, DI, etc.
  • Build cleaner, more readable code

πŸ“¦ Built-in Annotations

AnnotationUse-case
@OverrideEnsures you’re overriding a method
@DeprecatedMarks something as outdated
@SuppressWarningsSuppresses compiler warnings
@FunctionalInterfaceEnforces one-method functional interface

Example:

@Override
public String toString() {
    return "MyObject";
}

βš™οΈ Custom Annotation

You can define your own annotation too:

@interface MyAnnotation {
    String value();
    int priority() default 1;
}

Use it like this:

@MyAnnotation(value = "Test case", priority = 3)
public void run() {}

🎯 Real World: Framework Annotations

AnnotationWhere it’s usedPurpose
@Controller, @Service, @RepositorySpringDependency Injection
@RequestMapping, @GetMappingSpring MVCWeb routing
@Entity, @Table, @ColumnHibernate/JPAORM mappings
@TestJUnitUnit testing
@AutowiredSpringInject dependencies

These drive almost everything in enterprise Spring applications.


πŸ›  Custom Annotation + Reflection Use-Case (Advanced)

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface LogExecutionTime {}

public class Demo {
    @LogExecutionTime
    public void serve() {
        System.out.println("Serving...");
    }
}

You can later scan methods using Reflection API and add custom behavior.


🧠 Summary

FeatureEnumAnnotation
PurposeType-safe constant groupingMetadata, behavior-driven development
UsageAPI status, state, configFramework config, lifecycle, testing
ExtendsCan have methods, fieldsCannot have behavior; just metadata
Real-WorldHTTP codes, Roles, DaysSpring, JPA, Logging, JUnit

🏠 Homework

1. Create an enum named Role with constants: ADMIN, USER, GUEST.

  • Add a method getPermissionLevel() that returns int values for each role.

2. Create a custom annotation @Info with fields: author and version.

  • Apply it on a class and print its values using reflection.

3. Use built-in annotations:

  • Use @Override on a method
  • Use @Deprecated on an old method and call it

Would you like to move onto Object Class Methods (equals, hashCode, toString), or go into Wrapper Classes, Generics, or even Lambdas & Streams next?