×

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 Math multiplyFull() Method

The multiplyFull() method of Math class returns the exact product of the arguments. Syntax: public static long multiplyFull (int x, int y) Parameters: The parameters ‘x’ and ‘y’ represent the first value and second...

1 minute read.

Java Wrapper classes

Java Wrapper classes A wrapper class is a class whose object contains a primitive data type; moreover it provides a way to use primitive data type (int, boolean, etc.) as objects. Wrapper...

2 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.

How to encrypt password in Java

Every software program needs a username and password to identify a legitimate user. A username can be any number of things, including an email address or a string of characters....

6 minutes read.

String Palindrome Program in Java

String Palindrome Program in Java The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and...

11 minutes read.

Java Math sin() Method

The sin() method of Java Math class returns the trigonometric sine of the specified angle. Syntax: public static double sin(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The sin() method...

1 minute read.

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.

Tetris Game in Java

The Tetris game is among the most well-known video games ever produced for computers. Today, we may engage in this game on a mobile device as well. Alexey Pajitnov conceptualized...

12 minutes read.

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method...

2 minutes read.

Decagonal Numbers in Java

This section explains what is a decagonal number and how to write Java programmes that compute decagonal numbers. Both academics and Java programmer interviews regularly question about the Decagonal number...

3 minutes read.

Morris Traversal for Inorder in Java

Through Morris’s traversal, a tree is traversed without the aid of recursion or stacks. Based on the threaded binary tree, the Morris traversal is used. We perform internal modification throughout...

4 minutes read.

Java LinkedHashMap

LinkedHashMap implements the Map interface. It inherits the HashMap class. Some essential features of LinkedHashMap are: It contains the values based on the keys. It maintains the order of insertion. It contains unique...

5 minutes read.

Java Long Keyword

Long is a primitive data type in Java. To initilize variables, we implement the long keyword. It can also be applied to techniques. A 64-bit two's complement integer can put...

3 minutes read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

Isomorphic String in Java

In this tutorial, we will understand what is meant by isomorphic String in java. We will also see a Java program to find out if the string is isomorphic or...

4 minutes read.

Java 9 Interface Private Method

Java 9 provides us the facility to include private methods inside the java interface. In java 8 and earlier versions, we are supposed to use only constant variables and abstract...

3 minutes read.

Java Null Keyword

Null is a term that is only used for literal values in Java. Although it appears to be a term, it is a literal opposite of true and false. Java's...

3 minutes read.

Minimum XOR value pair in Java

In this section, you will discuss about minimum XOR value pair in Java. The objective is to enforce a value that indicates the least XOR values of the two numbers from...

4 minutes read.

Difference between JIT and JVM in Java

In this tutorial, we will discuss the difference between JIT (Just In Time Compiler) and JVM (Java Virtual Machine) in Java. Before we move to the differences, let's understand what...

4 minutes read.

Multithreading Program in Java

Multithreading Program in Java: Before discussing multithreading, it is important to discuss threads. Threads are the most fundamental part of a process. A process can have one or more threads....

4 minutes read.