Nearby lessons

107 of 125

Java - Annotations

📌 What You Will Learn
  • What annotations are and why they are useful
  • The built-in annotations: @Override, @Deprecated, @SuppressWarnings
  • Meta-annotations: @Retention and @Target
  • Creating your own custom annotation

Annotations is a core concept of the Java language. This lesson explains What is an Annotation?, Important Built-in Annotations and Meta-Annotations — Annotations About Annotations with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

What is an Annotation?

An annotation is a small piece of information (metadata) attached to code — like a sticky note on a class, method or variable. It does not change how the code runs by itself; instead, tools and frameworks read it and act on it.

In simple words: An annotation is metadata — a sticky note on your code. It does not change how the code runs; tools and frameworks read it and decide what to do.

Think of annotations as labels on boxes in a warehouse: 'FRAGILE' (handle carefully), 'EXPIRED' (throw away). The box does not change — but the workers (tools) behave differently when they see the label.

Example01
JCode Cell
1@Override
2public void run() { ... } // '@Override' is an annotation

Important Built-in Annotations

AnnotationUsed onWhat it tells
@OverrideMethods"I am redefining a parent method." Compiler warns if the signature is wrong.
@DeprecatedClasses/methods"This is old — avoid using it." Compiler warns users.
@SuppressWarnings("unchecked")Methods/classes"Stop showing these warnings."
@FunctionalInterfaceInterfaces"This interface has exactly one abstract method (can be a lambda)."
@SafeVarargsMethods"These var-args are safe."
In simple words: `@Override` is a safety net. It tells the compiler you are redefining a parent method, and it warns you if you got the signature wrong.
Example02
JCode Cell
1class Demo {
2 @Override
3 public String toString() {
4 return "Demo class";
5 }
6 
7 @Deprecated
8 void oldMethod() {
9 System.out.println("Old way - please use newMethod");
10 }
11 
12 void newMethod() {
13 System.out.println("New way");
14 }
15}
16 
17class Test {
18 public static void main(String[] args) {
19 Demo d = new Demo();
20 d.oldMethod(); // compiler shows a warning: deprecated
21 d.newMethod();
22 }
23}

Meta-Annotations — Annotations About Annotations

When we create our own annotation, we must decorate it with meta-annotations that describe where it works and how long it lives:

Meta-annotationWhat it controls
@RetentionHow long the annotation is kept: SOURCE, CLASS (compile), or RUNTIME (needed for reflection).
@TargetWhere it can be used: METHOD, FIELD, CLASS, PARAMETER, etc.
@DocumentedThe annotation will appear in javadoc.
@InheritedChild classes also get this annotation.
In simple words: `@Retention` controls how long an annotation survives, and `@Target` controls where it can go. Use RUNTIME retention when reflection must read the annotation.

Creating a Custom Annotation

In simple words: A custom annotation is declared with `@interface` and read back with reflection. isAnnotationPresent() checks if the annotation is there, and getAnnotation() reads its values.
Example04
JCode Cell
1import java.lang.annotation.*;
2 
3// Step 1: declare the annotation
4@Retention(RetentionPolicy.RUNTIME) // visible at run time
5@Target(ElementType.METHOD) // only for methods
6@interface MyTest {
7 int value() default 1;
8}
9 
10// Step 2: use it
11class Calculator {
12 @MyTest(value = 5)
13 public void add() { }
14}
15 
16// Step 3: read it (with reflection)
17import java.lang.reflect.*;
18 
19class ReadAnnotations {
20 public static void main(String[] args) throws Exception {
21 for (Method m : Calculator.class.getMethods()) {
22 if (m.isAnnotationPresent(MyTest.class)) {
23 MyTest t = m.getAnnotation(MyTest.class);
24 System.out.println(m.getName() + " has @MyTest value = " + t.value());
25 }
26 }
27 }
28}
Output
add has @MyTest value = 5

Real-World Use of Annotations

Annotations are everywhere in modern Java. Here is where you meet them daily:

Framework / APIFamous annotations
JUnit (testing)@Test, @BeforeEach, @AfterEach
Spring (web apps)@Component, @RestController, @Autowired
Spring Boot@SpringBootApplication
Hibernate (database)@Entity, @Table, @Column
JDK (Java 8+)@FunctionalInterface, @Deprecated
Trainer's Note: Trainer insight: annotations + reflection together are what make frameworks magical. Spring sees @RestController on your class, uses reflection to load it, and automatically starts handling web requests. When you write annotations, remember they are just labels — the real action happens in the framework code that reads them.

The Two Big Questions About Annotations

Q1 — We already have comments; why annotations?

Because comments are removed during compilation (the lexical analysis phase deletes them). So comments exist only in the .java file — they are gone from the .class file and unavailable at run time. Annotations survive compilation and can be read by your program at run time (with reflection).

PointCommentsAnnotations
Present after compilation?No (removed)Yes (if RetentionPolicy.RUNTIME)
Readable by the program?NoYes
Best forHuman descriptionsMetadata for tools and frameworks

Q2 — We already have XML; why annotations?

XML configuration was the old way, but it came with problems: you had to learn XML, check that files were in the right place and correctly formatted, and write parsing code. Annotations are Java-native and remove all of that.

PointXML documentsAnnotations
Extra technology to learn?Yes (XML + parsers)No
File placement/format checksNeeded every timeNot needed
Modern frameworksOld style (up to Java 1.4-era)Modern default (Spring Boot, JUnit 5)

Annotations vs Comments vs XML

A very good question from the classic material: we already have comments to describe code, so why do we need Annotations (Chapter 20)?

The problem: when you compile a program, the lexical analysis phase of the compiler removes comments. So comments exist only in the .java file — they are gone from the .class file and unavailable at run time.

Annotations are different — they stay with the code even after compilation, up to run time, and can be read programmatically (with reflection).

PointCommentsAnnotationsXML documents
Available after compilation?No (removed)YesYes (separate file)
Readable by your program?NoYesYes
Extra learning needed?NoNoYes (XML + parsing)
Best forHuman descriptionsMetadata for tools/frameworksConfiguration (older style)
Trainer's Note: Updated knowledge: in the old days (up to Java 1.4) many frameworks used XML for configuration. From Java 5, Annotations became the simpler Java-native alternative, and modern frameworks (Spring Boot, JUnit 5) rely heavily on them. XML still exists but annotations are the modern default.
📝 Key Takeaways
  • Annotations are metadata — sticky notes on code; they do not change execution by themselves.
  • @Override, @Deprecated, @SuppressWarnings are the common built-in ones.
  • @Retention decides how long the annotation lives; @Target decides where it can be used.
  • Custom annotations are declared with @interface and read using reflection.
  • Frameworks like Spring, JUnit and Hibernate are powered by annotations + reflection.

🧠 Test Your Knowledge

8 Questions
Progress: 0 / 8