Web Analytics

Annotations

Intermediate ~15 min read

Annotations provide metadata (data about data) for our code. They do not change the action of a compiled program directly but are used by compilers and tools.

Built-in Annotations

Java has several built-in annotations:

  • @Override: Ensures a method is overriding a parent method.
  • @Deprecated: Marks a method/class as obsolete.
  • @SuppressWarnings: Tells the compiler to ignore specific warnings.
@Override
public String toString() {
    return "My Object";
}

@Deprecated
public void oldMethod() { }

Creating Custom Annotations

You can create your own annotations using the @interface keyword.

@interface MyAnnotation {
    String value();
    int version() default 1;
}

@MyAnnotation(value = "Test", version = 2)
public void myMethod() { }

Full Example

Output
Click Run to execute your code

Summary

  • Annotations start with @.
  • Use @Override to prevent bugs when overriding methods.
  • Annotations can be processed at runtime using Reflection (next lesson).