0% found this document useful (0 votes)
13 views81 pages

Module 01

The document covers advanced Java and J2EE concepts, including enumerations, autoboxing, annotations, collections, string handling, servlets, and JDBC. It explains the fundamentals of each topic, provides examples, and outlines course objectives such as demonstrating the use of JDBC and adapting servlets for server-side programming. The content is structured into modules that detail various Java features and their applications.

Uploaded by

Santhosh Sgrao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views81 pages

Module 01

The document covers advanced Java and J2EE concepts, including enumerations, autoboxing, annotations, collections, string handling, servlets, and JDBC. It explains the fundamentals of each topic, provides examples, and outlines course objectives such as demonstrating the use of JDBC and adapting servlets for server-side programming. The content is structured into modules that detail various Java features and their applications.

Uploaded by

Santhosh Sgrao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 81

Advanced Java and J2EE

1
MODULE-1
Enumerations, Autoboxing and Annotations(metadata): Enumerations, Enumeration fundamentals, the values()
and value Of() Methods, java enumerations are class types, enumerations Inherits Enum, example, type
wrappers, Autoboxing, Autoboxing and Methods, Autoboxing/Unboxing occurs in Expressions,
Autoboxing/Unboxing, Boolean and character values, Autoboxing/Unboxing helps prevent errors, A word of
Warning. Annotations, Annotation basics, specifying retention policy, Obtaining Annotations at run time by
use of reflection, Annotated element Interface, Using Default values, Marker Annotations, Single Member
annotations, Built-In annotations.

MODULE-2
The collections and Framework: Collections Overview, Recent Changes to Collections, The Collection
Interfaces, The Collection Classes, Accessing a collection Via an Iterator, Storing User Defined Classes in
Collections, The Random Access Interface, Working With Maps, Comparators, The Collection Algorithms,
Why Generic Collections?, The legacy Classes and Interfaces, Parting Thoughts on Collections.

MODULE-3
String Handling :The String Constructors, String Length, Special String Operations, String Literals, String
Concatenation, String Concatenation with Other Data Types, String Conversion and toString( ) Character
Extraction, charAt( ), getChars( ), getBytes( ) toCharArray(), String Comparison, equals( ) and
equalsIgnoreCase( ), regionMatches( ) startsWith( ) and endsWith( ), equals( ) Versus == , compareTo( )
2
Searching Strings,
Modifying a String, substring( ), concat( ), replace( ), trim( ), Data Conversion Using valueOf( ), Changing the
Case of Characters Within a String, Additional String Methods, StringBuffer , StringBuffer Constructors,
length( ) and capacity( ), ensureCapacity( ), setLength( ), charAt( ) and setCharAt( ), getChars( ),append( ),
insert( ), reverse( ), delete( ) and deleteCharAt( ), replace( ), substring( ), Additional StringBuffer Methods,
StringBuilder .

MODULE-4
Background; The Life Cycle of a Servlet; Using Tomcat for Servlet Development; A simple Servlet; The
Servlet API; The Javax.servlet Package; Reading Servlet Parameter; The Javax.servlet.http package; Handling
HTTP Requests and Responses; Using Cookies; Session Tracking. Java Server Pages (JSP): JSP, JSP Tags,
Tomcat, Request String, User Sessions, Cookies, Session Objects

MODULE 5

The Concept of JDBC; JDBC Driver Types; JDBC Packages; A Brief Overview of the JDBC process;
Database Connection; Associating the JDBC/ODBC Bridge with the Database; Statement Objects; ResultSet;
Transaction Processing; Metadata, Data types; Exceptions
Course objectives:
 Explain the need for advanced Java concepts like Enumerations and Collections
 Define the working of Strings in Java
 Demonstrate the use of JDBC to access database through Java Programs
 Adapt servlets to build server-side programs
Chapter 1
Enumerations,
Autoboxing and
Annotations(metadata)
Enumeration
Enumerations, or enums, in Java are a special data type that enables a
variable to be a set of predefined constants. They are commonly used when you
have a fixed set of related values, such as days of the week, months, directions, or
status codes. Enums make the code more readable and safer by replacing integer or
string constants with a type-safe mechanism.
• Enumerations included in JDK 5. An enumeration is a list of named constants. It
is similar to final variables.
• An enumeration defines a class type in Java. By making enumerations into
classes, so it can have constructors, methods, and instance variables.
• An enumeration is created using the enum keyword.
• Enum in java is a data type that contains fixed set of constants.
• They can be useful in setting a scope of values for a particular object.

