SlideShare a Scribd company logo
Annotations in Java with Example
In this article, we will learn about annotations in Java with syntax and examples.
Annotations in Java
The annotations represent the metadata i.e attached with the class, interface,
function, or fields to denote a few additional information. The Java compiler and the
JVM use this information during processing.
Annotations in Java provide added information that can be used as an alternative
option for XML and Java marker interfaces.These are not a part of the Java
program, yet they provide access to add metadata information into the course code.
Java introduced the concept of annotations from JDK5.
As mentioned earlier, annotations provide only supplemental details about a
program. It does not affect the operation of the code they annotate.
More on java annotations:
■ They start with the symbol ‘@’.
■ Annotations do not modify the action or executions of a compiled program
like its classes, variables, constructors, interfaces, methods, and many
more.
■ We cannot consider them as mere comments. This is because
annotations change the method a compiler treats a program.
Built-in Java annotations:
Before getting into custom or user-defined annotations, let us take a look at the
built-in Java annotations. Some of the below-given annotations are applied to Java
code and the rest are applied to other annotations.
Built-in Java Annotations in Java code:
■ @Override
■ @SuppressWarnings
■ @Deprecated
Built-in Java Annotations used in other annotations:
■ @Target
■ @Retention
■ @Inherited
■ @Documented
Built-in Java Annotations
Let us look at a brief description of the built-in annotations.
1. @Override:
The @Override annotation makes sure that the subclass method overrides the
parent class method. If this is not the case, it throws an error during compilation. It is
easy to get rid of careless mistakes like spelling mistakes by marking the @Override
annotation. It gives assurance that the method is overridden.
Sample program to implement @Overrided annotation:
class FirstCode{
void learnCourse(){
System.out.println("Learn Courses with FirstCode");
}}
class FirstCode2 extends FirstCode{
@Override
void learnCourse(){
System.out.println("Learn Java with FirstCode");
}}
class FirstCodeMain{
public static void main(String args[]){
FirstCode fc = new FirstCode2();
fc.learnCourse();
}
}
Output:
Compile Time Error
2. @SuppressWarnings:
This annotation suppresses the warning that the compiler issues.
Sample program to implement @SuppressWarning annotation:
import java.util.*;
class FirstCode{
@SuppressWarning("unchecked")
public static void main(String args[]){
ArrayList al = new ArrayList();
al.add("Java");
al.add(C++);
al.add("Python");
for(Object obj:al)
System.out.println(obj);
}
}
Output:
Now no warning at compile time
Once we remove the @SuppressWarning(“unchecked”) annotation, the compiler
shows a warning due to the usage of non-generic collections.
3. @Deprecated:
The @Deprecated annotation denotes that the particular method is deprecated, so
the compiler prints the warning message. It also notifies the user that it may be
eradicated in future versions. Therefore, it is good to avoid such methods.
Sample program to implement @deprecated annotation:
class FirstCode{
void course1(){
System.out.println("Learn Java with FirstCode");
}
@Deprecated
void course2(){
System.out.println("Learn C++ with FirstCode");
}}
class FirstCodeMain{
public static void main(String args[]){
Firstcode fc = new FirstCode();
fc.course2();
}
}
Output:
During compilation:Note: Test.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
During Runtime:
Learn C++ with FirstCode
4. @Documented:
It is a marker interface that informs a toll that an annotation is to be documented. As
the annotations are not provided in the ‘Javadoc’ comments, the @Documented
annotation takes care of it. It enables the tools like ‘Javadoc’ to include and process
the annotation that is given in the document.
5. @Target:
It is designed to use as an annotation to another annotation. @Target takes a
parameter that is a constant from the ElementType enumeration. It denotes the type
of declaration to which we can apply the annotation. The constants given in the
below table are given with the type of the declaration to which it corresponds.
Target Constant Annotations that can be applied to
ANNOTATION_TYPE Another annotation
CONSTRUCTOR Constructor
FIELD Field
LOCAL_VARIABLE Local variable
METHOD Method
PACKAGE Package
PARAMETER Parameter
TYPE Class, Interface, or enumeration
There is flexibility to mention one or more of these values in a @Targetannotation. In
such a case, we can mention them in the braces-delimited list. Eg: To denote an
annotation that applies only to the local variables and fields, we can mention the
@Target annotation as given below:
@Target({Element.Type.FIELD, ElementType.LOCAL_VARIABLE})
6. @Retention Annotation
This denotes where and how long the annotation is retent. This annotation can hold
three values:
SOURCE: Annotations that are retained at the source level and ignored by the
compiler.
CLASS: Annotations that are retained at the source level and ignored by the JVM.
RUNTIME: These annotations will be retained during the runtime.
7. @Inherited:
The @Inherited annotation is a marker that is used to declare annotations. It has
control over the annotations that are used in class declarations. @Inhertited causes
the annotation for a superclass to be inherited by a subclass.
Thus, when a request is made to the subclass and the annotation is absent in the
superclass and annotated with @Inherited, then that annotation will be returned.
@Inherited
@interface FirstCode { }
@interface FirstCode{ }
class Superclass{}
class Subclass extends Superclass{}
Java User-defined annotation:
User-defined annotations or custom annotations can annotate program elements.
These elements include the variables, constructors, methods, etc. They are applied
before the declaration of an element.
Syntax: Declaration of a user-defined annotation:
@interface NewAnnotation
Here, NewAnnotation is the name of the annotation.
Rules to declare user-defined annotation
1. AnnotationName is an interface.
2. The parameter should not be related to the method declarations and throw errors.
3. Null values cannot be assigned to these parameters. But they can have default
values.
4. And these default values are optional.
5. The return type of the method must be either primitive, string, enum, an array of
the primitive, class name, or class name type.
Types of Annotation in Java:
The annotations are classified into five main types:
1. Marker Annotation
2. Single-value Annotation
3. Full Annotation
4. Type Annotation
5. Repeating Annotation
1. Marker Annotation:
This annotation is no method or any data. The only purpose of this annotation is to
mark a declaration. As it has no members, simply determining if it is present or
absent is enough. @Override and @Deprecated are examples for marker
Annotation.
Eg: @interface NewAnnotation{}
2. Single-value annotation:
An annotation with just one method is known as a single-value annotation. It allows
a shorthand form of assigning a value to a variable. All we need to do is, mention the
value for the data member when we apply the annotation. We need not mention the
name of the data member. But to use this shorthand, the name of the member
should be a value.
Snippet to implement single-value annotation:
@interface NewAnnotation{
int value();
}
Snippet to implement single-annotation with default value:
@interface NewAnnotation{
int value() default 0;
}
Example to apply a single-value annotation:
@NewAnnotation(value=5)
3. Full Annotation or Multi-value annotation:
It is the annotation that consists of multiple values, data members, names, and
pairs.
Snippet to implement full annotation:
@interface NewAnnotation{
int value1();
String value2();
String value3();
}
}
Example to implement full annotation with default values:
@interface NewAnnotation{
int value1() default 1;
String value2() default "";
String value3() default "FirstCode";
}
Snippet to implement multi-value annotation:
@NewAnnotation(value1=5, value2="FirstCode",value3="Java")
4. Type Annotation:
We can apply this annotation where a type is present. For example, we can annotate
the return type of a method. These are stated annotated with @Target annotation.
Sample program to implement type annotation:
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target(ElementType.TYPE_USE)
@interface TypeAnnoPgm{}
public class FirstCode{
public static void main(String[] args) {
@TypeAnnoPgm String string = "This string is annotated with a type annotation";
System.out.println(string);
xyz();
}
static @TypeAnnoPgm int xyz() {
System.out.println("The return type of this function is annotated");
return 0;
}
}
Output:
This string is annotated with a type annotation
The return type of this function is annotated
5. Repeating Annotations:
As the name suggests, these annotations can be applied to the same item more
than once. To make the annotation repeatable, we must annotate it with the
@Repeatable annotation as defined in the java.lang.annotation package. The values
in the field mention the contained type for the repeatable annotation. The contained
is mentioned as an annotation whose value field is an array of the repeatable
annotation type.
To make an annotation repeatable, we must first create the container annotation.
And we must mention the annotation type as an argument to the @Repeatable
annotation.
Sample program to implement repeating annotations:
import java.lang.annotation.Annotation;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(MyRepeatedAnnos.class)
@interface Words
{
String word() default "FirstCode";
int value() default 0;
}
@Retention(RetentionPolicy.RUNTIME) // Container annotation creation
@interface MyRepeatedAnnos
{
Words[] value();
}
public class Main {
@Words(word = "First Course = Java", value = 1)
@Words(word = "Second Course = C++", value = 2)
public static void newMethod()
{
Main obj = new Main();
try {
Class c = obj.getClass();
Method m = c.getMethod("newMethod");
Annotation anno = m.getAnnotation(MyRepeatedAnnos.class);
System.out.println(anno);
}
catch (NoSuchMethodException e) {
System.out.println(e);
}
}
public static void main(String[] args) { newMethod(); }
}
Output:
@MyRepeatedAnnos(value={@Words(value=1, word=”First Course”),
@Words(value=2, word=”Second Course”)})
Building annotations in a real-world
scenario:
In reality, a Java programmer only needs to apply the annotation. It is not the task of
the programmer to create or access annotations. These tasks are performed by the
implementation provider. On behalf of the annotation, the Java compiler or the JVM
performs various extra operations too.
Sample program to implement User-defined
annotations:
package source;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@ interface MyAnnotation //user-defined annotations
{
String Developer() default "Programmer1";
String Expirydate();
} // will be retained at runtime
public class FirstCode
{
@MyAnnotation(Developer="Programmer1", Expirydate="01-12-2023")
void fun1()
{
System.out.println("Test method 1");
}
@MyAnnotation(Developer="Progammer2", Expirydate="01-10-2024")
void fun2()
{
System.out.println("Test method 2");
}
public static void main(String args[])
{
System.out.println("Learn Java with FirstCode");
}
}
Output:
Learn Java with FirstCode
Uses of Java Annotations:
1. Provides commands to the compiler:
The built-in annotations help the programmers in giving various instructions to the
compiler. For example, the @Override annotations instruct the compiler that the
annotated method is overriding the method.
2. Compile-time instructors:
It also provides compile-time instructions to the compiler that can be later used. The
programmers can use these as software build tools to generate XML files, code, etc.
3. Run-time instructions:
Defining annotations can also be helpful during runtime. We can access this using
Java Reflection.
Where can we implement Annotations in
Java?
We can implement annotations to classes, methods, fields, and interfaces in java.
Example:
@Override
void newMethod(){}
In this example, the annotation instructs the compiler that newMethod() is a method
that overrides. This method overrides (newMethod()) of its superclass.
Summary
This was all about annotations in java. Hope you enjoyed the article.

