Annotations

Thinking

Imagine being able to add metadata to your code that informs the compiler or frameworks how to behave—without affecting business logic. That's the power of annotations in Java. They provide a clean and declarative way to inject behaviors or configurations.

Whether you're suppressing warnings, marking methods for override, or configuring frameworks like Spring, annotations act as powerful tools for modern development.

Description

Annotations in Java are metadata that provide information to the compiler, runtime, or development tools. They do not directly influence program logic but can be used by frameworks or compilers to generate code, enforce rules, or apply configurations.

  • Annotations begin with @ symbol.
  • They can be applied to classes, methods, fields, parameters, and more.
  • They are processed by tools and frameworks during compilation or at runtime using reflection.
Note:

Annotations are heavily used in frameworks like Spring, JUnit, and Hibernate to reduce boilerplate and configure behaviors declaratively.

Video Resources

Java Annotations Tutorial

A beginner-friendly guide to built-in and custom annotations in Java.

Examples (code)

Using Built-in Annotations


class Parent {
    void display() {
        System.out.println("Parent display");
    }
}

class Child extends Parent {
    @Override
    void display() {
        System.out.println("Child display");
    }
}
  

Creating a Custom Annotation


import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation {
    String value();
}

public class Demo {
    @MyAnnotation(value = "Custom Message")
    public void show() {
        System.out.println("Annotated method");
    }
}
  

Real-World Applications

Framework Configuration

Used in frameworks like Spring for dependency injection, transaction management, and more.

Unit Testing

JUnit uses annotations like @Test and @BeforeEach to define test cases and setup methods.

Security

Security configurations in frameworks often use annotations to declare access control and roles.

Interview Questions

Q1: What are annotations in Java?

Show Answer

Annotations are metadata in Java used to provide additional information to the compiler or runtime about the code. They do not alter the program logic directly.

Q2: What is the difference between @Override and @Deprecated annotations?

Show Answer

@Override indicates that a method is overriding a superclass method. @Deprecated marks the method as outdated and discourages its usage.

Q3: How can you create a custom annotation?

Show Answer

You define it using @interface, and specify @Target and @Retention policies to control where and how it can be used.