6
• Each declared value is an instance of the enum class.
• Enums are implicitly public, static, and final.
• enums extend java.lang.Enum and implement java.lang.Comparable.
• Supports equals, “==”, compareTo, ordinal, etc.
• Enums override toString() and provide valueOf(…), name().

Points to remember for Java Enum


•enum improves type safety.
•enum can be easily used in switch.
•enum can be traversed.
•enum can have fields, constructors and methods.
•enum may implement many interfaces but cannot extend any class because it
internally extends Enum class.
7
Enumeration fundamentals :
enumeration is a special kind of class that includes a list of constant values. The values in the
enumeration list define the values an object can have

Creating Enumerations
• When creating an enumeration list, we don't use the keyword class and when you create list,
enumeration object, we don't use the keyword new.
• To create an enumeration list, we need to import java.util.Enumeration.
• An enumeration is created using the enum keyword followed by the variable Name we want
associated with the list.

Syntax:
public enum variableName {
ITEM1
ITEM2
ITEMN
} 8
example: public enum Gender {
MALE, FEMALE, UNKNOWN
}
 Creating an enumeration object
To declare an enumeration object, use the variable name associated with the list
followed by the name of the object.
Syntax:
variableName object;
example: Gender gen;
 Assigning values to the enumeration object
To assign values to the object, must use the enumeration name, a dot and one of
the values in the list.
Syntax:
object = variableName.ITEM;
example: Gender gen=Gender.MALE; 9
 Assigning default values

We can also assign the default value to list of item in enumeration class. In
order to assign default value to list in enumeration class, should contain the
enumeration constructor, fields, methods.
example:
public enum Gender {
MALE(1), FEMALE(2), UNKNOWN(0)
}
Simple Program: {
enum Gender { Gender S;
MALE, FEMALE, UNKNOWN S=Gender.MALE;
} System.out.println("Gender IS="+S);
class Enu { }
public static void main( String args[] ) }

OUTPUT:
Gender IS=MALE 10
Java enum in CONTROL STATEMENTS:

Control statements are the statements which alter the flow of execution and
provide better control to the programmer on the flow of execution. In Java control
statements are categorized into selection control statements, iteration control
statements and jump control statements.

Java’s Selection Statements:


These statements allow us to control the flow of program execution based on
condition.
Types of control statements are:
1)Simple if Statement
2)if else
3)else if
4)switch
11
enum Gender {
MALE, FEMALE, UNKNOWN;
}
class cont {
public static void main( String args[] )
{
Gender s=Gender.FEMALE;
if(s==Gender.MALE)
System.out.println("Both are not equal");
}
}

Assessment 01: To find Smallest of given number.


12
program 1:
enum Gender { if(s==Gender.MALE)
MALE, FEMALE, UNKNOWN; System.out.println("both are equal");
} else
class cont { System.out.println("Both are not equal");
public static void main( String args[] ) }
{ }
Gender s=Gender.FEMALE;
output: Both are not equal
13
Assessment 01: To find Smallest of two numbers
3) else if: This statement perform a task depending on whether a condition is true
or false.

program Gender s=Gender.FEMALE;


enum Gender { if(s==Gender.MALE)
MALE, FEMALE, UNKNOWN; System.out.println("both are equal");
} else if (s==Gender.UNKNOWN)
class cont System.out.println("Both are equal");
{ else
public static void main( String args[] ) System.out.println("Both are not equal");
{ }
} 14
4. Switch Statement:
When there are several options and we have to choose only one option from the
available ones, we can use switch statement.

15
program 1: To check the gender of person

enum Gender {
switch(s)
MALE, FEMALE, UNKNOWN;
{
}
case MALE:System.out.print("Gender is male");
break;
class cont
case FEMALE:System.out.print("Gender is female");
{
break;
public static void main( String
case UNKNOWN:System.out.print("Gender is unknown");
args[] )
{
break;
Gender s=Gender.FEMALE;
default:System.out.print("NON of these");
}
} }

16
The values() and valueOf() Methods:
There are some methods that you can use that are part of the enumeration class, these
methods include :
1. values()
2. valueOf()
1.Values():
Method returns an array that contains a list of the enumeration constants
values() returns the values in the enumeration and stores them in an array. We can
process the array with a foreach loop.

17
Program 1: To print the list of day of enumeration class

