Java Annotations: Basics of @ Metadata in Java

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 233 of 306

Java annotations are labels that start with @ and attach extra information, called metadata, to classes, methods, fields, parameters and other parts of your code. An annotation does not change what the code does by itself. Instead, a tool reads it: the compiler, a build-time processor, or your program at runtime through reflection.

You have already used Java annotations in this tutorial: @Override in method overriding, @FunctionalInterface with lambdas, and @Entity and @Id in the JPA lessons. This lesson explains how annotations work underneath: the syntax, where you can place them, who reads them, and how long they survive.


What a Java Annotation Looks Like

Every annotation is the @ sign followed by the name of an annotation type, optionally with values in parentheses.

@AnnotationName
@AnnotationName(value)
@AnnotationName(elementOne = value1, elementTwo = value2)

Start with the annotation you know best, @Override:

public class FirstAnnotation {

    static class Animal {
        String sound() {
            return "...";
        }
    }

    static class Dog extends Animal {
        @Override                 // annotation on a method
        String sound() {
            return "Woof";
        }
    }

    public static void main(String[] args) {
        Animal pet = new Dog();
        System.out.println(pet.sound());
    }
}

Output:

Woof

How it works:

  • @Override sits directly before the method it describes. By convention it goes on its own line.
  • The program prints Woof with or without the annotation. The annotation only tells the compiler, "I intend this method to override one from the parent class."
  • Annotations have no effect on how the method runs. Their value comes from whoever reads them.

Why the Compiler Reads @Override

Make a typo in the method name and the annotation catches it:

public class Typo {
    static class Animal {
        String sound() { return "..."; }
    }

    static class Cat extends Animal {
        @Override
        String sounds() {          // typo: "sounds" instead of "sound"
            return "Meow";
        }
    }
}
Typo.java:7: error: method does not override or implement a method from a supertype
        @Override
        ^
1 error

Without @Override, sounds() would compile as a brand-new method, and Cat would silently inherit "..." from Animal. The annotation turns a hidden logic bug into a compile error.


Annotation Syntax: Marker, Single-Value and Full Forms

Annotations come in three shapes, depending on how many elements (named values) they have.

FormExampleWhen it is used
Marker@Override, @DeprecatedNo values; the presence of the annotation is the information
Single value@SuppressWarnings("unchecked")One element named value, so the name can be left out
Named elements@Deprecated(since = "2.0", forRemoval = true)One or more name = value pairs
Array value@SuppressWarnings({"unchecked", "rawtypes"})An element that holds several values, written in { }
import java.util.ArrayList;
import java.util.List;

public class Forms {

    @Deprecated                                   // marker annotation: no elements
    static void oldPrint(String text) {
        System.out.println(text);
    }

    @SuppressWarnings("unchecked")                // single value
    static List<String> copy(List rawList) {
        return new ArrayList<>(rawList);
    }

    @Deprecated(since = "2.0", forRemoval = true) // named elements
    static void legacyExport() {
        System.out.println("exporting...");
    }

    @SuppressWarnings({"unchecked", "rawtypes"})  // array value
    public static void main(String[] args) {
        List raw = new ArrayList();
        raw.add("Java");
        System.out.println(copy(raw));
    }
}

Output:

[Java]

How it works:

  • @SuppressWarnings("unchecked") is short for @SuppressWarnings(value = "unchecked"). The shortcut works only when the element is named value.
  • @Deprecated and @Deprecated(since = "2.0", forRemoval = true) are the same annotation type. Its elements have default values, so you may leave them out.
  • {"unchecked", "rawtypes"} passes an array. For a single item you can drop the braces: "unchecked" and {"unchecked"} mean the same.
  • @SuppressWarnings hides only the warning names you list. copy suppresses "unchecked", so compiling with -Xlint:all still reports its raw List parameter as [rawtypes]. main lists both names, so nothing is reported there.

Note: Element values must be compile-time constants: literals, static final constants, enum values, class literals such as String.class, other annotations, or arrays of these. A method call like LocalDate.now() is not allowed.


Where You Can Place Java Annotations

Annotations can go on almost every declaration in Java. Each annotation type decides which places it allows; you will set that yourself in Java Custom Annotations.

import java.util.List;

@SuppressWarnings("unused")                          // on a class
public class Placement {

    @Deprecated                                      // on a field
    private int legacyCounter;

