Training Outcomes Within Your Budget!

We ensure quality, budget-alignment, and timely delivery by our expert instructors.

Share this Resource

Table of Contents

Java Annotations

Java Annotations are an indispensable feature of Java. They act as metadata for the program, i.e., they offer extra information about the program/code by not being a part of the code. It is used as an alternative to eXtensible Markup Language (XML). The first rule of using annotations is to begin one with '@'.  

Based on the reports by Analytics Insight, one of the top 10 programming languages in the world is Java, with 8.2 million active developers. The multitude of features in Java, like Java Annotations, helps it sustain its popularity. Explore this blog on Java Annotation- What it is, it's different types, how to use them, their working, syntax and examples. Click here to start learning today! 

Table of Contents

1) Functioning of Java Annotations 

2) Types of Java Annotations

   a) Marker annotation

   b) Single-value annotation

   c) Multi-value annotation 

3) Built-in annotations vs custom annotations  

4) Conclusion 

Functioning of Java Annotations 

Java Annotations help in producing extra information about a program. The key benefit of using them is that they offer directions to the compiler. They are also equipped to provide instructions on the compilation-time as well. Let's explore the functioning of Java Annotations now with an example: 
 

public class MyClass
{
@Deprecated
public void myMethod()
{
System.out.println("This method is deprecated.");
}
public static void main(String[] args)
{
MyClass obj = new MyClass();
obj.myMethod();
}
}


In the above example of Functioning Java Annotation, you start with the @Deprecated annotation in Java. The @Deprecated annotation is a built-in Java annotation that indicates that the annotated element (in this case, the ‘myMethod’ method) should no longer be used and will likely be removed in a future version of the API. 

Output: 

This method is deprecated. 

Get introduced to the concepts of Swing and improve your understanding of Java with the Java Swing Development Training course. Sign up now! 

Types of Java Annotations 

Java Annotations are of three types – marker annotation, single-value annotation, and multi-value annotation. Let's understand these three types of annotations in detail with the help of examples: 

Marker annotation 

Marker annotations do not have a method, and they carry zero elements and zero data with them and are used to mark items in a program. The syntax for creating a marker annotation in Java is as follows: 

public @interface MarkerAnnotation { 

This declares a new annotation type named 'MarkerAnnotation' that can be used to mark other Java elements. To use this marker annotation, place it before the element that you want to mark like this: 
 

@MarkerAnnotation
public class MyClass
{
// class definition
}


Here, '@MarkerAnnotation' marks the 'MyClass' class with the 'MarkerAnnotation' metadata.

Single-value annotation

As the name suggests, single-value annotations contain a single method. Since it has only one member, its value must be specified only when the annotation is applied. The syntax of using a single-value annotation is as follows:

@AnnotationName(value)

Here, 'AnnotationName' is the annotation's name, and value is the value assigned to the annotation. 

For example, take a custom annotation called 'Author' to annotate a method with the author's name. You can define this annotation with a single value as follows:

public @interface Author {

    String value();

}

It defines the 'Author' annotation with a single value of type String. You can then use this annotation to annotate a method as follows:
 

@Author("John Doe")
public void myMethod()
{
//method code here
}


It annotates the 'myMethod()' with the 'Author' annotation and assigns the value "John Doe" to the annotation's 'value' attribute.

Multi-value annotation

Multi-value annotations carry more than one method. They are also known as full Java annotations and carry multiple values, members, etc. The syntax for multi-value annotations is as follows:  

public @interface MyAnnotation

{

    String[] value();

}

Here, 'MyAnnotation' is a custom annotation with a single parameter named 'value'. The 'value' parameter is defined as an array of 'String' values. To use this annotation with multiple values, you can specify the values as an array of strings like this:
 

@MyAnnotation(value={"value1", "value2", "value3"})
public class MyClass
{
// class implementation here
}


In this example, 'MyClass' is annotated with 'MyAnnotation' and specifies the values of the 'value' parameter as an array of strings. 

Javascript Unit Testing Training With Jasmine
 

Built-in annotations vs custom annotations 

Based on their source of origin, annotations are built-in or custom-made. While Java provides built-in Java Annotations, users can design and implement custom annotations. Let’s explore both these Java Annotations in detail with examples. 

Built-in annotation 


The five built-in annotations in Java

As mentioned above, built-in annotations are those provided by Java. They are also known as predefined or standard annotations. There are five built-in annotations in Java, and they are as follows: 

a) @Deprecated: @Deprecated is a marker Java Annotation that shows that a method or class is outdated. There is a marked difference between using the @deprecated tag and @Deprecated annotation. The tag is used for documentation, while the annotation is used for runtime reflection. Here is an example of using the @Deprecated annotation: 
 

public class MyClass
{
/** * This method is deprecated and should no longer be used.
* Use myNewMethod() instead.
*/
@Deprecated
public void myOldMethod()
{
System.out.println("This is my old method.");
}
public void myNewMethod() { System.out.println("This is my new method.");
}
}


In the above example, the 'myOldMethod()' is marked as deprecated using the '@Deprecated' annotation, and a comment is provided to suggest that 'myNewMethod()' should be used instead. Now, if you try to use 'myOldMethod()' in your code, you will get a warning indicating that it is deprecated: 

MyClass obj = new MyClass(); 

obj.myOldMethod(); // Warning: 'myOldMethod()' is deprecated 

Output: 

This is my old method. 

b) @SuppressWarnings: @SuppressWarnings is a Java Annotation that informs the compilers not to heed the warnings they produce. Any type of declaration can be on its receiving end. Here is an example of using @SuppressWarnings to suppress a warning that occurs when casting an object to a specific type: 
 