enum Days {
mon, tue, wed, thu, fri, sat, sun;
}
class cont
{
public static void main( String args[] )
{
Days d[]=Days.values(); output:
for(Days d1:d) today day is=mon
System.out.println("today day is:"+d1); today day is=tue
} today day is=wed
} today day is=thu
today day is=fri
today day is=sat
Try this program 2:TO find no of days in month today day is=sun 18
2. ValueOf():
• Method returns the enumeration constant whose value corresponds to the string
passed in str.
• Method takes a single parameter of the constant name to retrieve and returns the
constant from the enumeration, if it exists.

19
Note: An enumeration cannot inherit another class and an enum cannot be a superclass for
other class. 20
Java Enumerations Are Class Types

• Enumerations in Java can have methods, members and constructors just as any
other class can have.
• Each enumeration constant is an object of its enumeration type.
• Thus, when you define a constructor for an enum, the constructor is called when
each enumeration constant is created.
• Also, each enumeration constant has its own copy of any instance variables
defined by the enumeration.
• The enum constants have initial value that starts from 0, 1, 2, 3 and so on. But we
can initialize the specific value(default value) to the enum constants by defining
fields and constructors.

21
Program:
enum Value {
A(10), B(20), C(30);
int a;
int getValue(){ return a;}
Gender(int value)
{
this.a=value;
} }
class Enu
{
public static void main( String args[] )
{
System.out.println(" value of A
IS="+Value.A.getValue());
}
}
output: Value of A Is= 10

22
Enumerations Inherit Enum:

1.Ordinal():
•Returns the value of the constant's position in the list (the first constant has a position
of zero).
•The ordinal value provides the order of the constant in the enumeration, starting with
0
Example
WeekDays wd = WeekDays.MONDAY;
System.out.println(wd.ordinal());
23
program: To find index of Enum List.

enum Days {
mon, tue, wed;
}
class cont
{
public static void main( String args[] )
{
Days wd = Days.mon;
System.out.println("Index of list:"+wd.ordinal());
}
}
output: Index of list:0

24
Program 2: Using foreach loop

enum Days {
mon, tue, wed;
}
class cont
{
public static void main( String args[] )
{
Days wd[] = Days.values();
for(Days w:wd)
System.out.println("Index of list:"+w.ordinal()); output:
} Index of list:0
} Index of list:1
Index of list:2
25
2. CompareTo():
• Compares the ordinal value of the two enumeration objects.
• If the object invoking the method has a value less than the object being passed,
a negative number is returned.
• It the two objects have the same oridnal number, a zero is returned.
• If the invoking object has a greater value than the one being passed, a positive
number is returned.

program: To find order of day


enum Days {
mon, tue, wed;
}
class cont
{ 26
public static void main( String args[] )
{
Days d1,d2,d3;
d1=Days.mon;
d2=Days.tue;
d3=Days.wed;
if(d1.compareTo(d2)<0)
System.out.println("mon comes before tue");
if(d2.compareTo(d3)<0)
System.out.println("Tue comes before wed");
System.out.println("wed comes after tue");
}
}
output:
mon comes before tue
Tue comes before wed
wed comes after tue 27
3. Equals():
• Method returns true if the specified object is equal to this enum constant.
public final Boolean equals(Object other)
• Where other − This is the object to be compared for equality with this object.
• This method returns true if the specified object is equal to this enum constant

Example:
enum Days { d1=Days.mon;
mon, tue, wed; d2=Days.tue;
} d3=Days.wed;
class cont System.out.println(d1.equals(d2));
{ System.out.println(d2.equals(d3));
public static void main( String args[] ) System.out.println(d2.equals(d2));
{ } } Output:
false
Days d1,d2,d3; false
true 28
4. ToString():
• Method returns the name of this enum constant, as contained in the declaration.
public String toString()
• This method returns the name of this enum constant.

Example:
Days d1,d2,d3;
enum Days { d1=Days.mon;
mon, tue, wed; d2=Days.tue;
} d3=Days.wed;
class cont System.out.println(d1.toString());
{ System.out.println(d2. toString());
public static void main( String args[] ) System.out.println(d3. toString());
{ }
}
Output: mon tue wed
29
Type wrappers:
• Java uses primitive types (also called simple types), such as int or double, to
hold the basic data types supported by the language.
• Instead of primitive types if objects are used everywhere for even simple
calculations then performance overhead is the problem.
• To avoid this java had used primitive types. So, primitive types do not inherit Object class,
But there are times when you will need an object representation for primitives like int and
char.
• Many of the standard data structures implemented by Java operate on objects,
which mean that you can’t use these data structures to store primitive types.
• To handle these (and other) situations, Java provides type wrappers, which
are classes that encapsulate a primitive type within an object.
• Primitive types like integers or strings often have limited behavior in their raw form.
Wrappers add methods and properties that enable extended operations.

