How Do Annotations Work in Java?

Java annotations are used to provide meta data for the Java code, although they are not a part of the program itself. Metadata is data about data. So Annotations are metadata for source code. Classes, methods, variables, parameters and packages can be annotated in Java.

The important use of Annotations such as:

  1. Compiler instructions : Annotations can be used by the compiler to detect errors or suppress warnings.
  2. Build-time instructions : Software tools can process annotation information to generate code, XML files, and so forth.
  3. Runtime instructions : Some annotations are available to be examined at runtime.

Java has three built-in annotations:

  1. @Override : Checks that the method is an override. Causes a compile error if the method is not found in one of the parent classes or implemented interfaces.
  2. @SuppressWarnings : Instructs the compiler to suppress the compile time warnings specified in the annotation parameters.
  3. @Deprecated : Marks the method as obsolete. Causes a compile warning if the method is used.
@Override void yourMethod() { //Do something }
In the above code @Override annotation is being applied to a method. The @Override is instructing compiler that yourMethod() is an overriding method which is overriding the method (yourMethod()) of super class.