×

Annotations in Java

Annotations in Java

Java Annotations are metadata about the source code. They do not have any direct effect on the execution of the java program. Annotations in Java were introduced in JDK 5. The main purpose of using annotation is that it gives instructions to the compiler at the build-time and at the runtime of program execution.

Built-in Annotation in Java

There are three built-in annotations in Java,

  1. @Override

It is used during inheritance. The child class overrides the method declared in the base class. It is recommended to use this annotation so that even if someone changes the name of the method in the base class, the compiler will show an error message. Otherwise, it can be a hectic task to identify such errors.

Example:

 /* Base Class */
public class SampleParent {
    public void dummymethod() {
        System.out.println("Inside parent class");
    }
}
/* Child Class */
public class SampleChild extends SampleParent {
    @Override
    public void dummymethod() {
        System.out.println("Inside child class");
    }
} 

Here, the dummymethod() is initially declared inside SampleParent class and overridden inside SampleChild class.

  • @Deprecated

The @Deprecated annotation is a type of built-in annotation used for the data members who are no longer used in the program. The compiler shows a warning message if a @Deprecated data member is called or used. It is recommended to us @deprecated symbol to explain the reason behind deprecating the method, class, or data variable.

Example:

 @Deprecated
/*  @deprecated Use another class.*/
public class SampleAnnotate
{
    /* Some code */
} 

Here, the class SampleAnnotate is deprecated using @Deprecate. And @deprecated symbol explains the reason.

  • @SuppressWarnings
 public class SampleAnnotate
{
    @Deprecated
    /*  @deprecated Use another method.*/
    void deprecatedmethod()
    {
        /* Some code */
    }
}
class Sample extends SampleAnnotate
{
     @SuppressWarnings
    /* Deprecated method can be overridden with @SuppressWarnings */
    void deprecatedmethod()
    {
        /* Some code */
    }
} 

Here, the deprecatedmethod() is deprecated in the base class but still can be overridden using @SuppressWarnings.

Types of Annotations

  1. Marker Annotation

The purpose of marker annotation is to label a declaration. It does not contain any kind of data or members.

Example: @Override

  • Single value Annotation

An annotation that only contains one data value or method is called Single value annotation. The data element is named as value by default.

Example: @Annotaionexample(“DataMemberName”)

  • Full Annotation

This kind of annotation has multiple data elements split by using a comma.

Example: @Annotaionexample(value1=”DataMemberName”, value2=”DataMemberName”)

  • Type Annotation

Type annotation can be used to annotate the type of any method or a data variable. Type annotation is annotated using @Target annotation.

Example: The following program demonstrates the type annotation.

SampleTypeAnnotation.java

 import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/* @target annotation */
@Target(ElementType.TYPE_USE)
/* Declare type annotation */
@interface AnnotationTypeExample{}
public class SampleTypeAnnotaion
{
    /* Driver Code */
          public static void main(String ar[])
          {
              /* Annotating the type of a string */
                   @AnnotationTypeExample String string = "This program demonstrates type annotation";
                   System.out.println(string);
                   Annotatemethod();
          }
          /* Annotating return type of a method */
          static @AnnotationTypeExample int Annotatemethod()
          {
                   System.out.println("This method return type uses type annotation");
                   return 0;
          }
} 

Output:

 This program demonstrates type annotation
This method return type uses type annotation 

How to Create Custom Annotations?

To create a custom annotation @interface keyword is used. This keyword informs the Java compiler about the custom annotation. The following example shows how to create a custom annotation.

 /* Custom annotation */
@interface SampleCustomAnnotation
{
    String empid();
    String empname()
    String emppost()
    int empage();
}
The following code shows the use of custom annotation declared above. 
/* Custom Annotation is used here */
@MyAnnotation(
    empid="42",
    empname="abc"
    emppost="manager",
    empage=28,
)
public class MyClass
{
/* Some Code */
} 

