0% found this document useful (0 votes)
18 views

Module 1 Notes

Uploaded by

deepakchabri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Module 1 Notes

Uploaded by

deepakchabri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Advanced Java and 15CS64

J2EE 4
IA Marks: 20
ADVANCED JAVA and
J2EE Exam Hours: 3
Exam Marks: 80
MODULE-I 8 Hours

Enumerations, Autoboxing and Annotations(metadata): Enumerations, Enumeration


fundamentals, the values() and valueOf() 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
runtime by use of reflection, Annotated element Interface, Using Default values, Marker
Annotations, Single Member annotations, Built-In annotations.

MODULE-II 8 Hours

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-III 8 Hours

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( ) 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-IV 8 Hours

Servlet: 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-V 8 Hours

Dept. of CSE, Page i


DsDSATM
Advanced Java and 15CS64
J2EE 4
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.

Reference / Text Book Details

Sl.No. Title of Book Author Publication Edition

JAVA The Complete Tata McGraw


1 Herbert Schildt 7th/9th
Reference Hill
Tata McGraw
2 J2EE The Complete Reference Jim Keogh 2007
Hill
Introduction to JAVA Pearson
3 Y. Daniel Liang 7th
Programming Education, 2007
Stephanie Pearson
4 The J2EE Tutorial 2nd
Bodoff Education, 2004

Advanced JAVA Oxford University


5 Uttam K Roy 2015
Programming Press

Dept. of CSE, Page ii


DsDSATM
Advanced Java and 15CS64
J2EE 4
Table of Contents

SL No Module Description Page No

1 Module 1 – Enumeration, AutoBoxing and Annotations 1-23

2 Module 2 – Generics 24-57

3 Module 3 – String Methods 58-119

4 Module 4 – Servlets and JSP 120-149

5 Module 5 – JDBC Methods 150-166

Dept. of CSE, Page


DsDSATM iii
Advanced Java and 18CS64
J2EE 4
Module – 1
Enumerations, Autoboxing and Annotations
Enumerations

Enumerations was added to Java language in JDK5. Enumeration means a list of named constant. In Java,
enumeration defines a class type. An Enumeration can have constructors, methods and instance variables. It
is created using enum keyword. Each enumeration constant is public, static and final by default. Even
though enumeration defines a class type and have constructors, you do not instantiate an enum using new.
Enumeration variables are used and declared in much a same way as you do a primitive variable.

How to Define and Use an Enumeration

1. An enumeration can be defined simply by creating a list of enum variable. Let us take an example
for list of Subject variable, with different subjects in the list.

enum Subject //Enumeration defined


{
Java, Cpp, C, Dbms
}

2. Identifiers Java, Cpp, C and Dbms are called enumeration constants. These are public, static and
final by default.
3. Variables of Enumeration can be defined directly without any new keyword.

Subject sub;

4. Variables of Enumeration type can have only enumeration constants as value. We define an enum
variable as enum_variable = enum_type.enum_constant;

sub = Subject.Java;

5. Two enumeration constants can be compared for equality by using the = = relational operator.

Example:

if(sub == Subject.Java) {
...
}

Dept. of CSE Page 1


DSATM
Advanced Java and 18CS64
J2EE 4
Example of Enumeration

enum WeekDays
{ sun, mon, tues, wed, thurs, fri, sat }

class Test
{
public static void main(String args[])
{
WeekDays wk; //wk is an enumeration variable of type WeekDays
wk = WeekDays.sun; //wk can be assigned only the constants defined under
//enum type Weekdays
System.out.println("Today is "+wk);
}
}
Output :
Today is sun

The enum can be defined within or outside the class because it is similar to a class.

enum Season {
WINTER, SPRING, SUMMER, FALL
}
class EnumExample2
{
public static void main(String[] args)
{
Season s=Season.WINTER;
System.out.println(s);
}
}

Output:WINTER