More Related Content

Similar to Annotations in Java with Example.pdf

Java Docs
Java DocsJava Docs
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
Gurpreet singh
 
a basic java programming and data type.ppt
a basic java programming and data type.ppta basic java programming and data type.ppt
a basic java programming and data type.ppt
GevitaChinnaiah
 
Lecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptxLecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptx
SaqlainYaqub1
 
Spring framework Controllers and Annotations
Spring framework   Controllers and AnnotationsSpring framework   Controllers and Annotations
Spring framework Controllers and Annotations
Anuj Singh Rajput
 
Java program structure
Java program structureJava program structure
Java program structure
shalinikarunakaran1
 
presentation of java fundamental
presentation of java fundamentalpresentation of java fundamental
presentation of java fundamental
Ganesh Chittalwar
 
Krazykoder struts2 annotations
Krazykoder struts2 annotationsKrazykoder struts2 annotations
Krazykoder struts2 annotationsKrazy Koder
 
c_programming.pdf
c_programming.pdfc_programming.pdf
c_programming.pdf
Home
 
Basics of java 2
Basics of java 2Basics of java 2
Basics of java 2Raghu nath
 
C Programming - Refresher - Part II
C Programming - Refresher - Part II C Programming - Refresher - Part II
C Programming - Refresher - Part II
Emertxe Information Technologies Pvt Ltd
 