• Example: In Java, the Integer class wraps the primitive int type and adds methods like
parseInt, toString, and compare. 30
The type wrappers are :
Double, Float, Long, Integer, Short, Byte, Character, and Boolean.

Character:
• Character is a wrapper around a char.
• The constructor for Character is Character(char ch) here ch is a character
variable whose values will be wrapped to character object by the wrapper class
• To obtain the char value contained in a Character object, call charValue( ), shown
here:
char charValue( )
It returns the encapsulated character.
Boolean
•Boolean is a wrapper around boolean values. It defines these constructors:
Boolean(boolean boolValue)
Boolean(String boolString)
31
• In the first version, boolValue must be either true or false. In the second version,
if boolString contains the string "true" (in uppercase or lowercase), then the new
Boolean object will be true. Otherwise, it will be false.
• To obtain a boolean value from a Boolean object, use booleanValue( ), shown
here:
boolean booleanValue( )
• It returns the boolean equivalent of the invoking object.

The Numeric Type Wrappers


•The most commonly used type wrappers are those that represent numeric values. These are
Byte, Short, Integer, Long, Float, and Double. All of the numeric type wrappers inherit the
abstract class Number.
•Number declares methods that return the value of an object in each of the different
number formats. These methods are shown here:

1.byte byteValue( ) 2. double doubleValue( ) 3. float floatValue( ) 4. int intValue( )


5. long longValue( ) 6. short shortValue( ).
32
doubleValue( ): returns the value of an object as a double
floatValue( ): returns the value as a float, and so on.
•All of the numeric type wrappers define constructors that allow an object to be
constructed from a given value, or a string representation of that value. For example,
here are the constructors defined for Integer:
Integer(int num) Integer(String str)
•If str does not contain a valid numeric value, then a NumberFormatException is
thrown. All of the type wrappers override toString( ). It returns the human-readable
form of the value contained within the wrapper. This allows you to output the value
by passing a type wrapper object to println( ), for example, without having to
convert it into its primitive type.

33
Program : All wrapper class
public static void main(String args[]) {

Character c=new Character('@'); // character type


char c1=c.charValue();
System.out.println("Character wrapper class"+c1);

Boolean b=new Boolean(true);


boolean b1=b.booleanValue();
System.out.println("Boolean wrapper class"+b1);
Integer i1 = new Integer(100); // integre type
int i = i1.intValue();
System.out.println("Integer wrapper class"+i); // displays 100 100
Float f1 = new Float(12.5); // Float type output:
Character wrapper class@
float f = f1.floatValue(); Boolean wrapper class true
System.out.println("Float wrapper class"+f); } } Integer wrapper class100
34
Float wrapper class12.5
Autoboxing
• Autoboxing is the process by which a primitive type is automatically encapsulated
(boxed) into its equivalent type wrapper whenever an object of that type is needed.
There is no need to explicitly construct an object.
• For example, converting int to Integer class. The Java compiler applies autoboxing
when a primitive value is:
• Passed as a parameter to a method that expects an object of the corresponding
wrapper class.
• Assigned to a variable of the corresponding wrapper class.

• Auto-unboxing is the process by which the value of a boxed object is


automatically extracted(unboxed) from a type wrapper when its value is needed.
There is no need to call a method such as intValue( ) or doubleValue( ).

