Module 1 Notes
Module 1 Notes
J2EE 4
IA Marks: 20
ADVANCED JAVA and
J2EE Exam Hours: 3
Exam Marks: 80
MODULE-I 8 Hours
MODULE-II 8 Hours
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
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.
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.
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) {
...
}
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);
}
}
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
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,
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
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
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;
}
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.
}} output
Season is SUMMER value is 15
WINTER 5
SPRING 10
SUMMER 15
FALL -1
Output:
enum Tutorials
{ topic1, topic2,
topic3;
}
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;
}
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
enum Apple
{
shimla, ooty, wood, green, red
}
class dsatm
{
public static void main(String args[])
{
Apple ap, ap2, ap3;
ap = Apple.wood;
ap2 = Apple.ooty;
ap3 = Apple.wood;
System.out.println();
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))
if(ap == ap3)
System.out.println(ap + " == " + ap3);
}
}
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.
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.
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
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
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.
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
class UnboxingExample1{
public static void main(String
args[]){Integer i=new Integer(50);
int a=i;
System.out.println(a);
}
}
Output:50
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.
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.
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
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.
There are 7 built-in annotations in java. Some annotations are applied to java code and some to other
annotations.
@Override
@SuppressWarnings
@Deprecated
@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()
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()");
}
}
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.
Types of Annotation
Example: - @TestAnnotation()
Example: - @TestAnnotation(“testing”);
3. Multivalue Annotations:
These annotations consist of multiple data members/ name, value, pairs.
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{ }
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.
@interface
MyAnnotation{ int
value1( ) default 1; String
value2( ) default "";
String value3( ) default "xyz";
}
@MyAnnotation(value1=10,value2="Umesh",value3="SJBIT")
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.
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.
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.
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
}
}
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:
@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
{
...
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.
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 {
// 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) {
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( )
@Retention(RetentionPolicy.RUNTIME)
@interface What {
String description();
}
@What(description = "An annotation test class")
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:");
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