Annotations in Java
All Java Topics
Last updated: May 25, 2026
Author: ManaCoding Team
Annotations in Java provide metadata about code. They do not change program logic but give instructions to the compiler or runtime tools (like Spring, Hibernate).
Syntax
@Override
public String toString() {
return "Hello";
}
Example Program
import java.lang.annotation.*;
@interface Info {
String author();
int version();
}
@Info(author = "Jai", version = 1)
class Demo {
@Deprecated
public void oldMethod() {
System.out.println("Old method");
}
@Override
public String toString() {
return "Demo Class";
}
}
public class Main {
public static void main(String[] args) {
Demo d = new Demo();
d.oldMethod();
System.out.println(d.toString());
}
}
// Output:
// Old method
// Demo Class
What are Annotations?
- 1 Provide metadata about code.
- 2 Do not change program logic.
- 3 Used by compiler and frameworks.
- 4 Part of java.lang package.
Types of Annotations
- 1 @Override – method override check.
- 2 @Deprecated – marks old code.
- 3 @SuppressWarnings – suppress warnings.
- 4 Custom annotations.
Why Use Annotations?
- 1 To provide metadata.
- 2 To improve code readability.
- 3 To support frameworks.
- 4 To reduce boilerplate code.
Custom Annotations
- 1 Defined using @interface.
- 2 Can have elements (fields).
- 3 Used with reflection.
- 4 Processed at compile or runtime.
Quick Summary
- Annotations provide metadata in Java.
- They do not affect program logic.
- Used heavily in frameworks.
- Can be built-in or custom.
FAQs
What are annotations in Java?
They are metadata that provide information about code.
Do annotations affect program logic?
No, they only provide metadata.
What is @Override used for?
It indicates that a method overrides a superclass method.
Can we create custom annotations?
Yes, using @interface keyword.
Which frameworks use annotations?
Spring, Hibernate, and JUnit.
Interview Questions
Q1.
What are annotations in Java?
Answer:
They are metadata that provide information about code.
Q2.
Do annotations affect program logic?
Answer:
No, they only provide metadata.
Q3.
What is @Override used for?
Answer:
It indicates that a method overrides a superclass method.
Q4.
Can we create custom annotations?
Answer:
Yes, using @interface keyword.
Q5.
Which frameworks use annotations?
Answer:
Spring, Hibernate, and JUnit.
Quiz
What is the purpose of annotations in Java?