What is the @Deprecated annotation in Java?

Overview

As projects evolve, the interfaces, methods, and variables involved also undergo changes. Certain implementations, interfaces, etc., become obsolete. In these situations, the developers need to be alerted regarding the deprecation of such elements rather than breaking the compatibility.

In Java, the @Deprecated annotation helps us alert the developers regarding the usage of deprecated elements.

The @Deprecated annotation

The annotation conveys to developers that they are discouraged from using the elements that are annotated with the @Deprecated annotation. The element can be a field, attribute, method, interface, or module.

It’s a common practice to provide documentation alongside the annotation to indicate a better option that fulfills the same purpose.

The since attribute

since is a string-valued attribute that indicates the version in which the annotated program element was first deprecated. This attribute was introduced in Java version 9.

The forRemoval attribute

forRemoval is a boolean-valued attribute that can take true or false as value.

  • true value indicates an intent to remove the element in a future version.
  • false value indicates that the use of the element is discouraged, but there is no specific intent to remove it.

This attribute was introduced in Java version 9.

Example

public class Main {
@Deprecated(since = "2.1", forRemoval = true)
public int fibonacci(int n){
System.out.println("Calculate Fibonacci");
return 0;
}
public static void main(String args[]){
Main obj = new Main();
obj.fibonacci(100);
}
}

Explanation

  • Line 1: We define the Main class.

  • Lines 3 and 4: We define a fibonacci() method. We annotate the method with @Deprecated annotation. since and forRemoval attributes are also defined.

  • Line 5: We print a string indicating the calculation of the Fibonacci series.

  • Line 6: We return 0.

  • Line 10: We create an instance of the Main class.

  • Line 11: We invoke the fibonacci() method passing 100 as the argument.

Here, the code indicates that the method fibonacci is deprecated since version 2.1 of the library is used. And it is subjected to removal in a future version.

Free Resources