You have already been using an annotation for a long time: @Override. When we put it above a method, the method's behaviour doesn't change at all. Instead, it is a note to the compiler that says "I intend to override a parent method; please check that I really do."
Think of annotations like sticky notes on a textbook page. The notes don't change what is printed on the page, but someone who reads them (you, a teacher, or a tool) can act on them. In Java, the "readers" are the compiler, build tools, and frameworks.
An annotation is a form of metadata (data about the code) that you attach to classes, methods, fields, parameters, and other parts of a program. It starts with the @ symbol. An annotation does nothing by itself; it only has an effect when the compiler, a tool, or code running at runtime reads it.
Annotations were added in Java 5. Today they are everywhere: testing tools like JUnit use @Test, and frameworks like Spring use annotations such as @Autowired to wire an application together. Understanding them is important for both interviews and real projects.
Annotation Syntax
An annotation is written with @ followed by its name, placed just before the thing it describes. Some annotations take values inside brackets:
@Override // marker annotation: no values
public String toString() { ... }
@SuppressWarnings("unchecked") // one value
static List<String> makeList() { ... }
@Deprecated(since = "2.0", forRemoval = true) // named values
int oldMultiply(int a, int b) { ... }The named values like since = "2.0" are called elements. If an annotation has an element called value and it is the only one you are setting, you can leave out the name: @SuppressWarnings("unchecked") is short for @SuppressWarnings(value = "unchecked").
Annotations can be placed on classes, interfaces, methods, constructors, fields, parameters, and local variables. You can also put several annotations on the same thing.
Built-in Annotations
Java comes with a few annotations that the compiler understands directly:
Annotation | Used on | What it does |
|---|---|---|
| Methods | Compile error if the method does not actually override or implement a parent method |
| Almost anything | Marks code as outdated; the compiler warns anyone who uses it |
| Classes, methods, fields, variables | Tells the compiler to hide specific warnings |
| Interfaces | Compile error if the interface does not have exactly one abstract method |
| Varargs constructors and | Promises that a generic varargs method is safe, which hides a related warning |
We covered @Override in detail in the Method Overriding chapter: it catches mistakes like a misspelled method name or wrong parameter types. You will meet @FunctionalInterface again in the Functional Interfaces chapter. Let's look at @Deprecated and @SuppressWarnings now.
@Deprecated
When a method is replaced by a better one, we can't just delete it, because other code may still be using it. Instead, we mark it @Deprecated. The code keeps working, but everyone who uses it gets a warning. Since Java 9, the annotation has two optional elements:
since: the version in which it was deprecated.forRemoval: iftrue, it will be removed in a future version, so users should move away from it soon.
import java.util.ArrayList;
import java.util.List;
class Calculator {
/** @deprecated use {@link #add(int, int)} instead */
@Deprecated(since = "2.0")
int sum(int a, int b) {
return a + b;
}
@Deprecated(since = "2.0", forRemoval = true)
int oldMultiply(int a, int b) {
return a * b;
}
int add(int a, int b) {
return a + b;
}
}
class Main {
@SuppressWarnings("unchecked")
static List<String> makeList() {
List raw = new ArrayList(); // raw type: normally gives an "unchecked" warning
raw.add("Java");
return raw;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.sum(2, 3));
System.out.println(calc.oldMultiply(2, 3));
System.out.println(calc.add(2, 3));
System.out.println(makeList());
}
}When we compile this with a plain javac Main.java, the compiler prints:
Main.java:34: warning: [removal] oldMultiply(int,int) in Calculator has been deprecated and marked for removal
System.out.println(calc.oldMultiply(2, 3));
^
Note: Main.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 warningThe forRemoval = true method gets a full warning straight away. The normal deprecated method sum() only produces a short note; compiling with javac -Xlint:deprecation Main.java shows its warning too:
Main.java:33: warning: [deprecation] sum(int,int) in Calculator has been deprecatedThese are only warnings, so the program still compiles and runs. Output:
5
6
5
[Java]It is good practice to also write a @deprecated tag in the method's documentation comment (as we did for sum()) to tell users what to use instead. Note the difference: @Deprecated with a capital D is the annotation; @deprecated with a small d is a Javadoc tag inside a /** */ comment.
@SuppressWarnings
In the same program, makeList() uses a "raw" List, with no type in angle brackets, which throws away the type safety that generics give us (see the Generics chapter). Without the annotation, the compiler would print:
Note: Main.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.@SuppressWarnings("unchecked") hides that warning for the method. Other common values are "deprecation", "removal", and "rawtypes", and you can pass several at once: @SuppressWarnings({"unchecked", "rawtypes"}).
Use it carefully. A warning usually points at a real risk, so suppress it only when you have checked the code and are sure it is safe, and put the annotation on the smallest piece of code possible (one method or one variable, not a whole class).
Creating Your Own Annotation
We can define our own annotations with the @interface keyword. Inside, each element is declared like a method with no parameters, and it can have a default value:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Arrays;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Author {
String name(); // required: no default value
String date() default "unknown"; // optional
int version() default 1; // optional
String[] reviewers() default {}; // optional array element
}
@Author(name = "Priya", version = 3, reviewers = {"Arjun", "Neha"})
class PaymentService {
}
@Author(name = "Rahul")
class LoginService {
}
class Main {
static void printInfo(Class<?> cls) {
Author a = cls.getAnnotation(Author.class);
System.out.println(cls.getSimpleName() + " -> author: " + a.name()
+ ", date: " + a.date()
+ ", version: " + a.version()
+ ", reviewers: " + Arrays.toString(a.reviewers()));
}
public static void main(String[] args) {
printInfo(PaymentService.class);
printInfo(LoginService.class);
}
}Output:
PaymentService -> author: Priya, date: unknown, version: 3, reviewers: [Arjun, Neha]
LoginService -> author: Rahul, date: unknown, version: 1, reviewers: []Let's go through it:
name()has no default, so it is required. Writing@Author()without a name would be a compile error.Elements with a
defaultare optional.LoginServicedid not setversion, so it got1.Array elements use curly braces:
reviewers = {"Arjun", "Neha"}. For a single item, the braces can be left out.cls.getAnnotation(Author.class)reads the annotation at runtime. This is called reflection: a program looking at its own classes while it runs. We read element values by calling them like methods, such asa.name().The two lines above
@interface Authorare meta-annotations (annotations on an annotation). They are explained in the next section.
Annotation elements are restricted. Their type can only be a primitive (int, boolean, ...), String, Class, an enum, another annotation, or a one-dimensional array of these. Wrapper types like Integer or any other class are not allowed. Values must be constants (such as literals, enum constants, or class literals like String.class), and null is never allowed, so default null is a compile error too.
Meta-Annotations: @Retention and @Target
When we create an annotation, we usually describe two things about it: how long it is kept, and where it may be used.
@Retention: how long is it kept?
RetentionPolicy | Kept until | Who can read it | Example |
|---|---|---|---|
| Compilation only; not stored in the | The compiler and source-processing tools |
|
| Stored in the | Tools that read | Rarely chosen on purpose |
| Available while the program runs | Your code, using reflection |
|
The default is CLASS, and this surprises many beginners. If you forget @Retention(RetentionPolicy.RUNTIME), reflection simply can't see your annotation:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@interface Visible {
}
@interface Invisible { // no @Retention, so the default (CLASS) is used
}
@Visible
@Invisible
class Report {
}
class Main {
public static void main(String[] args) {
System.out.println("@Visible present? " + Report.class.isAnnotationPresent(Visible.class));
System.out.println("@Invisible present? " + Report.class.isAnnotationPresent(Invisible.class));
}
}Output:
@Visible present? true
@Invisible present? falseBoth annotations are written on Report, but only the RUNTIME one can be found while the program is running.
@Target: where can it be used?
@Target lists the kinds of declarations an annotation may be placed on, using values from the ElementType enum:
ElementType | Allowed on |
|---|---|
| Classes, interfaces, enums, records (and annotation interfaces) |
| Methods |
| Fields (including enum constants) |
| Method and constructor parameters |
| Constructors |
| Local variables |
For example, with @Target(ElementType.METHOD), putting the annotation on a class is a compile error ("annotation interface not applicable to this kind of declaration"). To allow several places, use an array: @Target({ElementType.METHOD, ElementType.FIELD}). If you leave out @Target, the annotation can be used on almost any declaration.
Other meta-annotations
@Documented: the annotation appears in the Javadoc documentation of the code that uses it.@Inherited: if a class has this annotation, its subclasses are treated as having it too. It only works for annotations on classes.@Repeatable(Java 8): allows the same annotation to be written more than once on the same element, like@Schedule(day = "Monday")and@Schedule(day = "Thursday")on one class.
A Complete Example: A Mini Test Runner
How does a testing tool like JUnit know which methods are tests? You mark them with @Test, and the tool uses reflection to find and run them. Let's build a tiny version ourselves to see that there is no magic involved:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.TreeMap;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Test {
boolean enabled() default true;
}
class CalculatorTests {
@Test
static void additionWorks() {
check(2 + 3 == 5);
}
@Test
static void integerDivisionWorks() {
check(10 / 3 == 3);
}
@Test
static void multiplicationIsWrong() {
check(2 * 3 == 5); // deliberately wrong
}
@Test(enabled = false)
static void slowNetworkTest() {
check(false);
}
static void check(boolean condition) { // no @Test: the runner ignores it
if (!condition) {
throw new AssertionError("check failed");
}
}
}
class Main {
public static void main(String[] args) throws Exception {
// getDeclaredMethods() returns methods in no fixed order,
// so we sort them by name using a TreeMap
TreeMap<String, Method> tests = new TreeMap<>();
for (Method m : CalculatorTests.class.getDeclaredMethods()) {
if (m.isAnnotationPresent(Test.class)) {
tests.put(m.getName(), m);
}
}
int passed = 0, failed = 0, skipped = 0;
for (Method m : tests.values()) {
Test test = m.getAnnotation(Test.class);
if (!test.enabled()) {
System.out.println("SKIP " + m.getName());
skipped++;
continue;
}
try {
m.invoke(null); // null: the method is static
System.out.println("PASS " + m.getName());
passed++;
} catch (InvocationTargetException e) {
System.out.println("FAIL " + m.getName() + " (" + e.getCause().getMessage() + ")");
failed++;
}
}
System.out.println(passed + " passed, " + failed + " failed, " + skipped + " skipped");
}
}Output:
PASS additionWorks
PASS integerDivisionWorks
FAIL multiplicationIsWrong (check failed)
SKIP slowNetworkTest
2 passed, 1 failed, 1 skippedHere is what happens step by step:
getDeclaredMethods()gives us all methods ofCalculatorTests, includingcheck().isAnnotationPresent(Test.class)keeps only the methods marked@Test. This works only because@TesthasRUNTIMEretention.The methods go into a
TreeMapso they run in alphabetical order. Java does not guarantee any order forgetDeclaredMethods().getAnnotation(Test.class).enabled()reads the element value, and disabled tests are skipped.m.invoke(null)calls the method (nullbecause it is static). If the method throws an exception,invoke()wraps it in anInvocationTargetException, andgetCause()gives us the originalAssertionError.
Notice that @Test did nothing on its own. All of the behaviour came from the code in main() that reads the annotation. This is the most important idea of this chapter.
Annotations in Real Projects
You will see annotations constantly when you use Java frameworks. Some common ones:
Annotation | From | Purpose |
|---|---|---|
| JUnit | Marks a method as a unit test |
| Spring | Turn a class into a web API and map URLs to methods |
| Spring | Ask Spring to supply (inject) an object automatically |
| JPA / Hibernate | Map a class to a database table and a field to its primary key |
| Lombok | Generate getters and setters during compilation |
These frameworks read annotations in two main ways. Spring, JUnit and Hibernate mostly use reflection at runtime, just like our test runner. Lombok instead uses an annotation processor, which runs inside the compiler and works with SOURCE-level annotations.
Annotation vs Comment vs Interface
Feature | Comment | Annotation | Interface |
|---|---|---|---|
Read by | Humans only | Compiler, tools, and programs | Compiler and the type system |
Can carry values? | Free text | Yes, typed elements | Only constant fields |
Changes behaviour? | Never | Only if something reads it | Yes, defines methods a class must implement |
Available at runtime? | No | Only with | Yes |
Common Mistakes
Forgetting @Retention(RetentionPolicy.RUNTIME). The default is
CLASS, soisAnnotationPresent()returnsfalseand your annotation looks "ignored".Expecting an annotation to do something by itself. A custom annotation has no effect until some code (or tool) reads it.
Using unsupported element types.
Integer,List, ordefault nullare not allowed in an annotation element.Overusing @SuppressWarnings. Putting it on a whole class can hide real bugs. Fix the warning if you can, and suppress it as narrowly as possible if you can't.
Confusing @Deprecated with @deprecated. The annotation (capital D) is what the compiler checks; the Javadoc tag (small d) is documentation.
Interview Tips
What is an annotation? Metadata attached to code using
@. It doesn't change the code directly, but the compiler, tools, or frameworks can read it and act on it.Name some built-in annotations.
@Override,@Deprecated,@SuppressWarnings,@FunctionalInterface,@SafeVarargs.What are the retention policies?
SOURCE(discarded after compilation),CLASS(in the .class file, not at runtime; the default),RUNTIME(readable using reflection).What is a meta-annotation? An annotation used on other annotations:
@Retention,@Target,@Documented,@Inherited,@Repeatable.How do you create a custom annotation? With
@interface. Elements are declared like methods without parameters and may havedefaultvalues.Is @Override mandatory? No, overriding works without it, but it is strongly recommended because the compiler then checks that you really are overriding something.
The Main Idea
Annotations are labels with optional data that you attach to code. They don't do anything on their own; the compiler, tools, or your program (using reflection) read them and decide what to do.
Key points to remember:
Built-in annotations like
@Overrideand@Deprecatedlet the compiler check your code and warn users.Create your own with
@interface; elements can have default values.@Retentiondecides how long an annotation lives; useRUNTIMEto read it with reflection.@Targetdecides where an annotation may be used.Frameworks like JUnit and Spring are built on annotations plus reflection.