class EnumExample3
{
enum Season
{
WINTER, SPRING, SUMMER, FALL;
} //semicolon; is optional here
public static void main(String[] args)
{
Season s=Season.WINTER; //enum type is required to access
WINTERSystem.out.println(s);
}
}

Dept. of CSE Page 2


DSATM
Advanced Java and 18CS64
J2EE 4
Output:WINTER

Example of Enumeration using switch statement

class EnumExample5{
enum Day
{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY
}
public static void main(String args[])
{
Day d=Day.MONDAY;
switch(d)
{ case
SUNDAY:
System.out.println("sunday");
break;

case MONDAY:
System.out.println("monday");
break;

default:
System.out.println("other day");
}
}
}

Output : monday

Dept. of CSE Page 3


DSATM
Advanced Java and 18CS64
J2EE 4
Values( ) and ValueOf( ) method

All the enumerations has predefined methods values() and valueOf().


 values() method returns an array of enum-type containing all the enumeration constants in it.
Its general form is,

public static enum-type[ ] values()

 valueOf() method is used to return the enumeration constant whose value is equal to the string
passed in asargument while calling this method.
It's general form is,

public static enum-type valueOf (String str)

Example of enumeration using values() and valueOf() methods:

enum Restaurants
{
dominos, kfc, pizzahut, paninos, burgerking;
}
class Test
{
public static void main(String args[])
{
Restaurants r;
System.out.println("All constants of enum type Restaurants are:");
Restaurants rArray[] = Restaurants.values(); //returns an array of constants of type Restaurants
for(Restaurants a : rArray) //using foreach loop
System.out.println(a);
r = Restaurants.valueOf("dominos");
System.out.println("I AM " + r);
}
}

Output:
All constants of enum type Restaurants are:
dominos
Kfc
Pizzahut
Paninos
burgerking
I AM dominos

Dept. of CSE Page 4


DSATM
Advanced Java and 18CS64
J2EE 4
 Instead of creating array we can directly obtain all
values.

class EnumExample1{
public enum Season
{
WINTER, SPRING, SUMMER, FALL
}
public static void main(String[] args)
{
for (Season s : Season.values())
System.out.println(s);
}
}

Output:
WINTER
SPRING
SUMMER
FALL

Points to remember about Enumerations

1. Enumerations are of class type, and have all the capabilities that a Java class has.
2. Enumerations can have Constructors, instance Variables, methods and can even implement
Interfaces.
3. Enumerations are not instantiated using new keyword.
4. All Enumerations by default inherit java.lang.Enum class.
5. As a class can only extend one parent in Java, so an enum cannot extend anything else.
6. enum may implement many interfaces but cannot extend any class because it internally extends
Enum class

Java Enum are class type and can contain Constructor, instance variable and Method & implement
interface.

enum Student
{
John(11), Jonny(10), Sam(13), Viraaj(9);
private int age; //variable defined in enum Student
int getage() //method defined in enum Student
{
return age;
}

Dept. of CSE Page 5


DSATM
Advanced Java and 18CS64
J2EE 4
Student(int age) //constructor defined in enum Student
{
this.age= age;
}
}

Dept. of CSE Page 6


DSATM
Advanced Java and 18CS64
J2EE 4
Age of Viraaj is 9 years

All students age is:


John age is 11
Jonny age is 10
Sam age is 13
Viraaj age is 9

In this example as soon as we declare an enum variable(Student S), the constructor is called, and it initializes
age for every enumeration constant with values specified with them in parenthesis.

Each enum constant(John, Jonny…) has its own copy of value(age…)

Student.Viraaj.getage()returns age of Viraaj.

Java Enum containg overloaded constructor