All the data members declared inside the custom annotation are initialized in the above code.

Annotation Placement

  1. Levels of Annotation

The annotations in Java program can be placed at the start of a class, method, variable, or interface. Following are the two levels of annotations.

  1. Class Level Annotation:

The annotation that is placed just above the class is called a Class level annotation.

Example:

 @Entity
public class Demo
{
     /* Some Code */
} 

Here, @Entity is a custom class-level annotation.

  1. Method Level Annotation:

The annotations that are placed just above a method is called a method level annotation.

Example:

 @SampleAnnotation
int Sample()
{
     /* method code */
} 

In the above code, the @SampleAnnotation is a custom annotation.

  • Type Annotation

At first, programmerswere allowed to only use annotations at the declaration part of data members. But now we can use annotation wherever a type is declared.

Example:

@NonNull List<String> dummylist

The above example declares a String type of List with @NonNull annotation.

In this article, we have discussed the concept of annotations in Java, what their types are and how we can use custom annotations.


Related Topics

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

Snake and Ladder Problem in Java

Find the smallest number of dice throws necessary to reach the destination or last cell from the source or first cell on a snake and ladder board. Essentially, the player...

6 minutes read.

Polymorphism Program in Java

Polymorphism Program in Java: Polymorphism means the existence of different forms of an object. The object can be a class object or a real-time entity. For example, a person can...

5 minutes read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.

Sealed Class in Java

What is a Sealed Class in Java? In programming, the two main issues that must be taken into account when creating an application are security and control flow. The use of...

5 minutes read.

Selection Sort in Java

Selection Sort in Java Selection sort is also a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted portion of the input array, and placing it...

5 minutes read.

Bouncy Number in Java

We will define bouncy numbers in this section and write Java programmes to determine whether a specific number is bouncy. Java coding exams and academic assignments usually inquire about the...

3 minutes read.

Generics vs Wildcard in Java

In generic programming, the question mark (?) is often referred to as the wildcard. It stands for a mysterious type. The wildcard can be used for many different contexts, such as...

4 minutes read.

Concurrent Modification Exception In Java

When an object is attempted to be updated concurrently when it is not allowed, the ConcurrentModificationException arises. This error typically occurs while using Java Collection classes. When another thread is iterating...

5 minutes read.

Java Integer getInteger() method

The getInteger() method of Integer class determines the integer value of the system property with the given name. Syntax` public static Integer getInteger(String nm) Parameters The parameter ‘nm’ represents the property name. Throws The getInteger ()...

1 minute read.

Java Math hypot() Method

The hypot() method of Math class returns the square root for the expression x2 + y2 without the intermediate underflow or overflow . Syntax: public static double hypot(double x, double y) Parameters: The parameters...

2 minutes read.

Collection Programs in Java

Collection Programs in Java Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly...

4 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.

What is String in Java?

What is String in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a Java...

4 minutes read.

Java Identifiers

In Java, the symbolic notations used for identification are called identifiers. Identifiers can be the name for the class, variable name declaration, name of the package, constant name and many...

3 minutes read.

Java copy constructor Example

Java provides the copy constructor much like C++ does. However, it is produced by default in C++. While we define our own copy constructor in Java. With an example, we will...

3 minutes read.

Narcissistic Number in Java

A Narcissistic number is made up of digits that have been added together and raised to powers equal to the number of digits in the original number. In those other...

3 minutes read.

Find next greater number with same set of digits in Java

It contains a number (num). Finding the smallest number that has the same number of elements as num that is also larger than num is the task at hand. If...

8 minutes read.

Java Byte Keyword

Byte: The Keyword Byte in Java programming language is a primitive data type.Digital content that is most used for eight bits is called as a byte.The Java Byte Keyword is used...

3 minutes read.

Java String charAt() method

It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1. Syntax: public char charAt (int index) Parmeters It accepts only...

3 minutes read.