← Back to Chapters

Java Annotations

? Java Annotations

? Quick Overview

Annotations in Java provide metadata about the code. They do not change program execution directly, but they help the compiler, tools, and frameworks understand how the code should be treated.

? Key Concepts

  • Annotations start with the @ symbol
  • They can be applied to classes, methods, variables, and more
  • Used for compiler checks, configuration, and runtime processing
  • Widely used in frameworks like Spring, Hibernate, and JUnit

? Syntax & Theory

Java provides built-in annotations and also allows developers to create custom annotations. Annotations can be processed at compile-time or runtime using reflection.

? View Code Example
// Using a built-in Java annotation
@Override
public String toString() {
return "Hello Annotations";
}

? Live Output / Explanation

Explanation

The @Override annotation tells the compiler that the method must override a method from its superclass. If it does not, the compiler throws an error.

? Interactive Simulator: How @Override protects you
// Parent Class
class Parent { void saveData() { ... } }
// Child Class
class Child extends Parent { void saveData() { ... } }
⚠️ Warning: Risky Code
Typo possible without check.

? Tips & Best Practices

  • Always use @Override when overriding methods
  • Prefer annotations over XML configuration when possible
  • Understand annotation retention policies before using them

? Try It Yourself

  1. Create a class and override a method without @Override
  2. Add @Override and observe compiler behavior
  3. Explore other annotations like @Deprecated