×

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

How to Convert String to double in Java

How to Convert String to double in java It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from...

3 minutes read.

How to add Elements in Array in Java

Consider an array of the size n, in the given size we must add the elements in the given array. In this tutorial we are preferred to learn how to add...

3 minutes read.

Web Crawler in Java

In this article, you will be acknowledged with what a web crawler in java is and what are its functions. You will also be able to understand where to implement...

4 minutes read.

Monsoon Umbrella Problem in Java

The Monsoon Umbrella problem is a classic Java programming problem used to test the skills of a programmer. The problem involves writing a program to determine the number of umbrellas...

3 minutes read.

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

Shallow copy in Java

Java's most important task is making a copy or clone of an object. In this part, we'll talk about shallow copies in Java and how to make them of Java...

4 minutes read.

How to uninstall the Java in Ubuntu

We need java on our computers in our daily lives because there are lots of different applications that are developed using the java environment, so we have to install java...

4 minutes read.

How to check if date is valid in Java?

In this article, you will acknowledge about how to verify if a date is valid or not. For this you will learn the approach, you will be able to write...

3 minutes read.

Java Open File

Java Desktop class give an open() strategy to open a filr. It has a place with a java.awt package. Work area execution is stage subordinate, so it is important to...

5 minutes read.

Java Xmx

This section will explain what Xmx in Java is and how to establish a Java application's maximum heap size. When we execute a Java application, it occasionally displays an error message...

3 minutes read.

How to Iterate a HashMap in Java?

Hash-map is a class of Java collections framework which has the functionality to implement the Map interface of Java. It stores the data in key-value pairs and can be accessed...

5 minutes read.

Concurrent Linked Deque in Java with Examples

Introduction Java's concurrent-linked deque, which holds its items as linked nodes, is unconstrained and thread-safe. Concurrent Linked Deque allows for element removal and addition on both sides because it implements the...

4 minutes read.

Object Definition in Java

In this article, you will be acknowledged about object in Java, its definition and how is this useful in writing the programs in Java. The comprehension of object-oriented technology depends on...

4 minutes read.

Java Destructors

Before knowing about Java destructors, let us know about constructors. If we understand the concept of the constructor, we can easily understand about destructor and also, we will get an...

3 minutes read.

How to Set Java_home in Linux

To set the Java_home in Linux, we must follow several steps to make us understand it easily.  Java follows the principle called WORA (write once run anywhere). We know that java...

3 minutes read.

Java Future Example

Future is an interface in the Java language that is a part of  java.util.concurrent package. It serves as a symbol for the output of an asynchronous computation. The interface offers ways to determine whether a computation has finished,  wait for it to finish, and receive its result. Once the task or calculation is finished, it cannot be undone. A Future interface offers ways to determine whether the computation is finished, to wait for it to finish, and to receive the computation's results. When the computation...

3 minutes read.

Java Class Keyword

We know that java is object-oriented programming language which contains the essential key concepts such as classes and objects etc to have clear idea about the object-oriented programming.Java is mainly...

3 minutes read.

Java Math signum() Method

The signum() method of Java Math class returns the signum function of the value. Syntax: public static double signum(double d)public static float signum (float d) Parameters: The parameter ‘d’ represents the floating-point value whose...

2 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.