Module 01
Module 01
1
MODULE-1
Enumerations, Autoboxing and Annotations(metadata): Enumerations, Enumeration fundamentals, the values()
and value Of() Methods, java enumerations are class types, enumerations Inherits Enum, example, type
wrappers, Autoboxing, Autoboxing and Methods, Autoboxing/Unboxing occurs in Expressions,
Autoboxing/Unboxing, Boolean and character values, Autoboxing/Unboxing helps prevent errors, A word of
Warning. Annotations, Annotation basics, specifying retention policy, Obtaining Annotations at run time by
use of reflection, Annotated element Interface, Using Default values, Marker Annotations, Single Member
annotations, Built-In annotations.
MODULE-2
The collections and Framework: Collections Overview, Recent Changes to Collections, The Collection
Interfaces, The Collection Classes, Accessing a collection Via an Iterator, Storing User Defined Classes in
Collections, The Random Access Interface, Working With Maps, Comparators, The Collection Algorithms,
Why Generic Collections?, The legacy Classes and Interfaces, Parting Thoughts on Collections.
MODULE-3
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( )
2
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-4
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 5
The Concept of JDBC; JDBC Driver Types; JDBC Packages; A Brief Overview of the JDBC process;
Database Connection; Associating the JDBC/ODBC Bridge with the Database; Statement Objects; ResultSet;
Transaction Processing; Metadata, Data types; Exceptions
Course objectives:
Explain the need for advanced Java concepts like Enumerations and Collections
Define the working of Strings in Java
Demonstrate the use of JDBC to access database through Java Programs
Adapt servlets to build server-side programs
Chapter 1
Enumerations,
Autoboxing and
Annotations(metadata)
Enumeration
Enumerations, or enums, in Java are a special data type that enables a
variable to be a set of predefined constants. They are commonly used when you
have a fixed set of related values, such as days of the week, months, directions, or
status codes. Enums make the code more readable and safer by replacing integer or
string constants with a type-safe mechanism.
• Enumerations included in JDK 5. An enumeration is a list of named constants. It
is similar to final variables.
• 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.
• Enum in java is a data type that contains fixed set of constants.
• They can be useful in setting a scope of values for a particular object.
6
• Each declared value is an instance of the enum class.
• Enums are implicitly public, static, and final.
• enums extend java.lang.Enum and implement java.lang.Comparable.
• Supports equals, “==”, compareTo, ordinal, etc.
• Enums override toString() and provide valueOf(…), name().
Creating Enumerations
• When creating an enumeration list, we don't use the keyword class and when you create list,
enumeration object, we don't use the keyword new.
• To create an enumeration list, we need to import java.util.Enumeration.
• An enumeration is created using the enum keyword followed by the variable Name we want
associated with the list.
Syntax:
public enum variableName {
ITEM1
ITEM2
ITEMN
} 8
example: public enum Gender {
MALE, FEMALE, UNKNOWN
}
Creating an enumeration object
To declare an enumeration object, use the variable name associated with the list
followed by the name of the object.
Syntax:
variableName object;
example: Gender gen;
Assigning values to the enumeration object
To assign values to the object, must use the enumeration name, a dot and one of
the values in the list.
Syntax:
object = variableName.ITEM;
example: Gender gen=Gender.MALE; 9
Assigning default values
We can also assign the default value to list of item in enumeration class. In
order to assign default value to list in enumeration class, should contain the
enumeration constructor, fields, methods.
example:
public enum Gender {
MALE(1), FEMALE(2), UNKNOWN(0)
}
Simple Program: {
enum Gender { Gender S;
MALE, FEMALE, UNKNOWN S=Gender.MALE;
} System.out.println("Gender IS="+S);
class Enu { }
public static void main( String args[] ) }
OUTPUT:
Gender IS=MALE 10
Java enum in CONTROL STATEMENTS:
Control statements are the statements which alter the flow of execution and
provide better control to the programmer on the flow of execution. In Java control
statements are categorized into selection control statements, iteration control
statements and jump control statements.
15
program 1: To check the gender of person
enum Gender {
switch(s)
MALE, FEMALE, UNKNOWN;
{
}
case MALE:System.out.print("Gender is male");
break;
class cont
case FEMALE:System.out.print("Gender is female");
{
break;
public static void main( String
case UNKNOWN:System.out.print("Gender is unknown");
args[] )
{
break;
Gender s=Gender.FEMALE;
default:System.out.print("NON of these");
}
} }
16
The values() and valueOf() Methods:
There are some methods that you can use that are part of the enumeration class, these
methods include :
1. values()
2. valueOf()
1.Values():
Method returns an array that contains a list of the enumeration constants
values() returns the values in the enumeration and stores them in an array. We can
process the array with a foreach loop.
17
Program 1: To print the list of day of enumeration class
enum Days {
mon, tue, wed, thu, fri, sat, sun;
}
class cont
{
public static void main( String args[] )
{
Days d[]=Days.values(); output:
for(Days d1:d) today day is=mon
System.out.println("today day is:"+d1); today day is=tue
} today day is=wed
} today day is=thu
today day is=fri
today day is=sat
Try this program 2:TO find no of days in month today day is=sun 18
2. ValueOf():
• Method returns the enumeration constant whose value corresponds to the string
passed in str.
• Method takes a single parameter of the constant name to retrieve and returns the
constant from the enumeration, if it exists.
19
Note: An enumeration cannot inherit another class and an enum cannot be a superclass for
other class. 20
Java Enumerations Are Class Types
• Enumerations in Java can have methods, members and constructors just as any
other class can have.
• Each enumeration constant is an object of its enumeration type.
• Thus, when you define a constructor for an enum, the constructor is called when
each enumeration constant is created.
• Also, each enumeration constant has its own copy of any instance variables
defined by the enumeration.
• The enum constants have initial value that starts from 0, 1, 2, 3 and so on. But we
can initialize the specific value(default value) to the enum constants by defining
fields and constructors.
21
Program:
enum Value {
A(10), B(20), C(30);
int a;
int getValue(){ return a;}
Gender(int value)
{
this.a=value;
} }
class Enu
{
public static void main( String args[] )
{
System.out.println(" value of A
IS="+Value.A.getValue());
}
}
output: Value of A Is= 10
22
Enumerations Inherit Enum:
1.Ordinal():
•Returns the value of the constant's position in the list (the first constant has a position
of zero).
•The ordinal value provides the order of the constant in the enumeration, starting with
0
Example
WeekDays wd = WeekDays.MONDAY;
System.out.println(wd.ordinal());
23
program: To find index of Enum List.
enum Days {
mon, tue, wed;
}
class cont
{
public static void main( String args[] )
{
Days wd = Days.mon;
System.out.println("Index of list:"+wd.ordinal());
}
}
output: Index of list:0
24
Program 2: Using foreach loop
enum Days {
mon, tue, wed;
}
class cont
{
public static void main( String args[] )
{
Days wd[] = Days.values();
for(Days w:wd)
System.out.println("Index of list:"+w.ordinal()); output:
} Index of list:0
} Index of list:1
Index of list:2
25
2. CompareTo():
• Compares the ordinal value of the two enumeration objects.
• If the object invoking the method has a value less than the object being passed,
a negative number is returned.
• It the two objects have the same oridnal number, a zero is returned.
• If the invoking object has a greater value than the one being passed, a positive
number is returned.
Example:
enum Days { d1=Days.mon;
mon, tue, wed; d2=Days.tue;
} d3=Days.wed;
class cont System.out.println(d1.equals(d2));
{ System.out.println(d2.equals(d3));
public static void main( String args[] ) System.out.println(d2.equals(d2));
{ } } Output:
false
Days d1,d2,d3; false
true 28
4. ToString():
• Method returns the name of this enum constant, as contained in the declaration.
public String toString()
• This method returns the name of this enum constant.
Example:
Days d1,d2,d3;
enum Days { d1=Days.mon;
mon, tue, wed; d2=Days.tue;
} d3=Days.wed;
class cont System.out.println(d1.toString());
{ System.out.println(d2. toString());
public static void main( String args[] ) System.out.println(d3. toString());
{ }
}
Output: mon tue wed
29
Type wrappers:
• Java uses primitive types (also called simple types), such as int or double, to
hold the basic data types supported by the language.
• Instead of primitive types if objects are used everywhere for even simple
calculations then performance overhead is the problem.
• To avoid this java had used primitive types. So, primitive types do not inherit Object class,
But there are times when you will need an object representation for primitives like int and
char.
• Many of the standard data structures implemented by Java operate on objects,
which mean that you can’t use these data structures to store primitive types.
• To handle these (and other) situations, Java provides type wrappers, which
are classes that encapsulate a primitive type within an object.
• Primitive types like integers or strings often have limited behavior in their raw form.
Wrappers add methods and properties that enable extended operations.
• Example: In Java, the Integer class wraps the primitive int type and adds methods like
parseInt, toString, and compare. 30
The type wrappers are :
Double, Float, Long, Integer, Short, Byte, Character, and Boolean.
Character:
• Character is a wrapper around a char.
• The constructor for Character is Character(char ch) here ch is a character
variable whose values will be wrapped to character object by the wrapper class
• To obtain the char value contained in a Character object, call charValue( ), shown
here:
char charValue( )
It returns the encapsulated character.
Boolean
•Boolean is a wrapper around boolean values. It defines these constructors:
Boolean(boolean boolValue)
Boolean(String boolString)
31
• 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.
• To obtain a boolean value from a Boolean object, use booleanValue( ), shown
here:
boolean booleanValue( )
• It returns the boolean equivalent of the invoking object.
33
Program : All wrapper class
public static void main(String args[]) {
• For example, conversion of Integer to int. The Java compiler applies unboxing
when an object of a wrapper class is:
35
• Passed as a parameter to a method that expects a value of the corresponding
primitive type.
• Assigned to a variable of the corresponding primitive type.
Uses of Autoboxing and Unboxing
• Useful in removing the difficulty of manually boxing and unboxing values in
several algorithms.
• it is very important to generics, which operates only on objects.
• It also helps prevent errors.
• autoboxing makes working with the Collections Framework
• here is the modern way to construct an Integer object that has the value 100:
Integer iOb = 100; // autobox an int
this for you, automatically.
• To unbox an object, simply assign that object reference to a primitive-type
variable.
• For example, to unbox iOb, you can use this line:
int i = iOb; // auto-unbox . 36
Program: Simple program for autoboxing and autoUnboxing
class auto
{
public static void main(String[] args)
{
Integer iob = 100; //Auto-boxing of int i.e converting primitive data type int to a Wrapper class
Integer
int i = iob; //Auto-unboxing of Integer i.e converting Wrapper class Integer to a primitve type int
Character cob = 'a'; //Auto-boxing of char i.e converting primitive data type char to a Wrapper
class Character
char ch = cob; //Auto-unboxing of Character i.e converting Wrapper class Character to a
primitive type char
40
// 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
41
Program:
class auto {
public static void main(String args[]) {
• 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. 42
A Word of Warning
In Java, "a word of warning" typically refers to a cautionary note or advice
about potential pitfalls, issues, or best practices when working with the language or a
specific feature. This phrase is often used in documentation, tutorials, or discussions
to highlight something developers should be aware of to avoid unexpectedly
consequences.
Because of autoboxing and auto-unboxing, some might be tempted to use objects
such as Integer or Double exclusively, abandoning primitives altogether.
Double a, b, c;
a = 10.0;
b = 4.0;
"A word of warning: Floating-point operations can introduce
c = Math.sqrt(a*a + b*b); precision errors; avoid using them for financial calculations."
Syntax ?
Syntax: An annotation starts with @, followed by the annotation name.
44
What’s the use of Annotations?
1) Instructions to the compiler: There are three built-in annotations available in
Java (@Deprecated, @Override & @SuppressWarnings) that can be used for
giving certain instructions to the compiler.
For example, the @override annotation is used for instructing
compiler that the annotated method is overriding the method.
2) Compile-time instructors: Annotations can provide compile-time instructions to
the compiler that can be further used by software build tools for generating code,
XML files etc.
3) Runtime instructions: We can define annotations to be available at runtime
which we can access using java reflection and can be used to give instructions to
the program at runtime.
45
Annotation basics
46
@Override
void myMethod() {
//Do something
}
• An annotation cannot include an extends clause. However, all annotation types
automatically extend the Annotation interface. Thus, Annotation is a super-
interface of all annotations. It is declared within the java.lang.annotation package.
47
Program: To display welcome message.
class annu
{
@mymethod public void show()
{
System.out.println("Well come to Annotation");
}
public static void main(String a[])
{
annu h = new annu();
h.show(); //deprecated
}
}
OutPUT:
Well come to Annotation
48
Specifying a Retention Policy
51
• After you have obtained a Class object, you can use its methods to obtain
information about the various items declared by the class, including its annotations
Class supplies (among others) the getMethod( ), getField( ), and getConstructor(
) methods, which obtain information about a method, field, and constructor,
respectively. These methods return objects of type Method, Field, and
Constructor.
• From a Class, Method, Field, or Constructor object, you can obtain a specific
annotation associated with that object by calling getAnnotation( ).
52
Program:
import java.lang.annotation.*;
import java.lang.reflect.*;
54
1. getDeclaredAnnotations( ) Method in Java
The getDeclaredAnnotations() method is part of the AnnotatedElement interface in
Java. This method is used to retrieve all the annotations explicitly declared on a particular
program element, such as a class, method, field, constructor, or other reflective objects.
Annotation[] getDeclaredAnnotations()
Returns: An array of Annotation objects representing all annotations explicitly declared on
the element. Returns an empty array if no annotations are declared.
Visibility: Only retrieves annotations that are directly declared on the program element.
Does not include inherited annotations (those inherited from superclasses or interfaces via
@Inherited).
55
import java.lang.annotation.*;
import java.lang.reflect.*;
class MyClass {
@MyAnnotation
public void myMethod() {}
}
57
import java.lang.annotation.*;
import java.lang.reflect.*;
class MyClass {
@MyAnnotation
public void myMethod() {}
}
public class SimpleIsAnnotationPresent {
public static void main(String[] args) throws Exception {
Method method = MyClass.class.getMethod("myMethod"); // Get the method
boolean isPresent = method.isAnnotationPresent(MyAnnotation.class); // Check for
annotation
System.out.println("Is MyAnnotation present? " + isPresent); // Print result
}
} Is MyAnnotation present? true 58
3. getDeclaredAnnotation( ):
Method returns this element's annotation for the specified type if such an
annotation is present, else null. This methods throws an exception
•NullPointerException − if the given annotation class is null
•IllegalMonitorStateException − if the current thread is not the owner of the
object's monitor. Syntax: public A getAnnotation(Class annotationClass)
4. getAnnotationsByType( ):
Returns annotations that are associated with this element. If there are no
annotations associated with this element, the return value is an array of
length 0.
59
5. getDeclaredAnnotationsByType( ):
Returns this element's annotation(s) for the specified type if such annotations
are either directly present or indirectly present. This method ignores inherited
annotations. If there are no specified annotations directly or indirectly present on this
element, the return value is an array of length 0.
60
Using Default Values:
62
import java.lang.annotation.*;
import java.lang.reflect.*;
// Define a marker annotation
@Retention(RetentionPolicy.RUNTIME)
@interface MyMarker {}
class MyClass {
@MyMarker
public void myMethod() {
System.out.println("myMethod() is running.");
}
}
public class MarkerAnnotationExample {
public static void main(String[] args) throws Exception {
Method method = MyClass.class.getMethod("myMethod");
String showSomething();
64
import java.lang.annotation.*;
// Define a single-member annotation
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String value(); // Single member (value)
}
class MyClass {
@MyAnnotation("Hello, Annotations!")
public void myMethod() {
System.out.println("myMethod() is running.");
}}
public class SingleMemberAnnotationExample {
public static void main(String[] args) throws Exception {
Method method = MyClass.class.getMethod("myMethod");
@Override
@Suppress Warnings
@Deprecated
67
class Parent {
void display() {
System.out.println("Parent class method");
}
}
68
@Suppress Warnings
@Suppress Warnings annotation: is used to suppress warnings issued by the compiler.
• Purpose: Instructs the compiler to suppress specific warnings that might be otherwise
generated.
• Usage:
• Used to ignore warnings, such as unchecked operations, deprecations, or unused
variables, which you are aware of and want to suppress.
• Commonly used with warnings like unchecked, deprecation, or serial.
69
import java.util.*;
class TestAnnotation2{
@SuppressWarnings("unchecked")
public static void main(String args[])
{
ArrayList list=new ArrayList();
list.add("sonoo");
}}
70
@Deprecated
@Deprecated annotation marks that this method is deprecated so compiler prints warning.
It informs user that it may be removed in the future versions. So, it is better not to use such
methods.
• Usage:
• Typically used to warn developers that a feature is outdated and might be removed
in future versions.
• The compiler generates a warning if the deprecated element is used.
71
class OldClass {
@Deprecated
void oldMethod() {
System.out.println("This method is deprecated");
}
}
Key Notes:
•Annotations like these improve code readability and maintainability by providing metadata
that informs developers and the compiler about specific behaviors or constraints.
•Overuse of @SuppressWarnings can hide genuine issues, so it should be used carefully.
72
Built-In Java Annotations used in other annotations
@Target
@Target tag is used to specify at which type, the annotation is used.
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. Let's see the
constants of ElementType enum:
Element Types Where the annotation can be applied
@Target(ElementType.TYPE)
@interface MyAnnotation{
int value1();
String value2();
}
2. Example to specify annotation for a class, methods or fields
RetentionPolicy.SOURCE refers to the source code, discarded during compilation. It will not be
available in the compiled class.
RetentionPolicy.CLASS refers to the .class file, available to java compiler but not to JVM . It is
included in the class file.
75
Example to specify the Retention Policy
76
@Inherited
By default, annotations are not inherited to subclasses. The @Inherited annotation marks the
annotation to be inherited to subclasses.
77
import java.lang.annotation.Inherited;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Inherited
@Target(ElementType.TYPE) // Can only be used on classes
@interface MyAnnotation {
}
@MyAnnotation
class Parent {
}
79
import java.lang.annotation.Documented;
Summary Table:
80
THE END
81