class
EnumExamp{ enum
Season{
WINTER(5), SPRING(10), SUMMER(15), FALL;

private int value;


Season(int
v){ value=v;
}
//default constructor initializes value to -1
Season(){
value= -1;
}

Dept. of CSE Page 7


DSATM
Advanced Java and 18CS64
J2EE 4
}
public static void main(String args[]){
//printing enum constant and its value
System.out.println("Season is "+ Season.SUMMER+ " value is "+ Season.SUMMER.value);
//printing all enum constant and its value
for (Season s : Season.values())
System.out.println(s+" "+s.value);

}} output
Season is SUMMER value is 15
WINTER 5
SPRING 10
SUMMER 15
FALL -1

Enumerations Inherits Enum


All enumerations automatically inherit java.lang.Enum. The Enum class defines several methods such as
ordinal( ), compareTo( ), equals( ) and so on, that are available for use by all enumerations. You can
obtain a value that indicates an enumeration constant’s position in the list of constants. This is called its
‘ordinal value’ and it is retrieved by calling the ordinal( ) method. This method returns the ordinal value of
the invoking constant. Ordinal values begin at ‘0’.

final int ordinal()

//example using ordinal() method


enum Season { WINTER, SPRING, SUMMER, FALL }
class EnumExample2{
public static void main(String[] args)
{Season s=Season.WINTER;
System.out.println(s.ordinal());
}}

Output:

//example using compareTo( ) method


You can compare the ordinal value of two contents of the same enumeration by using the compareTo( )
method. This method returns a negative integer, zero, or a positive integer as this object ordinal value less
than, equal to, or greater than the specified object ordinal value.

enum Tutorials
{ topic1, topic2,
topic3;
}

public class EnumDemo {

Dept. of CSE Page 8


DSATM
Advanced Java and 18CS64
J2EE 4
public static void main(String args[]) {

Tutorials t1, t2, t3;

t1 = Tutorials.topic1;
t2 = Tutorials.topic2;
t3 = Tutorials.topic3;

if(t1.compareTo(t2) > 0) {
System.out.println(t2 + " completed before " + t1);
}

if(t1.compareTo(t2) < 0) {
System.out.println(t1 + " completed before " + t2);
}

if(t1.compareTo(t3) == 0) {
System.out.println(t1 + " completed with " + t3);
}
}
}
topic1 completed before topic2

You can compare an enumeration constant with any other object by using equal( ), which overrides the
equals( ) method defined by Object. Although equals( ) can compare an enumeration constant to any other
object, those two objects will only be equal if they both refer to the same constant, within the same
enumeration.

enum Tutorials
{ topic1, topic2,
topic3;
}

public class EnumDemo {

public static void main(String args[]) {

Tutorials t1, t2, t3;

t1 = Tutorials.topic1;
t2 = Tutorials.topic2;
t3 = Tutorials.topic1;

if(t1.equals(t2))
{ System.out.println(“Error”);
}

if (t1.equals(t3)) {
Dept. of CSE Page 9
DSATM
Advanced Java and 18CS64
J2EE 4
System.out.println(t1 + " Equals " + t3);
}
}
}
topic1 Equals topic1

We can compare 2 enumerations references for equality using ==( operator).

enum Apple
{
shimla, ooty, wood, green, red
}

class dsatm
{
public static void main(String args[])
{
Apple ap, ap2, ap3;

// Obtain all ordinal values using ordinal().


System.out.println("Here are all apple constants" +
" and their ordinal values: ");
for(Apple a : Apple.values())
System.out.println(a + " " + a.ordinal());

ap = Apple.wood;
ap2 = Apple.ooty;
ap3 = Apple.wood;

System.out.println();

// Demonstrate compareTo() and equals()


if(ap.compareTo(ap2) < 0)
System.out.println(ap + " comes before " + ap2);

if(ap.compareTo(ap2) > 0)
System.out.println(ap2 + " comes before " + ap);

if(ap.compareTo(ap3) == 0)
System.out.println(ap + " equals " + ap3);

System.out.println();

if(ap.equals(ap2))
System.out.println("Error!");

if(ap.equals(ap3))

Dept. of CSE Page


DSATM 10
Advanced Java and 18CS64
J2EE 4
System.out.println(ap + " equals " + ap3);

if(ap == ap3)
System.out.println(ap + " == " + ap3);

}
}