• For example, conversion of Integer to int. The Java compiler applies unboxing
when an object of a wrapper class is:
35
• Passed as a parameter to a method that expects a value of the corresponding
primitive type.
• Assigned to a variable of the corresponding primitive type.
Uses of Autoboxing and Unboxing
• Useful in removing the difficulty of manually boxing and unboxing values in
several algorithms.
• it is very important to generics, which operates only on objects.
• It also helps prevent errors.
• autoboxing makes working with the Collections Framework
• here is the modern way to construct an Integer object that has the value 100:
Integer iOb = 100; // autobox an int
this for you, automatically.
• To unbox an object, simply assign that object reference to a primitive-type
variable.
• For example, to unbox iOb, you can use this line:
int i = iOb; // auto-unbox . 36
Program: Simple program for autoboxing and autoUnboxing
class auto
{
public static void main(String[] args)
{
Integer iob = 100; //Auto-boxing of int i.e converting primitive data type int to a Wrapper class
Integer
int i = iob; //Auto-unboxing of Integer i.e converting Wrapper class Integer to a primitve type int

System.out.println("integer type="+i+" "+iob);

Character cob = 'a'; //Auto-boxing of char i.e converting primitive data type char to a Wrapper
class Character
char ch = cob; //Auto-unboxing of Character i.e converting Wrapper class Character to a
primitive type char

System.out.println("character type="+cob+" "+ch);


}
output:
} integer type=100 100
character type=a a 37
Autoboxing and Methods:
• Thus, autoboxing/unboxing might occur when an argument is passed to a method,
or when a value is returned by a method.
• Autoboxing automatically occurs whenever a primitive type must be converted into
an object.autounboxing takes place whenever an object must be converted into a
primitive type.
Program:
class auto {
static int m(Integer v) {
return v ; // auto-unbox to int
}
public static void main(String args[]) {
Integer iOb = m(100); // Auto Boxing
System.out.println("Integer type="+iOb);
} output:
} Integer type=100 38
1. Autoboxing/Unboxing Occurs in Expressions:
• Autoboxing and unboxing take place whenever a conversion into an object or from an
object is required.
• This applies to expressions. Within an expression, a numeric object is automatically
unboxed.
• The outcome of the expression is reboxed, if necessary
Program:
public static void main(String args[]) {
Integer iOb, iOb2; int i;
iOb = 100;
System.out.println("Original value of iOb: " + iOb); //The following automatically unboxes
iOb, performs the increment, and then reboxes the result back into iOb.
++iOb;
System.out.println("After ++iOb: " + iOb);
iOb2 = iOb + (iOb / 3);
output:
System.out.println("iOb2 after expression: " + iOb2);
Original value of iOb: 100
i = iOb + (iOb / 3); After ++iOb: 101
System.out.println("i after expression: " + i); iOb2 after expression: 134
} } i after expression: 134 39
2. Autoboxing/Unboxing Boolean and Character Values
Java also supplies wrappers for boolean and char. These are Boolean and Character.
Autoboxing/unboxing applies to these wrappers, too
• Character ch = 'x'; // box a char
• char ch2 = ch; // unbox a char
• Boolean b = true; here the value true is boxed in b
• if(b) System.out.println("b is true"); // here b is unboxed
Program:
class auto {
public static void main(String args[]) {
//Autobox/unbox a boolean.
Boolean b = true;
if(b)
System.out.println("b is true");

40
// Autobox/unbox a char.
Character ch = 'x'; // box a char
char ch2 = ch; // unbox a char
System.out.println("ch2 is " + ch2);
}
} output:
b is true
ch2 is x

3. Autoboxing/Unboxing Helps Prevent Errors:


• Autoboxing always creates the proper object and auto unboxing always
produce the proper value.
• There is no way for the process to produce the wrong type of object or value.

41
Program:
class auto {
public static void main(String args[]) {

Integer iOb = 1000; // autobox the value 1000


int i = iOb.byteValue(); // manually unbox as byte !!!
System.out.println("unbox value:"+i); // does not display 1000 !
} } output:
unbox value:-24

• This program displays not the expected value of 1000, but –24! The reason is that
the value inside iOb is manually unboxed by calling byteValue( ), which causes
the truncation of the value stored in iOb, which is 1,000.
• This results in the garbage value of –24 being assigned to i.
• Auto-unboxing prevents this type of error because the value in iOb will always
autounbox into a value compatible with int. 42
A Word of Warning
In Java, "a word of warning" typically refers to a cautionary note or advice
about potential pitfalls, issues, or best practices when working with the language or a
specific feature. This phrase is often used in documentation, tutorials, or discussions
to highlight something developers should be aware of to avoid unexpectedly
consequences.
Because of autoboxing and auto-unboxing, some might be tempted to use objects
such as Integer or Double exclusively, abandoning primitives altogether.
Double a, b, c;
a = 10.0;
b = 4.0;
"A word of warning: Floating-point operations can introduce
c = Math.sqrt(a*a + b*b); precision errors; avoid using them for financial calculations."

System.out.println("Hypotenuse is " + c);


43
Annotation
• Java Annotation is a tag that represents the metadata i.e. attached with class,
interface, methods or fields to indicate some additional information which can be
used by java compiler and JVM.
• Annotations in java are used to provide additional information, so it is an
alternative option for XML and java marker interfaces.
Java annotations are metadata added to Java code, providing additional
information that does not directly affect the program's functionality. Introduced in
Java 5, annotations are widely used for various purposes like documentation, code
analysis, runtime processing, and configuring frameworks.