CSL101_Ch1.ppt
CSL101_Ch1.pptCSL101_Ch1.ppt
CSL101_Ch1.ppt
kavitamittal18
 
CSL101_Ch1.pptx
CSL101_Ch1.pptxCSL101_Ch1.pptx
CSL101_Ch1.pptx
shivanka2
 
CSL101_Ch1.pptx
CSL101_Ch1.pptxCSL101_Ch1.pptx
CSL101_Ch1.pptx
Ashwani Kumar
 
Dot net programming concept
Dot net  programming conceptDot net  programming concept
Dot net programming concept
sandeshjadhav28
 
CIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaCIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in Java
Hamad Odhabi
 
C language 3
C language 3C language 3
C language 3
Arafat Bin Reza
 
International Journal of Engineering Research and Development (IJERD)
International Journal of Engineering Research and Development (IJERD)International Journal of Engineering Research and Development (IJERD)
International Journal of Engineering Research and Development (IJERD)
IJERD Editor
 

Similar to Annotations in Java with Example.pdf (20)

Java Annotation
Java AnnotationJava Annotation
Java Annotation
 
Java Docs
Java DocsJava Docs
Java Docs
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
a basic java programming and data type.ppt
a basic java programming and data type.ppta basic java programming and data type.ppt
a basic java programming and data type.ppt
 
Lecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptxLecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptx
 
Spring framework Controllers and Annotations
Spring framework   Controllers and AnnotationsSpring framework   Controllers and Annotations
Spring framework Controllers and Annotations
 
Java program structure
Java program structureJava program structure
Java program structure
 
presentation of java fundamental
presentation of java fundamentalpresentation of java fundamental
presentation of java fundamental
 
Krazykoder struts2 annotations
Krazykoder struts2 annotationsKrazykoder struts2 annotations
Krazykoder struts2 annotations
 
c_programming.pdf
c_programming.pdfc_programming.pdf
c_programming.pdf
 
Basics of java 2
Basics of java 2Basics of java 2
Basics of java 2
 
C Programming - Refresher - Part II
C Programming - Refresher - Part II C Programming - Refresher - Part II
C Programming - Refresher - Part II
 
CSL101_Ch1.ppt
CSL101_Ch1.pptCSL101_Ch1.ppt
CSL101_Ch1.ppt
 
CSL101_Ch1.ppt
CSL101_Ch1.pptCSL101_Ch1.ppt
CSL101_Ch1.ppt
 
CSL101_Ch1.pptx
CSL101_Ch1.pptxCSL101_Ch1.pptx
CSL101_Ch1.pptx
 
CSL101_Ch1.pptx
CSL101_Ch1.pptxCSL101_Ch1.pptx
CSL101_Ch1.pptx
 
Dot net programming concept
Dot net  programming conceptDot net  programming concept
Dot net programming concept
 
CIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in JavaCIS 1403 lab 3 functions and methods in Java
CIS 1403 lab 3 functions and methods in Java
 
C language 3
C language 3C language 3
C language 3
 
International Journal of Engineering Research and Development (IJERD)
International Journal of Engineering Research and Development (IJERD)International Journal of Engineering Research and Development (IJERD)
International Journal of Engineering Research and Development (IJERD)
 

More from SudhanshiBakre1

IoT Security.pdf
IoT Security.pdfIoT Security.pdf
IoT Security.pdf
SudhanshiBakre1
 
Top Java Frameworks.pdf
Top Java Frameworks.pdfTop Java Frameworks.pdf
Top Java Frameworks.pdf
SudhanshiBakre1
 
Numpy ndarrays.pdf
Numpy ndarrays.pdfNumpy ndarrays.pdf
Numpy ndarrays.pdf
SudhanshiBakre1
 
Float Data Type in C.pdf
Float Data Type in C.pdfFloat Data Type in C.pdf
Float Data Type in C.pdf
SudhanshiBakre1
 
IoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdfIoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdf
SudhanshiBakre1
 
Internet of Things – Contiki.pdf
Internet of Things – Contiki.pdfInternet of Things – Contiki.pdf
Internet of Things – Contiki.pdf
SudhanshiBakre1
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdf
SudhanshiBakre1
 
Node.js with MySQL.pdf
Node.js with MySQL.pdfNode.js with MySQL.pdf
Node.js with MySQL.pdf
SudhanshiBakre1
 
Collections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdfCollections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdf
SudhanshiBakre1
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
SudhanshiBakre1
 
Types of AI you should know.pdf
Types of AI you should know.pdfTypes of AI you should know.pdf
Types of AI you should know.pdf
SudhanshiBakre1
 
Streams in Node .pdf
Streams in Node .pdfStreams in Node .pdf
Streams in Node .pdf
SudhanshiBakre1
 
RESTful API in Node.pdf
RESTful API in Node.pdfRESTful API in Node.pdf
RESTful API in Node.pdf
SudhanshiBakre1
 
Top Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfTop Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdf
SudhanshiBakre1
 
