MODULE 1 AJAVA
MODULE 1 AJAVA
MODULE 1
Enumerations, Autoboxing and Annotations
Enumeration in Java
Definition: An enumeration is a data type that consists of a fixed set of constants. It
can represent days of the week, directions, etc., and has been available since JDK 1.5.
Characteristics:
o Constants are public, static, and final by default.
o Enumeration can have constructors, methods, and instance variables, but you
do not instantiate an enum using new.
o Enumerations are declared similarly to primitive variables.
Defining and Using Enumerations
Syntax:
enum Subject {
JAVA, CPP, C, DBMS
}
Usage:
o Declare an enum variable: Subject sub;
o Assign a value: sub = Subject.JAVA;
o Compare values using ==: if(sub == Subject.JAVA) { ... }
Example Programs
1. Simple Enumeration:
enum WeekDays {
sun, mon, tues, wed, thurs, fri, sat
}
class Test {
public static void main(String args[]) {
WeekDays wk = WeekDays.sun;
System.out.println("Today is " + wk);
}
}
Output: Today is sun
1
Advanced Java Programming 21CS642
2
Advanced Java Programming 21CS642
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
3
Advanced Java Programming 21CS642
}
Output:
All constants of enum type Restaurants are:
DOMINOS
KFC
PIZZAHUT
PANINOS
BURGERKING
I AM DOMINOS
Points to Remember About Enumerations
1. Enumerations are of class type and have all the capabilities of a Java class.
2. Enumerations can have constructors, instance variables, methods, and can even
implement interfaces.
3. Enumerations are not instantiated using the new keyword.
4. All enumerations by default inherit the java.lang.Enum class.
5. An enum may implement multiple interfaces but cannot extend any class because it
internally extends the Enum class.
Java Enumerations as Class Types
Class Type:
o Each enum constant is an object of its enumeration type.
o Constructors for an enum are called when each constant is created.
o Each constant has its own copy of any instance variables defined by the enum.
Example: Enumeration with Constructor, Instance Variable, and Method
enum Apple2 {
Jonathan(10), GoldenDel(9), RedDel(12), Winesap(15), Cortland(8);
// Variable
int price;
// Constructor
Apple2(int p) {
4
Advanced Java Programming 21CS642
price = p;
}
// Method
int getPrice() {
return price;
}
}
5
Advanced Java Programming 21CS642
6
Advanced Java Programming 21CS642
ap = Apple5.RedDel;
ap2 = Apple5.GoldenDel;
ap3 = Apple5.RedDel;
System.out.println();
if (ap.equals(ap2)) {
System.out.println("Error!");
}
if (ap.equals(ap3)) {
System.out.println(ap + " equals " + ap3);
}
}
}
Output:
Here are all apple constants and their ordinal values:
Jonathan 0
7
Advanced Java Programming 21CS642
GoldenDel 1
RedDel 2
Winesap 3
Cortland 4
RedDel comes before GoldenDel
RedDel equals RedDel
RedDel equals RedDel
Java Type Wrappers
Java provides type wrappers to encapsulate primitive types within objects. This is useful for
scenarios where you need to use primitive types as objects, such as when working with Java
Collections or other object-oriented frameworks.
1. Primitive Types and Performance:
o Java uses primitive types (e.g., int, double, float) for performance reasons.
2. Need for Object Representation:
o Many data structures and APIs in Java require objects, not primitives. Hence,
type wrappers are necessary.
3. Type Wrappers:
o Java provides wrapper classes for each primitive type, allowing them to be
treated as objects.
Wrapper Classes:
1. Character:
o Purpose: Encapsulates the primitive type char.
o Constructor: Character(char ch)
2. Boolean:
o Purpose: Encapsulates the primitive type boolean.
o Constructor: Boolean(boolean boolValue)
3. Numeric Type Wrappers:
o Byte: Byte
o Short: Short
o Integer: Integer
o Long: Long
o Float: Float
8
Advanced Java Programming 21CS642
o Double: Double
Boxing and Unboxing
Boxing and unboxing in Java deal with the conversion between primitive types and their
corresponding wrapper classes. This is particularly useful for situations where you need to
work with objects instead of primitive types.
Key Concepts:
1. Boxing: Encapsulating a primitive value within an object.
2. Unboxing: Extracting the primitive value from its wrapper object.
Example of Boxing and Unboxing:
class Wrap {
public static void main(String args[]) {
Integer iOb = new Integer(100); // Boxing
int i = iOb.intValue(); // Unboxing
System.out.println(i + " " + iOb); // displays 100 100
}
}
Explanation:
Boxing: Integer iOb = new Integer(100); - Encapsulates the primitive value 100 into
an Integer object.
Unboxing: int i = iOb.intValue(); - Extracts the primitive value from the Integer
object.
Autoboxing and Unboxing
Java 5 introduced autoboxing and auto-unboxing, simplifying the process by allowing
automatic conversion between primitives and their wrapper objects.
Example of Autoboxing and Unboxing:
class Test {
public static void main(String[] args) {
Integer iob = 100; // Autoboxing
int i = iob; // Auto-unboxing
System.out.println(i + " " + iob); // displays 100 100
9
Advanced Java Programming 21CS642
10
Advanced Java Programming 21CS642
Double d = 33.3;
d = d + i; // Auto-unboxing, addition, and autoboxing
System.out.println("Value of d is " + d); // displays Value of d is 68.3
}
}
Output:
Value of d is 68.3
Error Prevention with Autoboxing/Unboxing
Autoboxing and unboxing help prevent errors that can occur with manual boxing/unboxing,
such as type mismatches.
Example of Error with 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 !
}
}
Output:
-24
Explanation:
The value 1000 is manually unboxed using byteValue(), causing truncation and
resulting in an incorrect value of -24.
Autoboxing/unboxing avoids such errors by ensuring the proper type conversion.
Annotations / Metadata in Java
Annotations in Java provide a way to add metadata to your code, allowing tools, debuggers,
and applications to understand and utilize this information. This metadata can help in
analyzing, documenting, and controlling the behavior of the code.
11
Advanced Java Programming 21CS642
Key Points:
1. Definition:
o An annotation is a form of metadata that can be applied to various elements of
Java source code, including classes, methods, variables, parameters, and
packages.
2. Purpose:
o Annotations are used to add additional information to the code, which can be
utilized by tools and frameworks during compilation or at runtime.
3. Compilation and Reflection:
o Annotations are compiled into bytecode and can be accessed using reflection.
This allows the program to query the metadata information and perform
actions accordingly.
Example: Understanding Metadata
Consider the example of a class declared as final:
public final class MyFinalClass {
// other class members
}
Metadata: The final keyword in the class declaration is a metadata indicator.
Purpose: It tells the compiler and JVM that this class cannot be subclassed.
12
Advanced Java Programming 21CS642
o Example:
class Animal {
void eatSomething() {
System.out.println("eating something");
}
}
class AnnotationDemo2 {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("a");
13
Advanced Java Programming 21CS642
list.add("b");
list.add("c");
for (Object obj : list) {
System.out.println(obj);
}
}
}
3. @Deprecated
o Purpose: Marks a method or class as deprecated, meaning it is no longer
recommended for use and may be removed in future versions.
o Example:
class A {
void m() {
System.out.println("hello m");
}
@Deprecated
void n() {
System.out.println("hello n");
}
}
class AnnotationDemo3 {
public static void main(String[] args) {
A a = new A();
a.n(); // Output: hello n
}
}
Built-In Java Annotations for Other Annotations
1. @Retention
14
Advanced Java Programming 21CS642
o Purpose: Specifies how the annotation should be stored and accessed. It can
be retained at runtime, compile-time, or only in the source code.
o Example:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation {
// Some code
}
2. @Documented
o Purpose: Indicates that the annotation should be included in the Javadoc
generated for the annotated element.
o Example:
import java.lang.annotation.Documented;
@Documented
public @interface MyCustomAnnotation {
// Some code
}
3. @Target
o Purpose: Specifies the kinds of elements an annotation can be applied to, such
as classes, methods, fields, etc.
o Example:
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface MyCustomAnnotation {
// Some code
}
15
Advanced Java Programming 21CS642
4. @Inherited
o Purpose: Indicates that if an annotation is applied to a class, its subclasses will
inherit the annotation. Useful for class-level annotations that should be
inherited by subclasses.
o Example:
import java.lang.annotation.Inherited;
@Inherited
public @interface MyCustomAnnotation {
// Some code
}
@MyCustomAnnotation
class MyParentClass {
// Some code
}
16
Advanced Java Programming 21CS642
17
Advanced Java Programming 21CS642
3. Multi-Value Annotation
o Definition: An annotation with more than one method.
o Example:
@interface MyMultiValueAnnotation {
int value1() default 1;
String value2() default "";
String value3() default "xyz";
}
Example of Custom Annotations
Here’s how you can define and use a custom annotation:
1. Define the Annotation:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.Documented;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
@interface MyAnnotation2 {
int value() default 2;
String name() default "cse";
}
2. Apply the Annotation:
class Hello {
@MyAnnotation2(value=4, name="ise")
public void sayHello() {
// Some code
}
18
Advanced Java Programming 21CS642
}
3. Retrieve and Use the Annotation:
import java.lang.reflect.Method;
public class CustomAnnotation {
public static void main(String[] args) {
try {
Hello h = new Hello();
// Get Class object representing the class
Class<?> c = h.getClass();
// Get Method object representing the method
Method m = c.getMethod("sayHello");
// Get the annotation from the method
MyAnnotation2 anno = m.getAnnotation(MyAnnotation2.class);
// Display the values
System.out.println("Value: " + anno.value());
System.out.println("Name: " + anno.name());
} catch (Exception e) {
System.out.println("No such method exception: " + e.getMessage());
}
}
}
Restrictions on Annotations
No Inheritance: Annotations cannot inherit from other annotations.
Method Constraints: Methods in annotations must:
o Not have parameters.
o Not have a throws clause.
o Return one of the following:
A primitive type (e.g., int, double).
An object of type String or Class.
An enum type.
19
Advanced Java Programming 21CS642
20