Syntax ?
Syntax: An annotation starts with @, followed by the annotation name.

44
What’s the use of Annotations?
1) Instructions to the compiler: There are three built-in annotations available in
Java (@Deprecated, @Override & @SuppressWarnings) that can be used for
giving certain instructions to the compiler.
For example, the @override annotation is used for instructing
compiler that the annotated method is overriding the method.
2) Compile-time instructors: Annotations can provide compile-time instructions to
the compiler that can be further used by software build tools for generating code,
XML files etc.
3) Runtime instructions: We can define annotations to be available at runtime
which we can access using java reflection and can be used to give instructions to
the program at runtime.

45
Annotation basics

46
@Override
void myMethod() {
//Do something
}
• An annotation cannot include an extends clause. However, all annotation types
automatically extend the Annotation interface. Thus, Annotation is a super-
interface of all annotations. It is declared within the java.lang.annotation package.

• It overrides hashCode( ), equals( ), and toString( ), which are defined by Object.


It also specifies annotationType( ), which returns a Class object that represents
the invoking annotation.

47
Program: To display welcome message.
class annu
{
@mymethod public void show()
{
System.out.println("Well come to Annotation");
}
public static void main(String a[])
{
annu h = new annu();
h.show(); //deprecated
}
}
OutPUT:
Well come to Annotation
48
Specifying a Retention Policy

• A retention policy determines at what point an annotation is discarded. Java defines


three such policies, which are encapsulated within the
java.lang.annotation.RetentionPolicy enumeration.

They are SOURCE, CLASS, and RUNTIME.


 An annotation with a retention policy of SOURCE is retained only in the source
file and is discarded during compilation.
 An annotation with a retention policy of CLASS is stored in the .class file during
compilation. However, it is not available through the JVM during run time.
 An annotation with a retention policy of RUNTIME is stored in the .class file
during compilation and is available through the JVM during run time. Thus,
RUNTIME retention offers the greatest annotation persistence.
Example:
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno
{
String str();
int val();
}
50
Obtaining Annotations at Run Time by Use of Reflection:

51
• After you have obtained a Class object, you can use its methods to obtain
information about the various items declared by the class, including its annotations
Class supplies (among others) the getMethod( ), getField( ), and getConstructor(
) methods, which obtain information about a method, field, and constructor,
respectively. These methods return objects of type Method, Field, and
Constructor.

Method getMethod(String methName, Class<?> ... paramTypes)

• From a Class, Method, Field, or Constructor object, you can obtain a specific
annotation associated with that object by calling getAnnotation( ).

<A extends Annotation> getAnnotation(Class<A> annoType)

52
Program:
import java.lang.annotation.*;
import java.lang.reflect.*;

// Define a custom annotation


@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String value();
}

// A class with an annotated method


class MyClass {
@MyAnnotation("Hello, Annotation!")
public void myMethod() {}
}

public class SimpleReflection {


public static void main(String[] args) throws Exception {
Method method = MyClass.class.getMethod("myMethod"); // Get the method
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class); // Get the annotation
System.out.println("Annotation value: " + annotation.value()); // Print the annotation value
}
}
Annotation value: Hello, Annotation!
53
The Annotated Element Interface:

54
1. getDeclaredAnnotations( ) Method in Java
The getDeclaredAnnotations() method is part of the AnnotatedElement interface in
Java. This method is used to retrieve all the annotations explicitly declared on a particular
program element, such as a class, method, field, constructor, or other reflective objects.

Annotation[] getDeclaredAnnotations()
Returns: An array of Annotation objects representing all annotations explicitly declared on
the element. Returns an empty array if no annotations are declared.

Visibility: Only retrieves annotations that are directly declared on the program element.
Does not include inherited annotations (those inherited from superclasses or interfaces via
@Inherited).

55
import java.lang.annotation.*;
import java.lang.reflect.*;

// Define a custom annotation


@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {}

class MyClass {
@MyAnnotation
public void myMethod() {}
}

public class SimpleAnnotations {


public static void main(String[] args) throws Exception {
Method method = MyClass.class.getDeclaredMethod("myMethod"); // Get the method
Annotation[] annotations = method.getDeclaredAnnotations(); // Get annotations
System.out.println("Annotations count: " + annotations.length); // Print count
}
} 56
2. isAnnotationPresent( ):