Epic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdfEpic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdf
SudhanshiBakre1
 
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdfDjango Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
SudhanshiBakre1
 
Benefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfBenefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdf
SudhanshiBakre1
 
Epic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdfEpic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdf
SudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Semaphore in Java with Example.pdf
Semaphore in Java with Example.pdfSemaphore in Java with Example.pdf
Semaphore in Java with Example.pdf
SudhanshiBakre1
 

More from SudhanshiBakre1 (20)

IoT Security.pdf
IoT Security.pdfIoT Security.pdf
IoT Security.pdf
 
Top Java Frameworks.pdf
Top Java Frameworks.pdfTop Java Frameworks.pdf
Top Java Frameworks.pdf
 
Numpy ndarrays.pdf
Numpy ndarrays.pdfNumpy ndarrays.pdf
Numpy ndarrays.pdf
 
Float Data Type in C.pdf
Float Data Type in C.pdfFloat Data Type in C.pdf
Float Data Type in C.pdf
 
IoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdfIoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdf
 
Internet of Things – Contiki.pdf
Internet of Things – Contiki.pdfInternet of Things – Contiki.pdf
Internet of Things – Contiki.pdf
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdf
 
Node.js with MySQL.pdf
Node.js with MySQL.pdfNode.js with MySQL.pdf
Node.js with MySQL.pdf
 
Collections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdfCollections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdf
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
Types of AI you should know.pdf
Types of AI you should know.pdfTypes of AI you should know.pdf
Types of AI you should know.pdf
 
Streams in Node .pdf
Streams in Node .pdfStreams in Node .pdf
Streams in Node .pdf
 
RESTful API in Node.pdf
RESTful API in Node.pdfRESTful API in Node.pdf
RESTful API in Node.pdf
 
Top Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfTop Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdf
 
Epic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdfEpic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdf
 
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdfDjango Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
 
Benefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfBenefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdf
 
Epic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdfEpic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdf
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
 
Semaphore in Java with Example.pdf
Semaphore in Java with Example.pdfSemaphore in Java with Example.pdf
Semaphore in Java with Example.pdf
 

Recently uploaded

Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 

Recently uploaded (20)

Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 