    @Deprecated                                      // on a constructor
    public Placement() { }

    public void greet(@SuppressWarnings("unused") String name) { // on a parameter
        @SuppressWarnings("unused")                   // on a local variable
        List<String> tags = List.of("java", "basics");
        System.out.println("Annotations do not change what this method does.");
    }

    public static void main(String[] args) {
        new Placement().greet("Asha");
    }
}

Output:

Annotations do not change what this method does.
LocationExample
Class, interface, enum, record@Entity public class Book { }
Field@Id private Long id;
Method@Override public String toString()
Constructor@Deprecated public Placement()
Parametervoid save(@NotNull String name)
Local variable@SuppressWarnings("unused") int temp = 0;
Packagein package-info.java: @Deprecated package com.gocourse.old;
Modulein module-info.java: @Deprecated module com.gocourse.legacy { }
Type use (Java 8+)List<@NonNull String> names

How it works:

  • An annotation applies to the declaration that immediately follows it. Modifiers such as public and private can come before or after it, but placing annotations first is the standard style.
  • You can stack several annotations on one declaration, each on its own line.
  • Type-use annotations attach to a use of a type rather than a declaration. They are mostly read by checking tools such as nullness checkers.

Who Reads Java Annotations?

Because annotations do nothing on their own, it helps to know who consumes them. There are three readers.

ReaderWhenExamples
The compilerDuring javac@Override causes errors, @Deprecated causes warnings, @SuppressWarnings hides warnings
Annotation processorsDuring javac, as plug-insLombok generates getters, MapStruct generates mappers, Hibernate generates metamodel classes
Your running programAt runtime, through reflectionJUnit finds @Test methods, Spring finds @Autowired fields, JPA reads @Entity and @Column

The JPA lesson used the third kind: Hibernate reads @Entity, @Id and @Column at runtime to map objects to tables. Frameworks read annotations through the Java Reflection API, and so can your own code.


Retention: How Long an Annotation Survives

Not every annotation is still there when the program runs. Each annotation type has a retention policy that decides how far it travels.

RetentionKept in .java sourceKept in .class fileVisible at runtimeExample
SOURCEYesNoNo@Override, @SuppressWarnings
CLASS (default)YesYesNoMany bytecode-tool annotations
RUNTIMEYesYesYes@Deprecated, @FunctionalInterface, JPA's @Entity

You can see the difference with reflection. getAnnotations() returns every annotation that survived until runtime:

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;

public class ReadAtRuntime {

    static class Report {
        @Override
        public String toString() {
            return "Report";
        }

        @Deprecated(since = "1.5")
        public void printOld() { }

        public void printNew() { }
    }

    public static void main(String[] args) throws NoSuchMethodException {
        for (String methodName : new String[] {"toString", "printOld", "printNew"}) {
            Method method = Report.class.getMethod(methodName);
            Annotation[] annotations = method.getAnnotations();
            System.out.println(methodName + " -> " + Arrays.toString(annotations));
        }

        Deprecated info = Report.class.getMethod("printOld").getAnnotation(Deprecated.class);
        System.out.println("since = " + info.since() + ", forRemoval = " + info.forRemoval());
    }
}

Output:

toString -> []
printOld -> [@java.lang.Deprecated(forRemoval=false, since="1.5")]
printNew -> []
since = 1.5, forRemoval = false

How it works:

  • toString() clearly has @Override in the source, yet reflection returns an empty array. @Override has SOURCE retention, so the compiler throws it away after checking it.
  • @Deprecated has RUNTIME retention, so it is stored in the .class file and reflection can see it, including the default value forRemoval=false that was never written.
  • getAnnotation(Deprecated.class) returns the annotation as an object. You call its elements like methods: info.since() and info.forRemoval().

You can confirm that the annotation lives in the bytecode with javap:

javap -v 'ReadAtRuntime$Report.class' | grep RuntimeVisibleAnnotations
  #17 = Utf8               RuntimeVisibleAnnotations
    RuntimeVisibleAnnotations:

An Annotation Type Is a Special Interface

Every annotation you use is declared somewhere with the keyword @interface. This is how the JDK declares the two annotations used above (comments removed):

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, MODULE, PARAMETER, TYPE})
public @interface Deprecated {
    String since() default "";

    boolean forRemoval() default false;
}