57
import java.lang.annotation.*;
import java.lang.reflect.*;

// Define a custom annotation


@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {}

class MyClass {
@MyAnnotation
public void myMethod() {}
}
public class SimpleIsAnnotationPresent {
public static void main(String[] args) throws Exception {
Method method = MyClass.class.getMethod("myMethod"); // Get the method
boolean isPresent = method.isAnnotationPresent(MyAnnotation.class); // Check for
annotation
System.out.println("Is MyAnnotation present? " + isPresent); // Print result
}
} Is MyAnnotation present? true 58
3. getDeclaredAnnotation( ):
Method returns this element's annotation for the specified type if such an
annotation is present, else null. This methods throws an exception
•NullPointerException − if the given annotation class is null
•IllegalMonitorStateException − if the current thread is not the owner of the
object's monitor. Syntax: public A getAnnotation(Class annotationClass)

4. getAnnotationsByType( ):
Returns annotations that are associated with this element. If there are no
annotations associated with this element, the return value is an array of
length 0.

59
5. getDeclaredAnnotationsByType( ):
Returns this element's annotation(s) for the specified type if such annotations
are either directly present or indirectly present. This method ignores inherited
annotations. If there are no specified annotations directly or indirectly present on this
element, the return value is an array of length 0.

60
Using Default Values:

public class DefaultValuesExample {


int number; // Default value for int is 0
String text; // Default value for String is null

public static void main(String[] args) {


DefaultValuesExample obj = new DefaultValuesExample();

// Print the default values


System.out.println("Default value of number: " + obj.number);
System.out.println("Default value of text: " + obj.text);
}
} Default value of number: 0
Default value of text: null 61
Marker Annotations:
A marker annotation is a special kind of annotation that contains no members.
Its sole purpose is to mark an item. Thus, its presence as an annotation is sufficient.
The best way to determine if a marker annotation is present is to use the method
isAnnotationPresent( ), which is defined by the AnnotatedElement interface.

Syntax: public @interface Example{

62
import java.lang.annotation.*;
import java.lang.reflect.*;
// Define a marker annotation
@Retention(RetentionPolicy.RUNTIME)
@interface MyMarker {}
class MyClass {
@MyMarker
public void myMethod() {
System.out.println("myMethod() is running.");
}
}
public class MarkerAnnotationExample {
public static void main(String[] args) throws Exception {
Method method = MyClass.class.getMethod("myMethod");

// Check if the marker annotation is present


if (method.isAnnotationPresent(MyMarker.class)) {
System.out.println("MyMarker annotation is present on myMethod.");
}
} } MyMarker annotation is present on myMethod. 63
Single-Member Annotations:
• A single-member annotation contains only one member. It works like a normal
annotation except that it allows a shorthand form of specifying the value of the
member.
When only one member is present, you can simply specify the value for that member
when the annotation is applied—you don’t need to specify the name of the member.
However,
• In order to use this shorthand, the name of the member must be value. Here is an
example that creates and uses a single-member annotation:
Syntax:
public @interface Example{

String showSomething();

64
import java.lang.annotation.*;
// Define a single-member annotation
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String value(); // Single member (value)
}
class MyClass {
@MyAnnotation("Hello, Annotations!")
public void myMethod() {
System.out.println("myMethod() is running.");
}}
public class SingleMemberAnnotationExample {
public static void main(String[] args) throws Exception {
Method method = MyClass.class.getMethod("myMethod");

// Check if the annotation is present and get its value


if (method.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
System.out.println("Annotation value: " + annotation.value());
} }}
Annotation value: Hello, Annotations! 65
Built-In Java Annotations
There are several built-in annotations in java. Some annotations are applied to java
code and some to other annotations.
Built-In Java Annotations used in java code

@Override
@Suppress Warnings
@Deprecated

Built-In Java Annotations used in other annotations


@Target
@Retention
@Inherited
@Documented
66
Built-In Java Annotations used in java code
@Override
@Override annotation assures that the subclass method is overriding the parent class method.
If it is not so, compile time error occurs.
Sometimes, we does the silly mistake such as spelling mistakes etc. So, it is better to mark
@Override annotation that provides assurity that method is overridden.

•Purpose: Indicates that a method is overriding a method in its superclass.


•Usage:
•Helps ensure that the method correctly overrides the parent class method.
•The compiler will throw an error if the annotated method does not match a method in the
superclass (e.g., if there’s a typo in the method name).

67
class Parent {
void display() {
System.out.println("Parent class method");
}
}

class Child extends Parent


{
@Override
void display()
{
System.out.println("Child class method");
}
}

68
@Suppress Warnings
@Suppress Warnings annotation: is used to suppress warnings issued by the compiler.

If you remove the @SuppressWarnings("unchecked") annotation, it will show warning at


compile time because we are using non-generic collection.

• Purpose: Instructs the compiler to suppress specific warnings that might be otherwise
generated.
• Usage:
• Used to ignore warnings, such as unchecked operations, deprecations, or unused
variables, which you are aware of and want to suppress.
• Commonly used with warnings like unchecked, deprecation, or serial.

69
import java.util.*;
class TestAnnotation2{
@SuppressWarnings("unchecked")
public static void main(String args[])
{
ArrayList list=new ArrayList();
list.add("sonoo");
}}

70
@Deprecated
@Deprecated annotation marks that this method is deprecated so compiler prints warning.
It informs user that it may be removed in the future versions. So, it is better not to use such
methods.

• Purpose: Marks a class, method, or field as deprecated, signaling that it should no


longer be used.

• Usage:
• Typically used to warn developers that a feature is outdated and might be removed
in future versions.
• The compiler generates a warning if the deprecated element is used.

71
class OldClass {
@Deprecated
void oldMethod() {
System.out.println("This method is deprecated");
}
}

public class Example {


public static void main(String[] args) {
OldClass obj = new OldClass();
obj.oldMethod(); // Compiler will issue a warning
}
}

Key Notes:
•Annotations like these improve code readability and maintainability by providing metadata
that informs developers and the compiler about specific behaviors or constraints.
•Overuse of @SuppressWarnings can hide genuine issues, so it should be used carefully.
72
Built-In Java Annotations used in other annotations
@Target
@Target tag is used to specify at which type, the annotation is used.
The java.lang.annotation. ElementType enum declares many constants to specify the type of
element where annotation is to be applied such as TYPE, METHOD, FIELD etc. Let's see the
constants of ElementType enum:
Element Types Where the annotation can be applied

TYPE class, interface or enumeration


FIELD fields
METHOD methods
CONSTRUCTOR constructors
LOCAL_VARIABLE local variables
ANNOTATION_TYPE annotation type
PARAMETER parameter 73
1. Example to specify annoation for a class

@Target(ElementType.TYPE)
@interface MyAnnotation{
int value1();
String value2();
}
2. Example to specify annotation for a class, methods or fields

@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})


