Annotations
Annotations Basics
Understand the purpose, syntax, and basic usage of annotations in Java.
Interview: Tests fundamental knowledge: how compiler handles annotations, and the differences between source, class, and runtime retention.
Annotations are metadata tags added to code elements like classes, methods, variables, or parameters. They do not change code execution directly, but are read by compilers, build tools, or runtime frameworks.
Core Idea
Annotations embed metadata directly inside Java source code, avoiding the need for external XML configuration.
Why It Matters
Modern frameworks (like Spring or Hibernate) rely entirely on annotations for routing, validation, and object-relational mapping (ORM).
Interview Lens
Focuses on retention policies (SOURCE, CLASS, RUNTIME) and compiler check integrations.
Annotation Retention Policies
An annotation's Retention Policy determines how long the metadata survives:
- SOURCE: Discarded by the compiler. Useful for checks (e.g.
@Override,@SuppressWarnings) or code generator plugins (Lombok). - CLASS: Kept in the compiled
.classfile, but discarded by the JVM classloader at runtime. This is the default. - RUNTIME: Preserved in the compiled class file and loaded into JVM memory. These can be inspected at runtime using Reflection.
Code Walkthrough
This class demonstrates using standard compiler-instructing annotations.
public class AnnotationDemo { @Override // Compiler verifies method matches parent declaration public String toString() { return "AnnotationDemo instance"; }
@Deprecated // Compiler triggers warning if other classes invoke this public void legacyMethod() { System.out.println("Use newMethod() instead."); } }
Interview-Relevant Information
Q: Can annotations contain logic or modify code execution directly?
Answer: No. Annotations are passive metadata structures. They cannot contain executable code blocks. The code behavior is modified by external processors (like compilers reading SOURCE annotations or reflection-based frameworks parsing RUNTIME annotations).
Quick Checklist
What is a retention policy? Which policy allows checking metadata at runtime? If yes, you understand annotation basics.
Use Cases
Configuring compile-time checks to prevent typo bugs in method signatures.
Flagging API methods as deprecated to coordinate software migrations.
Common Mistakes
Assuming class-retention annotations can be read via runtime reflection (they require RUNTIME retention).
Overusing legacy XML configurations when simpler annotation alternatives exist.