public class Example
{
public static void main(String[] args)
{
// Creating an object of type Object
Object obj = "Hello, World!";
// Casting obj to type String, which generates a warning @SuppressWarnings("unchecked")
String str = (String) obj;
// Printing the value of str
System.out.println(str);
}
}


In the above example, an object 'obj' of type 'Object' is created, and then you try to cast it to type 'String'. This generates a warning because the compiler cannot guarantee that the object is of type String. The '@SuppressWarnings' annotation is used with the "unchecked" parameter to suppress this warning, which tells the compiler to ignore any warnings related to unchecked conversions. 

Output: 

Hello, World! 

c) @Override: @Override is another marker annotation, and it is used on methods. The condition of using @Override is that @Override-annotated methods must, in turn, override one from a superclass. Failure to do so will result in a compile-time error. Here is an example of using the @Override annotation: 
 

public class Animal
{
public void makeSound() { System.out.println("The animal makes a sound");
}
}
public class Cat extends Animal
{ @Override
public void makeSound()
{
System.out.println("Meow");
}
}
public class Main { public static void main(String[] args)
{
Animal animal = new Animal();
animal.makeSound(); // Output: The animal makes a sound
Cat cat = new Cat();
cat.makeSound(); // Output: Meow
}
}


In this example, an Animal class with a 'makeSound()' method is taken, which prints "The animal makes a sound". We also have a 'Cat' class that extends 'Animal' and overrides the 'makeSound()' method with its own implementation that prints "Meow".  

In the 'Main' class, an instance of 'Animal' is created, and then you call its 'makeSound()' method, which outputs "The animal makes a sound". An instance of 'Cat' is also created, and you call its 'makeSound()' method, which outputs "Meow".  

The @Override annotation is used before the 'makeSound()' method in the 'Cat' class to indicate that it is overriding the 'makeSound()' method in the superclass (Animal). Suppose you accidentally mistake the method signature, such as misspelling the method name or using the wrong parameter types. In that case, the @Override annotation will cause a compilation error, informing you that you must fix your code. 

Output: 

The animal makes a sound 

Meow 

Improve your understanding of JavaScript operators and control statements. Enrol for the JavaScript for Beginners Course now! 

d) @FunctionaInterface: Functional interfaces in Java Annotations are interfaces that have a single abstract method. These interfaces are used by representing their interfaces with the @FunctionaInterface annotation. Here is an example of using the @FunctionalInterface annotation: 
 

@FunctionalInterface
interface Calculator
{
int calculate(int x, int y);
}
public class Main
{
public static void main(String[] args)
{
Calculator addition = (x, y) -> x + y;
Calculator subtraction = (x, y) -> x - y;
int result1 = addition.calculate(10, 5);
int result2 = subtraction.calculate(10, 5);
System.out.println("10 + 5 = " + result1); // Output: 10 + 5 = 15
System.out.println("10 - 5 = " + result2); // Output: 10 - 5 = 5
}
}


In this example, a functional interface called 'Calculator' is defined with a single abstract method called 'calculate', which takes two integer parameters and returns an integer result. Then, the '@FunctionalInterface' annotation indicates that this interface is used as a functional interface.  

In the 'main' method, two instances of the 'Calculator' interface are created using lambda expressions to define the behaviour of the 'calculate' method. Then, these instances are used to perform addition and subtraction operations on two integers. 

Output: 

10 + 5 = 15 

10 - 5 = 5 

e) @SafeVarargs: The @SafeVarargs annotation is used on methods that take the varargs parameter. The objective of the annotation is to prevent the method from performing harmful operations on the varargs parameters. This annotation can be applied to final methods, static methods, and constructors. Here is an example of using the @SafeVarargs annotation: 
 

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Concatenator
{
@SafeVarargs
public static List concatenate(List... lists)
{
List result = new ArrayList<>();
for (List list : lists)
{
result.addAll(list);
}
return result;
}
public static void main(String[] args)
{
List list1 = Arrays.asList("foo", "bar");
List list2 = Arrays.asList("baz", "qux");
List list3 = Arrays.asList("quux", "corge");
List concatenated = concatenate(list1, list2, list3);
System.out.println(concatenated); // prints [foo, bar, baz,
qux, quux, corge]
}
}


In this example, the '@SafeVarargs' annotation is used to suppress the "unchecked generic array creation" warning that the compiler would otherwise issue due to the creation of the 'List[]' parameter array. By using the '@SafeVarargs' annotation, we're telling the compiler that we're confident that the method is safe to use with variable arguments of generic types. 

Output: 

[foo, bar, baz, qux, quux, corge] 

Custom annotation 
 

Flowchart of Annotations

Custom annotation is a user-defined annotation, i.e., it is not provided by Java. One of the points to note while using custom annotation is that the method must return the data types from a specified set. This set includes primitive data types, strings, classes, etc.   

Custom annotations are allowed to assign a default value to the method, and the method shouldn't have any parameter. Another critical point about is that it should not have any throws clauses. Always remember to attach the '@' symbol before the interface keyword for defining the annotation. 

Conclusion 

Java Annotations provide valuable metadata that offers bound directions to the compiler. It is one of the useful features of Java. We hope this blog on Java Annotations has helped you learn more about annotations, their types, and how to use them with the help of the multiple examples provided. 

Learn about the basics of Java alongside its plethora of features be signing up for our Java Programming course now!

Frequently Asked Questions

Upcoming Programming & DevOps Resources Batches & Dates

Date

building Java Programming

Get A Quote

WHO WILL BE FUNDING THE COURSE?

cross

OUR BIGGEST SPRING SALE!

Special Discounts

red-starWHO WILL BE FUNDING THE COURSE?

close

close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.

close

close

Press esc to close

close close

Back to course information

Thank you for your enquiry!

One of our training experts will be in touch shortly to go overy your training requirements.

close close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.