How it works:

  • @interface declares an annotation type. Its "methods", such as since(), are the elements you fill in when you write @Deprecated(since = "2.0").
  • default "" and default false are why @Deprecated can be used with no values.
  • @Target limits where the annotation may be placed. @Override allows only methods, which is why putting it on a field is a compile error.
  • @Retention sets the retention policy from the table above. Annotations that describe other annotations, like @Target and @Retention, are called meta-annotations. The next lesson, Java Built-in Annotations, covers each of them.

Real-World Example: An API Deprecation Report

Large codebases mark old methods with @Deprecated and plan to remove them. Because @Deprecated is kept at runtime, a short tool can scan a class and list what needs attention before the next release.

The service class being audited:

public class PaymentService {

    public String payWithUpi(double amount) {
        return "UPI payment of Rs. " + amount;
    }

    @Deprecated(since = "3.0")
    public String payWithCheque(double amount) {
        return "Cheque payment of Rs. " + amount;
    }

    @Deprecated(since = "2.4", forRemoval = true)
    public String payWithDemandDraft(double amount) {
        return "DD payment of Rs. " + amount;
    }

    public String refund(String orderId) {
        return "Refund started for " + orderId;
    }
}

The report tool:

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Comparator;

public class DeprecationReport {

    public static void main(String[] args) {
        printReport(PaymentService.class);
    }

    static void printReport(Class<?> apiClass) {
        System.out.println("API report for " + apiClass.getSimpleName());
        System.out.printf("%-20s %-12s %-6s %s%n", "Method", "Status", "Since", "Action");

        Method[] methods = apiClass.getDeclaredMethods();
        Arrays.sort(methods, Comparator.comparing(Method::getName));

        int deprecatedCount = 0;
        for (Method method : methods) {
            Deprecated deprecated = method.getAnnotation(Deprecated.class); // null if absent
            if (deprecated == null) {
                System.out.printf("%-20s %-12s %-6s %s%n", method.getName(), "active", "-", "keep using");
                continue;
            }
            deprecatedCount++;
            String action = deprecated.forRemoval() ? "REMOVE before next release" : "migrate when possible";
            String since = deprecated.since().isEmpty() ? "?" : deprecated.since();
            System.out.printf("%-20s %-12s %-6s %s%n", method.getName(), "deprecated", since, action);
        }
        System.out.println(deprecatedCount + " of " + methods.length + " methods are deprecated.");
    }
}
javac PaymentService.java DeprecationReport.java
java DeprecationReport

Output:

API report for PaymentService
Method               Status       Since  Action
payWithCheque        deprecated   3.0    migrate when possible
payWithDemandDraft   deprecated   2.4    REMOVE before next release
payWithUpi           active       -      keep using
refund               active       -      keep using
2 of 4 methods are deprecated.

The same annotations also warn every developer who still calls the old methods. Compile a class that uses all three payment methods:

public class Shop {
    public static void main(String[] args) {
        PaymentService payments = new PaymentService();
        System.out.println(payments.payWithUpi(499.0));
        System.out.println(payments.payWithCheque(1200.0));
        System.out.println(payments.payWithDemandDraft(5000.0));
    }
}
javac -Xlint:deprecation Shop.java
Shop.java:5: warning: [deprecation] payWithCheque(double) in PaymentService has been deprecated
        System.out.println(payments.payWithCheque(1200.0));
                                   ^
Shop.java:6: warning: [removal] payWithDemandDraft(double) in PaymentService has been deprecated and marked for removal
        System.out.println(payments.payWithDemandDraft(5000.0));
                                   ^
2 warnings

How it works:

  1. One annotation, two readers. The compiler reads @Deprecated to produce warnings, and the report tool reads the same annotation at runtime through reflection.
  2. getAnnotation returns null when absent. That is how the loop separates active methods from deprecated ones.
  3. Elements carry real data. since() and forRemoval() turn a simple label into a migration plan: forRemoval = true becomes "REMOVE before next release".
  4. Sorted output. getDeclaredMethods() returns methods in no fixed order, so the tool sorts them by name for a stable report.
  5. Warning levels. A forRemoval = true method produces a [removal] warning on every compile. Plain deprecation warnings appear in full only with -Xlint:deprecation; without it, javac prints a short note instead.
  6. Behaviour is unchanged. Running Shop still prints all three payment lines. The annotations inform people and tools; they never block the call.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Annotations: Basics of @ Metadata in Java and get answers drawn from it.

Signed-in readers only.