Here are all apple constants and their ordinal values:


shimla 0
ooty 1
wood 2
green 3
red 4

ooty comes before wood


wood equals wood

wood equals wood


wood == wood

Dept. of CSE Page


DSATM 11
Advanced Java and 18CS64
J2EE 4

Type Wrapper

Java uses primitive data types such as int, double, float etc. to hold the basic data types.
Eg. Int a =10;
Float f=24.7;
Char ch=’c’;

Despite the performance benefits offered by the primitive data types, there are situations when you will
need an object representation of the primitive data type. For example, many data structures in Java operate
on objects. So you cannot use primitive data types with those data structures. To handle such type of
situations, Java provides type Wrappers which provide classes that encapsulate a primitive type within an
object.

Need of Wrapper Classes

1. They convert primitive data types into objects. Objects are needed if we wish to modify the
arguments passed into a method (because primitive types are passed by value).
2. The classes in java.util package handles only objects and hence wrapper classes help in this case
also.
3. Data structures in the Collection framework, such as ArrayList and Vector, store only objects
(reference types) and not primitive types.
4. An object is needed to support synchronization in multithreading.

Character : It encapsulates primitive type char within object.


Character (char ch) //constructor for Character class
ch-specifies character that will be wrapped by Character object being created.
To obtain primitive char value contained in Character object call
char charValue()

Dept. of CSE Page


DSATM 12
Advanced Java and 18CS64
J2EE 4
Boolean : It encapsulates primitive type boolean within object.
Boolean (boolean b) //constructor for Boolean class
To obtain primitive bool value contained in Boolean object call
boolean booleanValue()

Likewise for below wrapper classes


Numeric type wrappers : It is the most commonly used type wrapper.
Byte Short Integer Long Float Double

Primitive Wrapper Class Constructor Argument Methods to get primitive values


Boolean (boolean b)
boolean Boolean booleanValue()
or String
byte Byte Byte (byte b) or String byte Value()
char Character Character (char ch) char Value()
int Integer Integer(int a) or String int Value()
float Float Float(float f) or double or String float Value()
double Double Double (double d) or String double Value()
long Long Long (long l)or String long Value()
short Short Short (short) or String short Value()
Following example shows constructors in wrapper classes.

public class WrapperClasses


{
public static void main(String[] args)
{
Byte B1 = new Byte((byte) 10); //Constructor which takes byte value as an argument
Byte B2 = new Byte("10"); //Constructor which takes String as an argument

//Byte B3 = new Byte("abc"); //Run Time Error : NumberFormatException

//Because, String abc can not be parse-able to byte

Short S1 = new Short((short) 20); //Constructor which takes short value as an argument
Short S2 = new Short("10"); //Constructor which takes String as an argument

Integer I1 = new Integer(30); //Constructor which takes int value as an argument


Integer I2 = new Integer("30"); //Constructor which takes String as an argument

Long L1 = new Long(40); //Constructor which takes long value as an argument


Long L2 = new Long("40"); //Constructor which takes String as an argument

Float F1 = new Float(12.2f); //Constructor which takes float value as an argument


Float F2 = new Float("15.6"); //Constructor which takes String as an argument

Dept. of CSE Page


DSATM 13
Advanced Java and 18CS64
J2EE 4
Float F3 = new Float(15.6d); //Constructor which takes double value as an argument

Double D1 = new Double(17.8d); //Constructor which takes double value as an argument


Double D2 = new Double("17.8"); //Constructor which takes String as an argument

Boolean BLN1 = new Boolean(false); //Constructor which takes boolean value as an argument
Boolean BLN2 = new Boolean("true"); //Constructor which takes String as an argument

Character C1 = new Character('D'); //Constructor which takes char value as an argument


Character C2 = new Character("abc"); //Compile time error : String abc can not be converted to
character
}
}

Type Wrapper Hierarchy

Boxing : Process of converting primitive type to corresponding wrapper.


Eg. Integer i = new Integer(10);
Integer j = 20;

UnBoxing : Process of extracting value for type wrapper.


int a = i.intValue(i);

Autoboxing and Unboxing

 Autoboxing and Unboxing features was added in Java5.


 Autoboxing is a process by which primitive type is automatically encapsulated(boxed) into its
equivalent type wrapper
 Auto-Unboxing is a process by which the value of an object is automatically extracted from a type
Wrapper class.

Benefits of Autoboxing / Unboxing

1. Autoboxing / Unboxing lets us use primitive types and Wrapper class objects interchangeably.
Dept. of CSE Page
DSATM 14
Advanced Java and 18CS64
J2EE 4
2. We don't have to perform Explicit typecasting.
3. It helps prevent errors, but may lead to unexpected results sometimes. Hence must be used with care.
4. Auto-unboxing also allows you to mix different types of numeric objects in an expression. When the
values are unboxed, the standard type conversions can be applied.

Simple Example of Autoboxing in java:

class BoxingExample1{
public static void main(String
args[]){int a=50;
Integer a2=new Integer(a);//Boxing

Integer a3=5;//Boxing

System.out.println(a2+" "+a3);
}
}
Output:50 5

Simple Example of Unboxing in java:

class UnboxingExample1{
public static void main(String
args[]){Integer i=new Integer(50);
int a=i;

System.out.println(a);
}
}
Output:50

Autoboxing / Unboxing in Expressions

Whenever we use object of Wrapper class in an expression, automatic unboxing and boxing is done by
JVM.

Integer iOb;
iOb = 100; //Autoboxing of int
++iOb;

When we perform increment operation on Integer object, it is first unboxed, then incremented and then
again reboxed into Integer type object.

This will happen always, when we will use Wrapper class objects in expressions or conditions etc.

Dept. of CSE Page


DSATM 15
Advanced Java and 18CS64
J2EE 4

Example 2

class Test
{
public static void main(String args[])
{
Integer i = 35;
Double d = 33.3;
d = d + i;
System.out.println("Value of d is " + d);
}
}

Ouput:
Value of d is 68.3

Note: When the statement d = d + i; was executed, i was auto-unboxed into int, d was auto-unboxed into
double, addition was performed and then finally, auto-boxing of d was done into Double type Wrapper
class.

Autoboxing / Unboxing in Methods


class
Boxing1{ static
void m(int i)
{
System.out.println("int");
}
public static void main(String args[ ])
{
Integer s=30;
m(s);
}
}
Output: int

Autoboxing / Unboxing Boolean

class UnboxingExample2{
public static void main(String
args[ ]){Integer i=new Integer(50);
if(i<100){ //unboxing internally
System.out.println(i);
}
}
}
Dept. of CSE Page
DSATM 16
Advanced Java and 18CS64
J2EE 4
Output:50

Autoboxing / Unboxing Boolean and character values

// Autoboxing/unboxing a Boolean and Character.


class AutoBox5
{
public static void main(String args[]) {
Boolean b = true;
if(b) System.out.println("b is true");
// Autobox/unbox a char.
Character ch = 'x'; // box a char
char ch2 = ch; // unbox a char
System.out.println("ch2 is " + ch2);
}
}
The output is shown here:
b is true
ch2 is x

Dept. of CSE Page


DSATM 17
Advanced Java and 18CS64
J2EE 4
Autoboxing / Unboxing helps preventing errors

// An error produced by manual unboxing.


class UnboxingError {
public static void main(String args[]) {
Integer iOb = 1000; // autobox the value 1000
int i = iOb.byteValue(); // manually unbox as byte !!!
System.out.println(i); // does not display 1000 !
}
}

Annotations (Metadata)
Java Annotations allow us to add metadata information into our source code,
Annotations were added to the java from JDK 5.
Annotations, does not change the actions of a program.
Thus, an annotation leaves the semantics of a program unchanged.
However, this information can be used by various tools during both development and deployment.
□ Annotations start with ‘@’.
□ Annotations do not change action of a compiled program.
□ Annotations help to associate metadata (information) to the program elements i.e. instance variables,
constructors, methods, classes, etc.
□ Annotations are not pure comments as they can change the way a program is treated by compiler.

Annotations basics

An annotation always starts with the symbol @ followed by the annotation name. The symbol @ indicates
to the compiler that this is an annotation.

Where we can use annotations?


Annotations can be applied to the classes, interfaces, methods and fields.

Dept. of CSE Page


DSATM 18
Advanced Java and 18CS64
J2EE 4
Built-In Java Annotations

There are 7 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 imported from java.lang

 @Override
 @SuppressWarnings
 @Deprecated

Built-In Java Annotations used in other annotations


4 Annotations imported from java.lang.annotation

 @Target
 @Retention
 @Inherited
 @Documented

1. @Override It is a marker annotation that can be used only on methods. A method annotated with
@Override must override a method from a superclass. If it doesn’t, a compile-time error will result .
It is used to ensure that a superclass method is actually overridden, and not simply overloaded.

class Base
{
public void Display()
{
System.out.println("Base display()");
}
public static void main(String args[])
{
Base t1 = new Derived();
t1.Display();
}
}
class Derived extends Base
{
@Override
public void Display()
{
System.out.println("Derived display()");
}
}
Output:
Derived display()

Dept. of CSE Page


DSATM 19
Advanced Java and 18CS64
J2EE 4
2. @SuppressWarnings
It is used to inform the compiler to suppress specified compiler warnings. The warnings to suppress
are specified by name, in string form. This type of annotation can be applied to any type of
declaration.

Java groups warnings under two categories. They are : deprecation and unchecked.. Any
unchecked warning is generated when a legacy code interfaces with a code that use generics.

class DeprecatedTest
{
@Deprecated
public void Display()
{
System.out.println("Deprecatedtest display()");
}
}

public class SuppressWarningTest


{
// If we comment below annotation, program generates
// warning
@SuppressWarnings({"checked", "deprecation"})
public static void main(String args[])
{
DeprecatedTest d1 = new DeprecatedTest();
d1.Display();
}
}
Output:
Deprecatedtest display()

3. @Deprecated It is a marker annotation. It indicates that a declaration is obsolete and has been
replaced by a newer form.The Javadoc @deprecated tag should be used when an element has been
deprecated.

public class DeprecatedTest


{
@Deprecated
public void Display()
{
System.out.println("Deprecatedtest display()");
}

public static void main(String args[])


{
DeprecatedTest d1 = new DeprecatedTest();

Dept. of CSE Page


DSATM 20
Advanced Java and 18CS64
J2EE 4
d1.Display();
}
}
Output:
Deprecatedtest display()

Types of Annotation

There are 3 categories of Annotations:-


1. Marker Annotations:
 The only purpose is to mark a declaration. These annotations contain no members and do not
consist any data.
 Thus, its presence as an annotation is sufficient. Since, marker interface contains no members,
simplydetermining whether it is present or absent is sufficient.
 @Override , @Deprecated is an example of Marker Annotation.

Example: - @TestAnnotation()

2. Single value Annotations:


 These annotations contain only one member and allow a shorthand form of specifying the value of
the member.
 We only need to specify the value for that member when the annotation is applied and don’t needto
specify the name of the member. However in order to use this shorthand, the name of the member
must be value.

Example: - @TestAnnotation(“testing”);

3. Multivalue Annotations:
These annotations consist of multiple data members/ name, value, pairs.

Example:- @TestAnnotation(owner=”Umesh”, value=”Tutor”)

Java Custom Annotation

Java Custom annotations or Java User-defined annotations are easy to create and use. The @interface
element is used to declare an annotation. For example:

@interface MyAnnotation{ }

Here, MyAnnotation is the custom annotation name.

Points to remember for java custom annotation signature

There are few points that should be remembered by the programmer.

1. Annotations are created by using @interface, followed by annotation name as shown in the below
example.
Dept. of CSE Page
DSATM 21
Advanced Java and 18CS64
J2EE 4
2. An annotation can have elements as well. They look like methods. For example in the below code,
we have four elements. We should not provide implementation for these elements.

Dept. of CSE Page


DSATM 22
Advanced Java and 18CS64
J2EE 4
3. Method should return one of the following: primitive data types, String, Class, enum or array of
these data types.
4. Method should not have any parameter.
5. We should attach @ just before interface keyword to define annotation.
6. It may assign a default value to the method.

Declaring custom Annotation

@interface
MyAnnotation{ int
value1( ) default 1; String
value2( ) default "";
String value3( ) default "xyz";
}

How to apply custom Annotation

@MyAnnotation(value1=10,value2="Umesh",value3="SJBIT")

4. @Documented It is a marker interface that tells a tool that an annotation is to be documented.


Annotations are not included by Javadoc comments. Use of @Documented annotation in the code
enables tools like Javadoc to process it and include the annotation type information in the generated
document.

java.lang.annotation.Documented
@Documented
public @interface MyCustomAnnotation {
//Annotation body
}

@MyCustomAnnotation
public class MyClass {
//Class body
}

While generating the javadoc for class MyClass, the annotation @MyCustomAnnotation would be
included in that.

Dept. of CSE Page


DSATM 23
Advanced Java and 18CS64
J2EE 4
5. @Inherited

The @Inherited annotation signals that a custom annotation used in a class should be inherited by all of its
sub classes. For example:

java.lang.annotation.Inherited
@Inherited
public @interface MyCustomAnnotation {

}
@MyCustomAnnotation
public class MyParentClass {
...
}
public class MyChildClass extends MyParentClass {
...
}

Here the class MyParentClass is using annotation @MyCustomAnnotation which is marked with
@inherited annotation. It means the sub class MyChildClass inherits the @MyCustomAnnotation.

Dept. of CSE Page


DSATM 24
Advanced Java and 18CS64
J2EE 4

6. @Target

It specifies where we can use the annotation. For example: In the below code, we have defined the target
type as METHOD which means the below annotation can only be used on methods.

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.

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

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

@Target({ElementType.METHOD})
// u can also target multiple elements
//@Target({ ElementType.FIELD, ElementType.METHOD})
public @interface MyCustomAnnotation {

}
public class MyClass
{ @MyCustomAnnotati
on
public void myMethod()
{
//Doing something
}
}

Dept. of CSE Page


DSATM 25
Advanced Java and 18CS64
J2EE 4
public void myMethod()
{
//Doing something
}
}

7. @Retention

It indicates how long annotations with the annotated type are to be retained.

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
@interface MyCustomAnnotation {

Here we have used RetentionPolicy.RUNTIME. There are two other options as well. Lets see what do they
mean:

 RetentionPolicy.RUNTIME: The annotation should be available at runtime, for inspection


via javareflection.
 RetentionPolicy.CLASS: The annotation would be in the .class file but it would not be available at
runtime.
 RetentionPolicy.SOURCE: The annotation would be available in the source code of the program, it
would neither be in the .class file nor be available at the runtime.

Dept. of CSE Page


DSATM 26
Advanced Java and 18CS64
J2EE 4
Complete in one example
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited; import
java.lang.annotation.Retention; import
java.lang.annotation.RetentionPolicy;import
java.lang.annotation.Target;

@Documented
@Target(ElementType.METHOD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation{
int studentAge() default 18;
String studentName();
String stuAddress();
String stuStream() default "CSE";
}
@MyCustomAnnotation( studentName="umesh", stuAddress="India")
public class MyClass
{
...

Dept. of CSE Page


DSATM 27
Advanced Java and 18CS64
J2EE 4
Obtaining annotation at runtime using reflection

Reflection is an API which is used to examine or modify the behavior of methods, classes, interfaces at
runtime.

 The required classes for reflection are provided under java.lang.reflect package.

Reflection can be used to get information about –

 Class The getClass() method is used to get the name of the class to which an object belongs.
 Constructors The getConstructors() method is used to get the public constructors of the class to
which an object belongs.
 Methods The getMethods() method is used to get the public methods of the class to which an
objects belongs.

import java.lang.annotation.*;
import java.lang.reflect.*;
// An annotation type declaration.
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
String str();
int val();
}
class Meta {
// Annotate a method.
@MyAnno(str = "Annotation Example", val = 100)
public static void myMeth() {
Meta ob = new Meta();
// Obtain the annotation for this method
// and display the values of the members.

try {

// First, get a Class object that represents

// this class.
Class c = ob.getClass();
// Now, get a Method object that represents
// this method.
Method m = c.getMethod("myMeth");
// Next, get the annotation for this class.
MyAnno anno = m.getAnnotation(MyAnno.class);
// Finally, display the values.
System.out.println(anno.str() + " " + anno.val());
} catch (NoSuchMethodException exc) {

Dept. of CSE Page


DSATM 28
Advanced Java and 18CS64
J2EE 4
System.out.println("Method Not Found.");
}
}
public static void main(String args[])
{myMeth();
}
}
The output from the program is shown here:

Annotation Example 100

Obtaining All Annotations

You can obtain all annotations that have RUNTIME retention that are associated with an
item by calling getAnnotations( ) on that item. It has this general form:

Annotation[ ] getAnnotations( )

It returns an array of the annotations. getAnnotations( ) can be called on objects of type


Class, Method, Constructor, and Field.

// Show all annotations for a class and a method.


import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
String str();
int val();
}

@Retention(RetentionPolicy.RUNTIME)
@interface What {
String description();
}
@What(description = "An annotation test class")

@MyAnno(str = "Meta2", val = 99)

class Meta2 {
@What(description = "An annotation test method")
@MyAnno(str = "Testing", val = 100)
public static void myMeth()
{ Meta2 ob = new
Meta2();try {
Annotation annos[] = ob.getClass().getAnnotations();
// Display all annotations for Meta2.
System.out.println("All annotations for Meta2:");

Dept. of CSE Page


DSATM 29
Advanced Java and 18CS64
J2EE 4
for(Annotation a : annos)
System.out.println(a);
System.out.println();
// Display all annotations for myMeth.
Method m = ob.getClass( ).getMethod("myMeth");
annos = m.getAnnotations();
System.out.println("All annotations for myMeth:");
for(Annotation a : annos)
System.out.println(a);
} catch (NoSuchMethodException exc)
{ System.out.println("Method Not
Found.");
}
}
public static void main(String args[])
{myMeth();
}
}

The output is shown here:


All annotations for Meta2:
@What(description=An annotation test class)
@MyAnno(str=Meta2, val=99)
All annotations for myMeth:
@What(description=An annotation test method)
@MyAnno(str=Testing, val=100)

The AnnotatedElement Interface

The methods getAnnotation( ) and getAnnotations( ) used by the preceding examples are defined
by the AnnotatedElement interface, which is defined in java.lang.reflect. This interface supports
reflection for annotations and is implemented by the classes Method, Field,Constructor, Class, and Package.
In addition to getAnnotation( ) and getAnnotations( ), AnnotatedElement defines two other
methods. The first is getDeclaredAnnotations( ), which has this general form:

Annotation[ ] getDeclaredAnnotations( )

It returns all non-inherited annotations present in the invoking object. The second is

Dept. of CSE Page


DSATM 30
Advanced Java and 18CS64
J2EE 4
isAnnotationPresent( ), which has this general form:

boolean isAnnotationPresent(Class annoType)

It returns true if the annotation specified by annoType is associated with the


invokingobject. It returns falseotherwise.

Dept. of CSE Page


DSATM 31

You might also like