English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input Output (I/O)

Java Reader/Writer

Java Other Topics

Java Annotations (Annotations)

In this tutorial, we will learn what annotations are, different Java annotations, and how to use them through examples.

Java annotations are the metadata of our program source code (data about data).

They provide additional information about the program to the compiler, but are not part of the program itself. These annotations do not affect the execution of the compiled program.

Annotations start with @. Their syntax is:

@AnnotationName

Let's take the @Override annotation as an example.

@Override annotation specifies that the method annotated with it overrides the method with the same name, return type, and parameter list of the superclass.

When rewriting methods, it is not necessary to use @Override. However, if we use it, the compiler will give an error if there is an error in the method override (such as incorrect parameter type).

Example1: @Override annotation example

class Animal {
  public void displayInfo() {
    System.out.println("I am an animal.");
  }
}
class Dog extends Animal {
  @Override
  public void displayInfo() {
    System.out.println("I am a dog.");
  }
}
class Main {
  public static void main(String[] args) {
    Dog d1 = new Dog();
    d1.displayInfo();
  }
}

Output result

I am a dog.

In this example, the method displayInfo() exists in both the superclass Animal and the subclass Dog. When calling this method, the method of the subclass will be called instead of the method in the superclass.

Annotation format

Annotations can also include elements (members/Properties/Parameters).

1.Marker annotations

Marker annotations do not contain members/Elements. It is only used to mark declarations.

The syntax is:

@AnnotationName()

Since these annotations do not contain elements, parentheses are not required. For example,

@Override

2.Single-element annotations

Single-element annotations only contain one element.

The syntax is:

@AnnotationName(elementName = "elementValue")

If there is only one element, it is customary to name the element value.

@AnnotationName(value = "elementValue")

In this case, the element name can also be removed. The default element name value is used.

@AnnotationName("elementValue")

3.Multi-element annotations

These annotations contain multiple elements separated by commas.

The syntax is:

@AnnotationName(element1 = "value1", element2 = "value2")

Annotation position

Any declaration can be annotated by placing it above the declaration. From Java 8Starting with Java 5, comments can also be placed before the type.

1Above declaration statements

As described above, Java comments can be placed above the declarations of classes, methods, interfaces, fields, and other program elements.

Example2Example of @SuppressWarnings annotation

import java.util.*;
class Main {
  @SuppressWarnings("unchecked")
  static void wordsList() {
    ArrayList wordList = new ArrayList<>();
    //This will result in unchecked warnings
    wordList.add("w")3codebox"); 
    System.out.println("Word list => " + wordList);
  }
  public static void main(String args[]) {
    wordsList();
  }
}

Output result

Word list => [w3codebox]

If the above program is compiled without the @SuppressWarnings("unchecked") annotation, the compiler will still compile the program, but will give the following warning:

Main.java uses unchecked or unsafe operations.
Word list => [w3codebox]

We receive a warning

Main.java uses unchecked or unsafe operations

Because of the following statement.

ArrayList wordList = new ArrayList<>();

This is because we have not defined the generic type for ArrayList. We can resolve this warning by specifying generics within the angle brackets <>.

ArrayList<String> wordList = new ArrayList<>();

2. type annotations

In Java 8Previously, comments could only be applied to declarations. Now, type annotations can also be used. This means we can place annotations anywhere types are used.

Constructor call

new @Readonly ArrayList<>()

Type definition

@NonNull String str;

This declaration specifies a non-null variable str of type String to avoid NullPointerException.

@NonNull List<String> newList;

This declaration specifies a non-null list of String types.

List<@NonNull String> newList;

This declaration specifies a list of non-null String values.

Type conversion
newStr = (@NonNull String) str;

extends and implements clauses

class Warning extends @Localized Message

throws Clause

public String readMethod() throws @Localized IOException

Type annotations make Java code more analyzable and provide stronger type checking.

Annotation Types

1. Predefined Annotations

  1. @Deprecated

  2. @Override

  3. @SuppressWarnings

  4. @SafeVarargs

  5. @FunctionalInterface

2. Meta Annotations

  1. @Retention

  2. @Documented

  3. @Target

  4. @Inherited

  5. @Repeatable

3. Custom Annotations

These annotation types are inJava Annotation TypesDetailed descriptions are provided in the tutorial.

Annotation Usage

  • Compiler Instructions - They can be used to provide instructions to the compiler, detect errors, or suppress warnings. Such as built-in annotations @Deprecated, @Override, @SuppressWarnings.

  • Compile-time Instructions - These comments provide compile-time instructions that help software build tools generate code, XML files, etc.

  • Runtime Instructions - Some annotations can be defined to provide instructions to the program at runtime. These annotations are accessed using Java reflection.