Module 1 Enumerations Autoboxing and Annotations in Java 1
Module 1 Enumerations Autoboxing and Annotations in Java 1
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: [email protected]
Module 1: Enumerations Auto boxing and Annotations
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.
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
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;
byte byteValue( )
double doubleValue( )
float floatValue( )
int intValue( )
long longValue( )
short shortValue( )
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.
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
Output:
100
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.
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:
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.
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.
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.
@Retention(retention-policy)
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:
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.
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
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.
Question Bank