Annotations in Java with Example.pdf

  • 1. Annotations in Java with Example In this article, we will learn about annotations in Java with syntax and examples. Annotations in Java The annotations represent the metadata i.e attached with the class, interface, function, or fields to denote a few additional information. The Java compiler and the JVM use this information during processing. Annotations in Java provide added information that can be used as an alternative option for XML and Java marker interfaces.These are not a part of the Java program, yet they provide access to add metadata information into the course code. Java introduced the concept of annotations from JDK5. As mentioned earlier, annotations provide only supplemental details about a program. It does not affect the operation of the code they annotate. More on java annotations: ■ They start with the symbol ‘@’. ■ Annotations do not modify the action or executions of a compiled program like its classes, variables, constructors, interfaces, methods, and many more. ■ We cannot consider them as mere comments. This is because annotations change the method a compiler treats a program. Built-in Java annotations:
  • 2. Before getting into custom or user-defined annotations, let us take a look at the built-in Java annotations. Some of the below-given annotations are applied to Java code and the rest are applied to other annotations. Built-in Java Annotations in Java code: ■ @Override ■ @SuppressWarnings ■ @Deprecated Built-in Java Annotations used in other annotations: ■ @Target ■ @Retention ■ @Inherited ■ @Documented Built-in Java Annotations Let us look at a brief description of the built-in annotations. 1. @Override: The @Override annotation makes sure that the subclass method overrides the parent class method. If this is not the case, it throws an error during compilation. It is easy to get rid of careless mistakes like spelling mistakes by marking the @Override annotation. It gives assurance that the method is overridden. Sample program to implement @Overrided annotation: class FirstCode{ void learnCourse(){ System.out.println("Learn Courses with FirstCode");
  • 3. }} class FirstCode2 extends FirstCode{ @Override void learnCourse(){ System.out.println("Learn Java with FirstCode"); }} class FirstCodeMain{ public static void main(String args[]){ FirstCode fc = new FirstCode2(); fc.learnCourse(); } } Output: Compile Time Error 2. @SuppressWarnings: This annotation suppresses the warning that the compiler issues. Sample program to implement @SuppressWarning annotation: import java.util.*; class FirstCode{ @SuppressWarning("unchecked") public static void main(String args[]){ ArrayList al = new ArrayList();
  • 4. al.add("Java"); al.add(C++); al.add("Python"); for(Object obj:al) System.out.println(obj); } } Output: Now no warning at compile time Once we remove the @SuppressWarning(“unchecked”) annotation, the compiler shows a warning due to the usage of non-generic collections. 3. @Deprecated: The @Deprecated annotation denotes that the particular method is deprecated, so the compiler prints the warning message. It also notifies the user that it may be eradicated in future versions. Therefore, it is good to avoid such methods. Sample program to implement @deprecated annotation: class FirstCode{ void course1(){ System.out.println("Learn Java with FirstCode"); } @Deprecated void course2(){
  • 5. System.out.println("Learn C++ with FirstCode"); }} class FirstCodeMain{ public static void main(String args[]){ Firstcode fc = new FirstCode(); fc.course2(); } } Output: During compilation:Note: Test.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details. During Runtime: Learn C++ with FirstCode 4. @Documented: It is a marker interface that informs a toll that an annotation is to be documented. As the annotations are not provided in the ‘Javadoc’ comments, the @Documented annotation takes care of it. It enables the tools like ‘Javadoc’ to include and process the annotation that is given in the document. 5. @Target: It is designed to use as an annotation to another annotation. @Target takes a parameter that is a constant from the ElementType enumeration. It denotes the type of declaration to which we can apply the annotation. The constants given in the below table are given with the type of the declaration to which it corresponds.
  • 6. Target Constant Annotations that can be applied to ANNOTATION_TYPE Another annotation CONSTRUCTOR Constructor FIELD Field LOCAL_VARIABLE Local variable METHOD Method PACKAGE Package PARAMETER Parameter TYPE Class, Interface, or enumeration There is flexibility to mention one or more of these values in a @Targetannotation. In such a case, we can mention them in the braces-delimited list. Eg: To denote an annotation that applies only to the local variables and fields, we can mention the @Target annotation as given below: @Target({Element.Type.FIELD, ElementType.LOCAL_VARIABLE}) 6. @Retention Annotation This denotes where and how long the annotation is retent. This annotation can hold three values:
  • 7. SOURCE: Annotations that are retained at the source level and ignored by the compiler. CLASS: Annotations that are retained at the source level and ignored by the JVM. RUNTIME: These annotations will be retained during the runtime. 7. @Inherited: The @Inherited annotation is a marker that is used to declare annotations. It has control over the annotations that are used in class declarations. @Inhertited causes the annotation for a superclass to be inherited by a subclass. Thus, when a request is made to the subclass and the annotation is absent in the superclass and annotated with @Inherited, then that annotation will be returned. @Inherited @interface FirstCode { } @interface FirstCode{ } class Superclass{} class Subclass extends Superclass{} Java User-defined annotation: User-defined annotations or custom annotations can annotate program elements. These elements include the variables, constructors, methods, etc. They are applied before the declaration of an element. Syntax: Declaration of a user-defined annotation: @interface NewAnnotation
  • 8. Here, NewAnnotation is the name of the annotation. Rules to declare user-defined annotation 1. AnnotationName is an interface. 2. The parameter should not be related to the method declarations and throw errors. 3. Null values cannot be assigned to these parameters. But they can have default values. 4. And these default values are optional. 5. The return type of the method must be either primitive, string, enum, an array of the primitive, class name, or class name type. Types of Annotation in Java: The annotations are classified into five main types: 1. Marker Annotation 2. Single-value Annotation 3. Full Annotation 4. Type Annotation 5. Repeating Annotation 1. Marker Annotation:
  • 9. This annotation is no method or any data. The only purpose of this annotation is to mark a declaration. As it has no members, simply determining if it is present or absent is enough. @Override and @Deprecated are examples for marker Annotation. Eg: @interface NewAnnotation{} 2. Single-value annotation: An annotation with just one method is known as a single-value annotation. It allows a shorthand form of assigning a value to a variable. All we need to do is, mention the value for the data member when we apply the annotation. We need not mention the name of the data member. But to use this shorthand, the name of the member should be a value. Snippet to implement single-value annotation: @interface NewAnnotation{ int value(); } Snippet to implement single-annotation with default value: @interface NewAnnotation{ int value() default 0; } Example to apply a single-value annotation: @NewAnnotation(value=5) 3. Full Annotation or Multi-value annotation:
  • 10. It is the annotation that consists of multiple values, data members, names, and pairs. Snippet to implement full annotation: @interface NewAnnotation{ int value1(); String value2(); String value3(); } } Example to implement full annotation with default values: @interface NewAnnotation{ int value1() default 1; String value2() default ""; String value3() default "FirstCode"; } Snippet to implement multi-value annotation: @NewAnnotation(value1=5, value2="FirstCode",value3="Java") 4. Type Annotation: We can apply this annotation where a type is present. For example, we can annotate the return type of a method. These are stated annotated with @Target annotation. Sample program to implement type annotation:
  • 11. import java.lang.annotation.ElementType; import java.lang.annotation.Target; @Target(ElementType.TYPE_USE) @interface TypeAnnoPgm{} public class FirstCode{ public static void main(String[] args) { @TypeAnnoPgm String string = "This string is annotated with a type annotation"; System.out.println(string); xyz(); } static @TypeAnnoPgm int xyz() { System.out.println("The return type of this function is annotated"); return 0; } } Output: This string is annotated with a type annotation The return type of this function is annotated 5. Repeating Annotations: As the name suggests, these annotations can be applied to the same item more than once. To make the annotation repeatable, we must annotate it with the @Repeatable annotation as defined in the java.lang.annotation package. The values in the field mention the contained type for the repeatable annotation. The contained
  • 12. is mentioned as an annotation whose value field is an array of the repeatable annotation type. To make an annotation repeatable, we must first create the container annotation. And we must mention the annotation type as an argument to the @Repeatable annotation. Sample program to implement repeating annotations: import java.lang.annotation.Annotation; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Method; @Retention(RetentionPolicy.RUNTIME) @Repeatable(MyRepeatedAnnos.class) @interface Words { String word() default "FirstCode"; int value() default 0; } @Retention(RetentionPolicy.RUNTIME) // Container annotation creation @interface MyRepeatedAnnos { Words[] value();
  • 13. } public class Main { @Words(word = "First Course = Java", value = 1) @Words(word = "Second Course = C++", value = 2) public static void newMethod() { Main obj = new Main(); try { Class c = obj.getClass(); Method m = c.getMethod("newMethod"); Annotation anno = m.getAnnotation(MyRepeatedAnnos.class); System.out.println(anno); } catch (NoSuchMethodException e) { System.out.println(e); } } public static void main(String[] args) { newMethod(); } } Output: @MyRepeatedAnnos(value={@Words(value=1, word=”First Course”), @Words(value=2, word=”Second Course”)})
  • 14. Building annotations in a real-world scenario: In reality, a Java programmer only needs to apply the annotation. It is not the task of the programmer to create or access annotations. These tasks are performed by the implementation provider. On behalf of the annotation, the Java compiler or the JVM performs various extra operations too. Sample program to implement User-defined annotations: package source; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Documented @Retention(RetentionPolicy.RUNTIME) @ interface MyAnnotation //user-defined annotations { String Developer() default "Programmer1"; String Expirydate(); } // will be retained at runtime public class FirstCode { @MyAnnotation(Developer="Programmer1", Expirydate="01-12-2023")
  • 15. void fun1() { System.out.println("Test method 1"); } @MyAnnotation(Developer="Progammer2", Expirydate="01-10-2024") void fun2() { System.out.println("Test method 2"); } public static void main(String args[]) { System.out.println("Learn Java with FirstCode"); } } Output: Learn Java with FirstCode Uses of Java Annotations: 1. Provides commands to the compiler: The built-in annotations help the programmers in giving various instructions to the compiler. For example, the @Override annotations instruct the compiler that the annotated method is overriding the method.
  • 16. 2. Compile-time instructors: It also provides compile-time instructions to the compiler that can be later used. The programmers can use these as software build tools to generate XML files, code, etc. 3. Run-time instructions: Defining annotations can also be helpful during runtime. We can access this using Java Reflection. Where can we implement Annotations in Java? We can implement annotations to classes, methods, fields, and interfaces in java. Example: @Override void newMethod(){} In this example, the annotation instructs the compiler that newMethod() is a method that overrides. This method overrides (newMethod()) of its superclass. Summary This was all about annotations in java. Hope you enjoyed the article.