@interface MyAnnotation{
int value1();
String value2();
} 74
@Retention
Purpose: Specifies how long the annotation is retained (its lifecycle).
@Retention annotation is used to specify to what level annotation will be available .

Retention Policy Availability

RetentionPolicy.SOURCE refers to the source code, discarded during compilation. It will not be
available in the compiled class.

RetentionPolicy.CLASS refers to the .class file, available to java compiler but not to JVM . It is
included in the class file.

RetentionPolicy.RUNTIME refers to the runtime, available to java compiler and JVM .

75
Example to specify the Retention Policy

@Retention(RetentionPolicy.RUNTIME) // Annotation is available at runtime


@Target(ElementType.TYPE)
@interface MyAnnotation{
int value1();
String value2();
}

76
@Inherited
By default, annotations are not inherited to subclasses. The @Inherited annotation marks the
annotation to be inherited to subclasses.

• Purpose: Indicates that an annotation type is inheritable by subclasses.


• Usage:
• If an annotation is marked with @Inherited, then any subclass of a class that uses this
annotation will automatically inherit it.
• Only works with class-level annotations (annotations with
@Target(ElementType.TYPE)).

77
import java.lang.annotation.Inherited;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Inherited
@Target(ElementType.TYPE) // Can only be used on classes
@interface MyAnnotation {
}

@MyAnnotation
class Parent {
}

class Child extends Parent {


}

public class Test {


public static void main(String[] args) {
System.out.println(Child.class.isAnnotationPresent(MyAnnotation.class)); // true
}
}
78
@Documented
The @Documented Marks the annotation for inclusion in the documentation.
• Purpose: Indicates that the annotation should be included in the generated
JavaDoc.
• Usage:
• Ensures that custom annotations are documented in the API
documentation generated by tools like Javadoc.
• By default, annotations are not included in JavaDoc unless they are
annotated with @Documented.

79
import java.lang.annotation.Documented;

@Documented // This annotation will appear in Javadoc


@interface MyAnnotation {
String value();
}

Summary Table:

80
THE END
81

You might also like