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

More Related Content

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

Programming style guideline very good
Programming style guideline very goodProgramming style guideline very good
Programming style guideline very good
Dang Hop
 
Java Annotation
Java AnnotationJava Annotation
Java Annotation
karthik.tech123
 
Java Docs
Java DocsJava Docs
Java Docs
Pallavi Srivastava
 
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
 
Programming with Java by Faizan Ahmed & Team
Programming with Java by Faizan Ahmed & TeamProgramming with Java by Faizan Ahmed & Team
Programming with Java by Faizan Ahmed & Team
FaizanAhmed272398
 
Introduction to java programming with Fundamentals
Introduction to java programming with FundamentalsIntroduction to java programming with Fundamentals
Introduction to java programming with Fundamentals
rajipe1
 
CSL101_Ch1.ppt Computer Science
CSL101_Ch1.ppt          Computer ScienceCSL101_Ch1.ppt          Computer Science
CSL101_Ch1.ppt Computer Science
kavitamittal18
 
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
 
Mobile computing for Bsc Computer Science
Mobile computing for Bsc Computer ScienceMobile computing for Bsc Computer Science
Mobile computing for Bsc Computer Science
ReshmiGopinath4
 
Programming with Java - Essentials to program
Programming with Java - Essentials to programProgramming with Java - Essentials to program
Programming with Java - Essentials to program
leaderHilali1
 
Java program structure
Java program structureJava program structure
Java program structure
shalinikarunakaran1
 
Presentation on programming language on java.ppt
Presentation on programming language on java.pptPresentation on programming language on java.ppt
Presentation on programming language on java.ppt
HimambashaShaik
 
presentation of java fundamental
presentation of java fundamentalpresentation of java fundamental
presentation of java fundamental
Ganesh Chittalwar
 
programming for problem solving in C and C++.pptx
programming for problem solving in C and C++.pptxprogramming for problem solving in C and C++.pptx
programming for problem solving in C and C++.pptx
BamaSivasubramanianP
 
Krazykoder struts2 annotations
Krazykoder struts2 annotationsKrazykoder struts2 annotations
Krazykoder struts2 annotations
Krazy 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 2
Raghu 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
 
Programming style guideline very good
Programming style guideline very goodProgramming style guideline very good
Programming style guideline very good
Dang Hop
 
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
 
Programming with Java by Faizan Ahmed & Team
Programming with Java by Faizan Ahmed & TeamProgramming with Java by Faizan Ahmed & Team
Programming with Java by Faizan Ahmed & Team
FaizanAhmed272398
 
Introduction to java programming with Fundamentals
Introduction to java programming with FundamentalsIntroduction to java programming with Fundamentals
Introduction to java programming with Fundamentals
rajipe1
 
CSL101_Ch1.ppt Computer Science
CSL101_Ch1.ppt          Computer ScienceCSL101_Ch1.ppt          Computer Science
CSL101_Ch1.ppt Computer Science
kavitamittal18
 
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
 
Mobile computing for Bsc Computer Science
Mobile computing for Bsc Computer ScienceMobile computing for Bsc Computer Science
Mobile computing for Bsc Computer Science
ReshmiGopinath4
 
Programming with Java - Essentials to program
Programming with Java - Essentials to programProgramming with Java - Essentials to program
Programming with Java - Essentials to program
leaderHilali1
 
Presentation on programming language on java.ppt
Presentation on programming language on java.pptPresentation on programming language on java.ppt
Presentation on programming language on java.ppt
HimambashaShaik
 
presentation of java fundamental
presentation of java fundamentalpresentation of java fundamental
presentation of java fundamental
Ganesh Chittalwar
 
programming for problem solving in C and C++.pptx
programming for problem solving in C and C++.pptxprogramming for problem solving in C and C++.pptx
programming for problem solving in C and C++.pptx
BamaSivasubramanianP
 
Krazykoder struts2 annotations
Krazykoder struts2 annotationsKrazykoder struts2 annotations
Krazykoder struts2 annotations
Krazy 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 2
Raghu nath
 

More from SudhanshiBakre1 (20)

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
 
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
 
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
 
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
 
Ad

Recently uploaded (20)

Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
BookNet Canada
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...
BookNet Canada
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
BookNet Canada
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...
BookNet Canada
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
Ad

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.
  翻译: