Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Module 1: Enumerations Auto boxing and

Annotations
Subject Code: 21CS642

4/16/2024
Rao Bahadur Y Mahabaleswarappa Engineering College Ballari
Dr Shiva Prasad KM, Associate Professor Department of CSE, RYMEC Ballari M:
7899964163 Email: shivakalmutt@gmail.com
Module 1: Enumerations Auto boxing and Annotations

Module 1: Enumerations and Autoboxing

1. Introduction of Java with a simple example:


As we all know any computer program always consists of two elements code
and data. Furthermore, a program can be conceptually organized around its
data or the data. That is, some programs are written around “what is
happening” and others are written around “who is being affected.”
Two paradigms govern how a program is constructed they are

 The first way is called the process-oriented model. This approach


characterizes a program as a series of linear steps (that is, code). The
process-oriented model can be thought of as code acting on data.
Procedural languages such as C employ this model to considerable
success.
 The second way called object-oriented programming, was conceived.
Object-oriented programming organizes a program around its data (that
is, objects) and a set of well-defined interfaces to that data. An object-
oriented program can be characterized as data controlling access to code.
As you will see, by switching the controlling entity to data, you can
achieve several organizational benefits.

Object-oriented programming (OOP) is at the core of Java. All Java programs are
to at least some extent object-oriented. Object-oriented programming is a
computer programming design philosophy or methodology that organizes/
models software design around data, or objects rather than functions and logic.
An object is referred to as a data field that has unique attributes and behaviour.
Everything in OOP is grouped as self-sustainable objects.Java is a high-level,
class-based, object-oriented programming language that is designed to have as
few implementation dependencies as possible. It is a general-purpose
programming language intended to let programmers write once, and run
anywhere (WORA), meaning that compiled Java code can run on all platforms
that support Java without the need to recompile.

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 2


Module 1: Enumerations Auto boxing and Annotations

The three different principles of Object-oriented programming are:

I. Encapsulation: Encapsulation in Java is the process of wrapping data


and methods into a single unit. This is done to protect data from being
accessed directly and to improve code maintainability.
II. Inheritance: Inheritance is the process by which one object acquires the
properties of another object. This is important because it supports the
concept of hierarchical classification.
For example, a Golden Retriever is part of the classification dog, which in
turn is part of the mammal class, which is under the larger class animal.
Without the use of hierarchies, each object would need to define all of its
characteristics explicitly.
However, by use of inheritance, an object need only define those qualities
that make it unique within its class. It can inherit its general attributes
from its parent. Thus, it is the inheritance mechanism that makes it
possible for one object to be a specific instance of a more general case.
III. Polymorphism: Polymorphism (from Greek, meaning “many forms”) is a
feature that allows one interface to be used for a general class of actions.
The specific action is determined by the exact nature of the situation.
1.2. The first simple Program in Java:
Let us start writing compiling and executing a simple Java program as shown
below here. As you will see this involves a little more work than you might
imagine.
/*
This is a Simple Java Program. Call this file as “Example.java”.*/
class Example {
//Your program always begins with a call to main()
Public static void main( String args) {
System. out.println(“Welcome to Java Programming Language”);
}}
Entering the Program:

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 3


Module 1: Enumerations Auto boxing and Annotations

The first thing that you must learn about Java is that the name you give to a
source file is very important. For this example, the name of the source file
should be Example.java. Let’s see why
 In Java, a source file is officially called a compilation unit. It is a text file
that contains (among other things) one or more class definitions. (For
now, we will be using source files that contain only one class.) The Java
compiler requires that a source file use the .java filename extension.
 As you can see by looking at the program, the name of the class defined
by the program is also an Example. This is not a coincidence. In Java, all
code must reside inside a class. By convention, the name of the main
class should match the name of the file that holds the program.
 You should also make sure that the capitalization of the filename
matches the class name. The reason for this is that Java is case-
sensitive.
Compiling the Program:
 To compile the Example program, execute the compiler, javac, specifying
the name of the source file on the command line, as shown here:
C:\> javac Example.java
 The Javac compiler creates a file called Example. class that contains the
byte code version of the program. Thus, the output of javac is not code
that can be directly executed.
 To run the program, you must use the Java application launcher
called java. To do so, pass the class name Example as a command-line
argument, as shown here:
C:\>java Example
 When the program is run, the following output is displayed:
Welcome to Java Programming Language

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 4


Module 1: Enumerations Auto boxing and Annotations

1.3. Enumerations:
An enumeration in Java is a special data type used to define a collection of
constants. It's declared using the enum keyword. They allow you to declare a
type that represents a fixed set of constants. In their simplest form, Java
enumerations appear similar to enumerations in other languages. Each
constant within the enumeration is an instance of the enum type.
The syntax of Enumeration is:
enum TypeName {
CONSTANT1,
CONSTANT2,
// More constants...
}
Although Java offered other features that provide somewhat similar
functionality, such as final variables, many programmers still missed the
conceptual purity of enumerations especially because enumerations are
supported by many other commonly used languages. In Java, an enumeration
can have constructors, methods, and instance variables.
Example 1: Write a Java program to represent and print the constant
values using Enumeration.
// Define an enumeration named Day
enum Day {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}
public class Enumeration {
public static void main(String[] args) {
// Accessing enum constants
Day today = Day.WEDNESDAY;

// Output the current day


System. out.println("Today is: " + today);

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 5


Module 1: Enumerations Auto boxing and Annotations

// Switch statement with enum


switch(today) {
case SUNDAY:
System. out.println("It's Sunday!");
break;
case MONDAY:
System. out.println("It's Monday!");
break;
case TUESDAY:
System. out.println("It's Tuesday!");
break;
case WEDNESDAY:
System. out.println("It's Wednesday!");
break;
case THURSDAY:
System. out.println("It's Thursday!");
break;
case FRIDAY:
System. out.println("It's Friday!");
break;
case SATURDAY:
System. out.println("It's Saturday!");
break;
}
}
}
Output:
Today is: WEDNESDAY
It's Wednesday!

Example 2: Write a Java program to demonstrate Enumeration on apples


and print the output.
// Define an enumeration named AppleVariety
enum AppleVariety {
FUJI,
GRANNY_SMITH,
HONEYCRISP,
GALA
}
public class appledemo {
public static void main(String[] args) {
// Accessing enum constants
AppleVariety myApple = AppleVariety.FUJI;

// Output the selected apple variety

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 6


Module 1: Enumerations Auto boxing and Annotations

System. out.println("My favorite apple variety is: " +


myApple);

// Switch statement with enum


switch(myApple) {
case FUJI:
System. out.println("Fuji apples are sweet and
crisp.");
break;
case GRANNY_SMITH:
System. out.println("Granny Smith apples are tart and
crisp.");
break;
case HONEYCRISP:
System. out.println("Honeycrisp apples are sweet and
juicy.");
break;
case GALA:
System. out.println("Gala apples are sweet and
aromatic.");
break;
}
}
}
Output:
My favorite apple variety is: FUJI
Fuji apples are sweet and crisp.

1.4. The values( ) and valueof( ) method:


All enumerations automatically contain two predefined methods: values ( ) and
valueOf( ). Their general forms are shown here:
public static enum-type [ ] values( )
public static enum-type valueOf(String str )
The values( ) method returns an array that contains a list of the enumeration
constants. The valueOf( ) method returns the enumeration constant whose
value corresponds to the string passed in str. In both cases, enum-type is the
type of the enumeration.

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 7


Module 1: Enumerations Auto boxing and Annotations

Example 3: Write a Java program to demonstrate values() and valueof()


methods in enumeration on apples and print the output.
// Use the built-in enumeration methods.
// An enumeration of apple varieties.
enum Apple {
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}
class EnumDemo2 {
public static void main(String args[])
{
Apple ap;
System. out.println("Here are all Apple constants:");
// use values()
Apple allapples[] = Apple.values();
for(Apple a : allapples)
System.out.println(a);
System.out.println();
// use valueOf()
ap = Apple.valueOf("Winesap");
System.out.println("ap contains " + ap);
}
}
Output:
Here are all Apple constants:
Jonathan
GoldenDel
RedDel
Winesap
Cortland
ap contains Winesap

1.5. Java enumerations are class types:


A Java enumeration is a class type. Although you don’t instantiate an enum
using new, it otherwise has much the same capabilities as other classes.
The fact that enum defines a class gives the Java enumeration extraordinary
power. For example, you can give them constructors, add instance variables and
methods, and even implement interfaces. The below example represents the
implementation of class types with the support of methods instances and
constructors.

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 8


Module 1: Enumerations Auto boxing and Annotations

Example 4: Write a Java program to demonstrate enumeration on apples by


using enumeration methods, instance variables and constructors.
// Define an enumeration named AppleVersion
enum AppleVersion {
IPHONE_13("iPhone 13", 2021),
IPAD_PRO("iPad Pro", 2021),
MACBOOK_PRO("MacBook Pro", 2021);
private final String modelName;
private final int releaseYear;
// Constructor
AppleVersion(String modelName, int releaseYear) {
this.modelName = modelName;
this.releaseYear = releaseYear;
}
// Method to get the model name
public String getModelName() {
return modelName;
}
// Method to get the release year
public int getReleaseYear() {
return releaseYear;
}
}
public class AppleDemo {
public static void main(String[] args) {
// Accessing enum constants
AppleVersion myPhone = AppleVersion.IPHONE_13;
AppleVersion myTablet = AppleVersion.IPAD_PRO;
AppleVersion myLaptop = AppleVersion.MACBOOK_PRO;

// Output details of each Apple product


System.out.println("My phone is " + myPhone.getModelName() + " released in " +
myPhone.getReleaseYear());
System.out.println("My tablet is " + myTablet.getModelName() + " released in " +
myTablet.getReleaseYear());
System.out.println("My laptop is " + myLaptop.getModelName() + " released in " +
myLaptop.getReleaseYear());
}
}
Output:
My phone is iPhone 13 released in 2021
My tablet is an iPad Pro released in 2021
My laptop is a MacBook Pro released in 2021

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 9


Module 1: Enumerations Auto boxing and Annotations

1.6. Enumeration inherits Enum:


In Java, all enums implicitly inherit the Enum class. The Enum class provides
several methods that are available to all enum types. Although you can’t
inherit a superclass when declaring an enum, all enumerations
automatically inherit one java.lang.Enum. This class defines several methods
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, shown here:
final int ordinal( )
It returns the ordinal value of the invoking constant. Ordinal values begin
at zero.
 You can compare the ordinal value of two constants of the same
enumeration by using the compareTo( ) method. It has this general form:
final int compareTo(enum-type e)
Here, enum-type is the type of the enumeration, and e is the constant
being compared to the invoking constant. Remember, both the invoking
constant and e must be of the same enumeration. If the invoking constant
has an ordinal value less than e’s, then compareTo( ) returns a negative
value. If the two ordinal values are the same, then zero is returned. If the
invoking constant has an ordinal value greater than e, then a positive
value is returned.
 You can compare for equality an enumeration constant with any other
object by using equals( ), which overrides the equals( ) method defined
by the Object. Remember, you can compare two enumeration
references for equality by using = =.
 Note: Ordinal, compareto and equals methods plays an important role
in this concept

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 10


Module 1: Enumerations Auto boxing and Annotations

Example 5: Write a Java program to demonstrate ordinal value, compare to


and equal enumeration method.
// Define an enumeration named Month
enum Month {
JANUARY,
FEBRUARY,
MARCH,
APRIL,
MAY,
JUNE,
JULY,
AUGUST,
SEPTEMBER,
OCTOBER,
NOVEMBER,
DECEMBER
}
public class EnumMethodsDemo {
public static void main(String[] args) {
// Accessing enum constants
Month current month = Month.APRIL;
Month next month = Month.MAY;
Month sameMonth = Month.APRIL;
// Output the ordinal value of the current month
System. out.println("The Ordinal value of current month: " +
currentmonth.ordinal());
// Output the result of the compareTo method
System. out.println("Result of comparing currentMonth to nextMonth:
" + currentMonth.compareTo(nextMonth));
// Output the result of the equals method
System. out.println("Is currentMonth equal to nextMonth? " +
currentMonth.equals(nextMonth));
// Output the result of the equals method for the same month
System. out.println("Is currentMonth equal to sameMonth? " +
currentMonth.equals(sameMonth));
}
}
Output:
The ordinal value of currentMonth: 3
Result of comparing currentMonth to nextMonth: -1
Is currentMonth equal to nextMonth? false
Is currentMonth equal to sameMonth? true

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 11


Module 1: Enumerations Auto boxing and Annotations

1.7. Type Wrappers in Java


Type wrappers, also known as wrapper classes, are classes in Java that
encapsulate primitive data types within an object. They provide a way to
convert primitive data types into objects so that they can be included in
activities such as collections, which require objects rather than primitives.
The type wrappers are Double, Float, Long, Integer, Short, Byte,
Character, and Boolean. These classes offer a wide array of methods that
allow you to fully integrate the primitive types into Java’s object hierarchy
The non-numeric type wrappers are represented below as follows:
 Character is a wrapper around a char. The constructor for the Character
is
Character(char ch)
Here, ch specifies the character that will be wrapped by the Character
object being created. To obtain the char value contained in a Character
object, call charValue( ), shown here:
char charValue( )
It returns the encapsulated character.
 Boolean is a wrapper around boolean values. It defines these
constructors
Boolean(boolean boolValue)
Boolean(String boolString)
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.
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 numeric type wrappers are represented below as follows:

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 12


Module 1: Enumerations Auto boxing and Annotations

byte byteValue( )
double doubleValue( )
float floatValue( )
int intValue( )
long longValue( )
short shortValue( )

For example: doubleValue( ) returns the value of an object as a double,


floatValue( ) returns the value as a float, and so on. These methods are
implemented by each of the numeric type wrappers.
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.
Example 6: Write a Java program to demonstrate numeric and non-
numeric type wrappers.
public class TypeWrapperDemo {
public static void main(String[] args) {
// Numeric type wrappers
Integer intValue = new Integer(42);
Double doubleValue = new Double(3.14);
// Non-numeric type wrappers
Character charValue = new Character('A');
Boolean boolValue = new Boolean(true);

// Output numeric type wrappers


System. out.println("Integer value: " + intValue);
System. out.println("Double value: " + doubleValue);
// Output non-numeric type wrappers
System. out.println("Character value: " + charValue);
System. out.println("Boolean value: " + boolValue);

// Convert wrapper objects to primitive types


int primitiveInt = intValue.intValue();

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 13


Module 1: Enumerations Auto boxing and Annotations

double primitiveDouble = doubleValue.doubleValue();


char primitiveChar = charValue.charValue();
boolean primitiveBool = boolValue.booleanValue();

// Output primitive type values


System. out.println("Primitive int value: " + primitiveInt);
System. out.println("Primitive double value: " + primitiveDouble);
System. out.println("Primitive char value: " + primitiveChar);
System. out.println("Primitive boolean value: " + primitiveBool);
}
}
Output:
Integer value: 42
Double value: 3.14
Character value: A
Boolean value: true
Primitive int value: 42
Primitive double value: 3.14
Primitive char value: A
Primitive boolean value: true

1.8. 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. 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.
Auto-unboxing greatly streamlines the coding of several algorithms, removing
the tedium of manual boxing and unboxing values. It also helps prevent errors.
Example 6: Write a Java program to demonstrate autoboxing and auto-
unboxing methods.

public class AutoboxingExample {


public static void main(String[] args) {
// Autoboxing: converting primitive int to an Integer object
Integer intValue = 42; // Autoboxing
// Autoboxing: converting primitive double to Double-object
Double doubleValue = 3.14; // Autoboxing
// Autoboxing: converting primitive boolean to Boolean object

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 14


Module 1: Enumerations Auto boxing and Annotations

Boolean boolValue = true; // Autoboxing


// Autoboxing: converting primitive char to Character object
Character charValue = 'A'; // Autoboxing
// Output autoboxed values
System. out.println("Integer value: " + intValue);
System. out.println("Double value: " + doubleValue);
System. out.println("Boolean value: " + boolValue);
System. out.println("Character value: " + charValue);
// Unboxing: converting Integer object to primitive int
int unboxed it = intValue; // Unboxing
// Unboxing: converting Double-object to primitive double
double unboxedDouble = doubleValue; // Unboxing
// Unboxing: converting a Boolean object to a primitive boolean
boolean unboxedBool = boolValue; // Unboxing
// Unboxing: converting Character object to primitive char
char unboxedChar = charValue; // Unboxing
// Output unboxed values
System. out.println("Unboxed int value: " + unboxed it);
System. out.println("Unboxed double value: " + unboxedDouble);
System. out.println("Unboxed boolean value: " + unboxedBool);
System. out.println("Unboxed char value: " + unboxedChar);
}
}

Output:
Integer value: 42
Double value: 3.14
Boolean value: true
Character value: A
Unboxed int value: 42
Unboxed double value: 3.14
Unboxed boolean value: true
Unboxed char value: A

1.9. Autoboxing methods:


In addition to the simple case of assignments, autoboxing automatically occurs
whenever a primitive type must be converted into an object; auto-unboxing takes
place whenever an object must be converted into a primitive type. Thus,
autoboxing/unboxing might occur when an argument is passed to a method, or
when a value is returned by a method.

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 15


Module 1: Enumerations Auto boxing and Annotations

Example 7: Write a Java program to demonstrate autoboxing and auto-


unboxing methods.

// Autoboxing/unboxing takes place with


// method parameters and return values.
class AutoBox2 {
// Take an Integer parameter and return an int value;
static int m(Integer v) {
return v ; // auto-unbox to int
}
public static void main(String args[]) {
// Pass an int to m() and assign the return value to an Integer. Here, the
argument 100 is autoboxed into an Integer. The return value is also autoboxed
into an Integer.
Integer iOb = m(100);
System.out.println(iOb);
}

Output:
100

1.10. Autoboxing and Unboxing Occurs in the Expressions:


In general, 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.

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 16


Module 1: Enumerations Auto boxing and Annotations

Example 8: Write a Java program to demonstrate autoboxing and auto-


unboxing that occurs in expressions.

// Autoboxing/unboxing occurs inside expressions.


class AutoBox3 {
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);
// Here, iOb is unboxed, the expression is
// evaluated, and the result is reboxed and
// assigned to iOb2.
iOb2 = iOb + (iOb / 3);
System.out.println("iOb2 after expression: " + iOb2);
// The same expression is evaluated, but the
// result is not reboxed.
i = iOb + (iOb / 3);
System. out.println("i after expression: " + i);
}
}
Output:
Original value of iOb: 100
After ++iOb: 101
iOb2 after expression: 134
I after expression: 134

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 17


Module 1: Enumerations Auto boxing and Annotations

1.11. Autoboxing/Autounboxing Boolean and Characters values:


Java also supplies wrappers for Boolean and char. These are Boolean and
Character. Autoboxing/unboxing applies to these wrappers, too. For example,
consider the following program:

//Autoboxing/unboxing a Boolean and Character.


class AutoBox5 {
public static void main(String args[]) {
// Autobox/unbox a boolean.
Boolean b = true;
// Below, b is auto-unboxed when used in
// a conditional expression, such as an if.
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);
}
}
OUTPUT:
b is true
ch2 is x

The most important thing to notice about this program is the auto-unboxing of b
inside the if conditional expression. As you should recall, the conditional
expression that controls an if must evaluate to type a boolean. Because of auto-
unboxing, the boolean value contained within b is automatically unboxed when
the conditional expression is evaluated. Thus, with the advent of
autoboxing/unboxing, a Boolean object can be used to control an if statement.

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 18


Module 1: Enumerations Auto boxing and Annotations

1.12. Autoboxing and unboxing prevent errors:


In addition to the convenience that it offers, autoboxing/unboxing can also help
prevent errors. For example, consider the following program:

// An error produced by manual unboxing.


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

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.
In general, because autoboxing always creates the proper object, and auto-unboxing
always produces the proper value, there is no way for the process to produce the
wrong type of object or value.
1.13. Annotations & Basics of Annotations
An annotation is created through a mechanism based on the interface. Let’s begin
with an example. Here is the declaration for an annotation called MyAnno:

// A simple annotation type.


@interface MyAnno {
String str();
int val();
}

First, notice the @ that precedes the keyword interface. This tells the compiler that
an annotation type is being declared. Next, notice the two members str( ) and val( ).
All annotations consist solely of method declarations. An annotation cannot include
an extended clause. However, all annotation types automatically extend the
Annotation interface.

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 19


Module 1: Enumerations Auto boxing and Annotations

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.

Once you have declared an annotation, you can use it to annotate something.
Before JDK 8, annotations could be used only on declarations, and that is where we
will begin. Any type of declaration can have an annotation associated with it. For
example, classes, methods, fields, parameters, and enum constants can be
annotated. Even an annotation can be annotated. In all cases, the annotation
precedes the rest of the declaration.

1.14. Specifying 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.
Retention Policy 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.

A retention policy is specified for an annotation by using one of Java’s built-in


annotations: @Retention. Its general form is shown here:

@Retention(retention-policy)

Here, retention policy must be one of the previously discussed enumeration


constants. If no retention policy is specified for an annotation, then the default
policy of CLASS is used.

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 20


Module 1: Enumerations Auto boxing and Annotations

1.15. Obtaining Annotations at run time by use of reflections

Reflection is the feature that enables information about a class to be obtained at


run time. The reflection API is contained in the java. lang. reflect package.

The first step to using reflection is to obtain a Class object that represents the class
whose annotations you want to obtain. Class is one of Java’s built-in classes and is
defined in Java. lang. There are various ways to obtain a Class object. One of
the easiest is to call getClass ( ), which is a method defined by Object. Its
general form is shown here:

final Class<?> getClass ( )

It returns the Class objects that represents the invoking object.

1.16. Annotated Element interfaces:


 The methods getAnnotation( ) and getAnnotations( ) used by the preceding
examples are defined by the Annotated Element 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, among others.
 In addition to getAnnotation( ) and getAnnotations( ), AnnotatedElement defines
several other methods. Two have been available since JDK 5.
o The first is getDeclaredAnnotations( ), which has this general form:
Annotation[ ] getDeclaredAnnotations( )
It returns all non-inherited annotations present in the invoking object.
o The second is isAnnotationPresent( ), which has this general form:
boolean isAnnotationPresent(Class<? extends Annotation> annoType)
It returns true if the annotation specified by annoType is associated with
the invoking object. It returns false otherwise.

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 21


Module 1: Enumerations Auto boxing and Annotations

1.17. 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.
 Example for Marker Annotation is represented below:

import java.lang.annotation.*;
import java.lang.reflect.*;
// A marker annotation.
@Retention(RetentionPolicy.RUNTIME)
@interface MyMarker { }
class Marker {
// Annotate a method using a marker.
// Notice that no ( ) is needed.
@MyMarker
public static void myMeth() {
Marker ob = new Marker();
try {
Method m = ob.getClass().getMethod("myMeth");
// Determine if the annotation is present.
if(m.isAnnotationPresent(MyMarker.class))
System.out.println("MyMarker is present.");
} catch (NoSuchMethodException exc) {
System.out.println("Method Not Found.");
}
}
public static void main(String args[]) {
myMeth();
}
}
The output, shown here, confirms that @MyMarker is present:
MyMarker is present.

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 22


Module 1: Enumerations Auto boxing and Annotations

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

Here is an example that creates and uses a single-member annotation:


import java.lang.annotation.*;
import java.lang.reflect.*;
// A single-member annotation.
@Retention(RetentionPolicy.RUNTIME)
@interface MySingle {
int value(); // this variable name must be value
}
class Single {
// Annotate a method using a single-member annotation.
@MySingle(100)
public static void myMeth() {
Single ob = new Single();
try {
Method m = ob.getClass().getMethod("myMeth");
MySingle anno = m.getAnnotation(MySingle.class);
System.out.println(anno.value()); // displays 100
} catch (NoSuchMethodException exc) {
System.out.println("Method Not Found.");
}
}
public static void main(String args[]) {
myMeth();
}
}

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 23


Module 1: Enumerations Auto boxing and Annotations

1.19. Built-in Annotations

Java defines many built-in annotations. Most are specialized, but nine are general
purpose. Of these, four are imported from java.lang.annotation.

1. @Retention:
@Retention is designed to be used only as an annotation to another annotation.
It is used to specify the retention policy.
2. @Documented:
The @Documented annotation is a marker interface that tells a tool that an
annotation is to be documented. It is designed to be used only as an annotation
to an annotation declaration.
3. @Target:
The @Target annotation specifies the types of items to which an annotation can
be applied. It is designed to be used only as an annotation to another
annotation. @Target takes one argument, which is an array of constants of the
ElementType enumeration. This argument specifies the types of declarations to
which the annotation can be applied.

4. @Inhertited:
@Inherited is a marker annotation that can be used only on another annotation
declaration. Furthermore, it affects only annotations that will be used on class

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 24


Module 1: Enumerations Auto boxing and Annotations

declarations. @Inherited causes the annotation for a superclass to be inherited


by a subclass.
If that annotation is present in the superclass, and if it is annotated with
@Inherited, then that annotation will be returned.
5. @Override:
@Override 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.
6. @Deprecated:
@Deprecated is a marker annotation. It indicates that a declaration is obsolete
and has been replaced by a newer form.
7. @Functional Interface:

A functional interface is an interface that contains one and only one abstract
method. Functional interfaces are used by lambda expressions. If the annotated
interface is not a functional interface, a compilation error will be reported. It is
important to understand that @FunctionalInterface is not needed to create a
functional interface. Any interface with exactly one abstract method is, by
definition, a functional interface. Thus, @FunctionalInterface is purely
informational.
8. @Safevarargs:
@SafeVarargs is a marker annotation that can be applied to methods and
constructors. It indicates that no unsafe actions related to a varargs parameter
occur. It is used to suppress unchecked warnings on otherwise safe code as it
relates to non-reifiable vararg types and parameterized array instantiation.
9. @SuppressWarnings:
@SuppressWarnings specifies that one or more warnings that might be issued by
the compiler are to be suppressed. The warnings to suppress are specified by
name, in string form.

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 25


Module 1: Enumerations Auto boxing and Annotations

Question Bank

Dr Shiva Prasad KM Associate Professor Dept of CSE RYMEC M: 7899964163 Page 26

You might also like