Advanced Java VTU Mod 1
Advanced Java VTU Mod 1
Module -1
Enumerations, Autoboxing, and Annotations(Metadata)
Enumerations
Enumerations included in JDK 5. An enumeration is a list of named constants.
It is similar to final variables.
Enum in java is a data type that contains fixed set of constants.
An enumeration defines a class type in Java. By making enumerations into
classes, so it can have constructors, methods, and instance variables.
An enumeration is created using the enum keyword.
Ex:
Enumeration variable can be created like other primitive variable. It does not
use the new for creating object.
Ex:Apple ap;
Ap is of type Apple, the only values that it can be assigned (or can contain)
are those defined by the enumeration. For example, this assigns:
ap = Apple.RedDel;
Example Code-1
class EnumDemo
{
public static void main(String args[])
{
Apple ap;
ap = Apple.RedDel;
System.out.println("Value of ap: " + ap);// Value of ap: RedDel
ap = Apple.GoldenDel;
if(ap == Apple.GoldenDel)
System.out.println("ap contains GoldenDel.\n"); // ap contains GoldenDel.
switch(ap)
{
case Jonathan:
System.out.println("Jonathan is red.");
break;
case GoldenDel:
System.out.println("Golden Delicious is yellow.");// Golden Delicious is yellow
break;
case RedDel:
System.out.println("Red Delicious is red.");
break;
case Winesap:
System.out.println("Winesap is red.");
break;
case Cortland:
System.out.println("Cortland is red.");
break;
}
}
}
The values( ) and valueOf( ) Methods All enumerations automatically contain two predefined
methods: values( ) and valueOf( ).
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.
Example Code-2:
class EnumExample1{
System.out.println(s);
Season s = Season.valueOf("WINTER");
} }
Example Code-3
class EnumExample5{
Day day=Day.MONDAY;
switch(day){
case SUNDAY:
System.out.println("sunday");
break;
case MONDAY:
System.out.println("monday");
break;
default:
System.out.println("other day");
}}
enum Apple {
Apple(int p) { price = p; }
class EnumDemo3 {
{ Apple ap;
for(Apple a : Apple.values())
The first is the instance variable price, which is used to hold the price of each
variety of apple.
The second is the Apple constructor, which is passed the price of an apple.
The third is the method getPrice( ), which returns the value of price.
When the variable ap is declared in main( ), the constructor for Apple is called once for
each constant that is specified.
the arguments to the constructor are specified, by putting them inside parentheses after each
constant, as shown here:
These values are passed to the parameter of Apple(),which then assigns this value to price.
The constructor is called once for each constant.
Because each enumeration constant has its own copy of price, you can obtain the price of
a specified type of apple by calling getPrice().
Enum class defines several methods that are available for use by all enumerations.
ordinal( )
It returns the ordinal value of the invoking constant. Ordinal values begin at zero. Thus, in
the Apple enumeration, Jonathan has an ordinal value of zero, GoldenDel has an ordinal
value of 1, RedDel has an ordinal value of 2, and so on.
compareTo( )
To compare the ordinal value of two constants of the same enumeration by using the
compareTo( ) method. It has this general form:
equals()
equals method is overridden method from Object class, it is used to compare the
enumeration constant. Which returns true if both constants are same.
class EnumDemo4
System.out.println("Here are all apple constants" + " and their ordinal values: ");
for(Apple a : Apple.values())
ap = Apple.RedDel;
ap2 = Apple.GoldenDel;
ap3 = Apple.RedDel;
System.out.println();
System.out.println();
if(ap.equals(ap2)) System.out.println("Error!");
Wrappers Classes
Java uses primitive types such as int or double, to hold the basic data types supported
by the language.
The primitive types are not part of the object hierarchy, and they do not inherit Object.
Despite the performance benefit offered by the primitive types, there are times when you
will need an object representation.
Many of the standard data structures implemented by Java operate on objects, which
means that you can’t use these data structures to store primitive types.
To handle the above situation, Java provides type wrappers, which are classes that
encapsulate a primitive type within an object.
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.
Character:
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( )
Boolean:
Boolean(boolean boolValue)
Boolean(String boolString)
In the second version, if boolString contains the string “true” (in uppercase or
lowercase), then the new Boolean object will be true. Otherwise, it will be false.
To obtain a boolean value from a Boolean object, use booleanValue( ), shown here:
boolean booleanValue( )
Integer(int num)
Integer(String str)
class Wrap
int i = iOb.intValue();
This program wraps the integer value100 inside an Integer object called iOb.
The program then obtains this value by calling intValue() and stores the result in i.
Thus, in the program, this line boxes the value 100 into an Integer:
int i = iOb.intValue();
AutoBoxing
Auto-unboxing
Auto- unboxing is the process by which the value of a boxed object is automatically
extracted from a type wrapper when it is assigned to primitive type value is needed.
Example Program:
class AutoBoxUnBox
class AutoBox2 {
{ return v ; }
System.out.println(iOb);// 100
In the program, notice that m( ) specifies an Integer parameter and returns an int
result.
Then, m( ) returns the int equivalent of its argument. This causes v to be auto-unboxed.
Next, this int value is assigned to iOb in main( ), which causes the int return value to be
autoboxed.
The outcome of the expression is reboxed, if necessary. For example, consider the
following program:
class AutoBox3
iOb = 100;
++iOb;
It works like this: iOb is unboxed, the value is incremented, and the result is reboxed.
Integer iOb = 2;
switch(iOb) {
case 1: System.out.println("one");
break;
case 2: System.out.println("two");
break;
default:
System.out.println("error");
When the switch expression is evaluated, iOb is unboxed and its int value is obtained.
if(b)
}}
b is true ch2 is x
Annotations
Annotations (Metadata) Beginning with JDK 5, a new facility was added to Java that
enables you to embed supplemental information into a source file.
This information, called an annotation, 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.
@Retention(retention-policy)
@Retention(RetentionPolicy.RUNTIME)
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
class Meta {
// Annotate a method.
Jayanthi M.G , Associate Professor ,Department of CSE, Cambridge Institute of Technology.
Advance Java and J2EE –Module 1
try {
Class c = ob.getClass();
Method m = c.getMethod("myMeth");
This program uses reflection as described to obtain and display the values of str and val in
the MyAnnoannotation associated with myMeth()in the Metaclass.
notice the expression MyAnno.class. This expression evaluates to a Class object of type
MyAnno, the annotation.
This construct is called a class literal. You can use this type of expression whenever a
Class object of a known class is needed.
However, to obtain a method that has parameters, you must specify class objects
representing the types of those parameters as arguments to getMethod( ). For example,
here is a slightly different version of the preceding program:
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
class Meta {
{ myMeth("test", 10); }
Two Parameters 19
To obtain information about this method, getMethod( ) must be called as shown here:
Here, the Class objects representing String and int are passed as additional arguments.
You can obtain all annotations that have RUNTIME retention that are associated with an
item by calling getAnnotations( ) on that item.
Annotation[ ] getAnnotations( )
getAnnotations( ) can be called on objects of type Class, Method, Constructor, and Field.
Here is another reflection example that shows how to obtain all annotations associated
with a class and with a method.
Example code:
@Retention(RetentionPolicy.RUNTIME)
@Retention(RetentionPolicy.RUNTIME)
System.out.println();
annos = m.getAnnotations();
for(Annotation a : annos)
System.out.println(a);
@MyAnno(str=Meta2, val=99)
@MyAnno(str=Testing, val=100)
The program uses getAnnotations( ) to obtain an array of all annotations associated with
the Meta2 class and with the myMeth( ) method. As explained, getAnnotations( ) returns
an array of Annotation objects.
Recall that Annotation is a super-interface of all annotation interfaces and that it overrides
toString( ) in Object.
1. getAnnotation( ) --- It can be invoked with method, class. It return the used
annotation.
2. getAnnotations( ) --- It can be invoked with method, class. It return the used
annotations.
3. getDeclaredAnnotations( ) -- It returns all non-inherited annotations present in the
invoking object.
4. isAnnotationPresent( ), which has this general form:
It returns true if the annotation specified by annoType is
associated with the invoking object. It returns false otherwise.
You can give annotation members default values that will be used if no value is specified
when the annotation is applied.
@interface MyAnno { String str() default "Testing"; int val() default 9000; }
Example:
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno { String str() default "Testing"; int val() default 9000; }
class Meta3 {
@MyAnno()
Method m = c.getMethod("myMeth");
Output:
Testing 9000
Marker Annotations
Its sole purpose is to mark a declaration. 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 a defined by the AnnotatedElement interface.
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
@interface MyMarker { }
class Marker {
@MyMarker
if(m.isAnnotationPresent(MyMarker.class))
System.out.println("MyMarker is present.");
Output
MyMarker is present.
Built in Annotations
Java Annotation is a tag that represents the metadata i.e. attached with class, interface,
methods or fields to indicate some additional information which can be used by java
compiler and JVM.
@Override
@SuppressWarnings
@Deprecated
@Target
@Retention
@Inherited
@Documented
@Override
@Override annotation assures that the subclass method is overriding the parent class method.
If it is not so, compile time error occurs.Sometimes, we does the silly mistake such as
spelling mistakes etc. So, it is better to mark @Override annotation that provides assurity that
method is overridden.
void eatSomething()
{System.out.println("eating something");}
}
class Dog extends Animal{
@Override
void eatsomething()
{
System.out.println("eating foods");
}//Compile time error }
@SuppressWarnings
annotation: is used to suppress warnings issued by the compiler.
import java.util.*;
class TestAnnotation2{
@SuppressWarnings("unchecked")
list.add("sonoo");
}}
@Deprecated
@Deprecated annoation marks that this method is deprecated so compiler prints warning. It
informs user that it may be removed in the future versions.
class A{
@Deprecated
class TestAnnotation3{
A a=new A();
a.n();
}}
@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 declarations. @Inherited causes the
annotation for a superclass to be inherited by a subclass.
@Inherited
public @interface MyCustomAnnotation {
}
@MyCustomAnnotation
public class MyParentClass {
...
}
public class MyChildClass extends MyParentClass {
...
}
@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
@Target
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.
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
public @interface MyCustomAnnotation {
}
public class MyClass {
@MyCustomAnnotation
public void myMethod()
{
//Doing something
}
}
If you do not define any Target type that means annotation can be applied to any element.