Java 7th Sem Ashokkumar
Java 7th Sem Ashokkumar
Java 7th Sem Ashokkumar
JAVA/ J2EE
Notes prepared by
Mr. Ashok Kumar K
9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Unit 1:
INTRODUCTION TO JAVA
1.1 Basics
In the Java programming language, all source code is first written in plain text files ending with the .java extension. Those source files
are then compiled into .class files by the java compiler (javac). A .class file does not contain code that is native to your processor; it
instead contains bytecodes the machine language of the Java Virtual Machine (JVM). The java launcher tool then runs your
application with an instance of the Java Virtual Machine.
Because the JVM is available on many different operating systems, the same .class files are capable of running on Microsoft Windows,
the Solaris Operating System (Solaris OS), Linux, or Mac OS. This is how java achieves Compile once, Run anywhere feature.
Fig: Through the JVM, the same application is capable of running on multiple platforms
Java as a Platform
A platform is the hardware or software environment in which a program runs. The Java platform is a software-only platform
that runs on top of other hardware-based platforms like Windows, Mac, etc.
The JVM is one of the components of Java platform which executes the bytecodes on any machine in which its been
installed. The bytecodes can be generated by compiling the java source code (.java file) using a java compiler.
Bytecodes will be contained within .class files.
The API is a large collection of ready-made software components that provide many useful capabilities. It is grouped
into libraries of related classes and interfaces; these libraries are known as packages. As a platform-independent
environment, the Java platform can be a bit slower than native code. However, advances in compiler and virtual
machine technologies are bringing performance close to that of native code without threatening portability.
Upon installing Java in any machine, you should be getting these two entities
Java Development Kit (JDK)
Java Runtime Environment (JRE)
JRE is an implementation of Java Virtual Machine which actually runs the program.
Typically, each JDK contains one (or more) JRE's along with the various development
tools like the Java source compilers, bundling and deployment tools, debuggers,
development libraries, etc.
You can download the latest distribution of Java at its official website http://www.java.com/en/download/manual.jsp
This site provides java distribution for Windows, Mac OS, Linux, and Solaris. Download and install latest version of
Java on whichever the platform you are comfortable with.
Installation procedure is pretty simple. Hopefully you don't encounter any blockage here. Give a try!
After installing Java in your machine, please set the JAVA_HOME, PATH and CLASSPATH environment variables.
The JAVA_HOME is the variable that your operating system uses to locate the installation path of java.
The PATH is the variable that your operating system uses to locate needed executables from the command
line or Terminal window.
The CLASSPATH variable is one way to tell applications, including the JDK tools, where to look for user
classes.
Simple
Java is a simple Language because it contains many features of other Languages like C and C++ and removes complexity because it
doesnt use pointers, storage classes and goto statements and it doesnt support multiple inheritances.
Object oriented
Java is purely an Object Oriented Programming language i.e., all the code of the Java language is written into the classes and objects.
Distributed
Java is designed as distributed language because, for creating applications on network it has the ability to share the data and programs
over the LAN (local area network). Java apps can open the remote objects on internet as easily they can do in local systems.
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Multithreaded
A Java program can be divided into multiple threads assigning different tasks for different threads and have all the threads executing in
parallel. Example for multithreaded application is a browser (multiple tabs can be opened; here each tab is a thread).
Dynamic
The Java Virtual Machine (JVM) maintains a lot of runtime information about the program and the objects in the program. Libraries are
dynamically linked during runtime. So, even if you make dynamic changes to pieces of code, the program is not affected.
Architecture neutral
This means that the programs written on one platform can run on any other platform without having to rewrite or recompile them. In
other words, it follows 'Write-once-run-anywhere' approach.
Java programs are compiled into bytecode format which does not depend on any machine architecture but can be easily translated into
a specific machine by a Java Virtual Machine (JVM) for that machine.
Portable
A C/C++ program may run slightly differently on different hardware platforms depending on how these platforms implement arithmetic
operations.
In Java, it has been simplified. Unlike C/C++, in Java the size of the primitive data types are machine independent. For example, an int
in Java is always a 32-bit integer, and float is always a 32-bit IEEE 754 floating point number. These consistencies make Java
programs portable among different platforms such as Windows, UNIX and Mac.
High performance
Java programs are compiled to portable intermediate form known as bytecodes, rather than to native machine level instructions and
JVM executes the bytecodes on any machine on which it is installed. This architecture means that Java programs are faster than
programs/scripts written in purely interpreted languages but slower than C and C++ programs that compiled to native machine
languages.
Robust
A Program or an application is said to be robust (reliable) when it is able to give some response in any kind of context. Javas features
help to make the programs robust. Some of those features are: type checking, exception handling, etc
Secured
Java provides data security through encapsulation. When we transfer the code from one machine to another, the JVM first check the
code to check if it is affected by virus/threats or not. If the code is affected then it will never execute that code in that machine. Also we
can write applets in Java which provides security. An applet is a small program which can be downloaded from a server using a
browser. There is no need to worry about applets accessing the system resources which may compromise security.
Object
An Object can be any real world entity we come across in our life. Example an Animal is an Object, also a Bank is an Object, a Human
is an Object etc. An object is a software bundle of related state and behavior.
Class
A class is a blueprint or prototype from which objects are created. It's just a template for an object. It describes an object. For Example,
a class just describes how a Dog looks like. (Say, a dog has 4 legs, it barks, it eats etc.), but an Object refers to a real Dog.
Inheritance
Generally, a process by which a child class acquires the state and behavior of its parent class is referred to as Inheritance. For
example, Hyundai is a parent class whose properties are inherited by the classes named iTen, iTwenty, Verna, Getz etc.
Polymorphism
The word "Polymorphism" refers to the ability to take more than one form. In terms of programming, the polymorphism refers to the
process in which a member function of a class behaves differently for different inputs. For example, a function move() in the game of
chess behaves differently for different pawns (for instance, it allows only sideways movement for camel and straight movement for
elephant).
Encapsulation
Encapsulation refers to the process of binding the data members and the functions (that accesses these data) together. A class is an
example for encapsulation. Through encapsulation a class can hide the internal details of how an object does something. Encapsulation
helps to change the internal implementation of the object without affecting the overall functionality of the system. Encapsulation
provides abstraction (Information hiding).
Interface
An interface is a description of the actions that an object can do. For example when you flip a light switch, the light goes on, you don't
care how, just that it does. In Object Oriented Programming, an Interface is a description of all functions that an object must have. For
example, anything that "ACTS LIKE" a light, should have a turn_on() method and a turn_off() method. So these two functions will be
included within an interface. The purpose of interfaces is to allow the computer to enforce these properties and to know that an object of
TYPE T must have functions called X,Y,Z, etc.
Package
A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being
similar to different folders on your computer. You arrange all audio songs under a specific directory, and all video songs under another
directory, etc. Because software written in the Java programming language can be composed of hundreds or thousands of individual
classes, it makes sense to keep things organized by placing related classes and interfaces into packages.
Assumptions:
Java has been installed and the environment variables are been properly set.
Steps
Step1: Open a text editor (notepad, edit plus, etc) and write the source code.
Step 2: Save this file as Hello.java in your local hard disk (where ever you wish)
Step 3: Open a command window and change the directory to the one where you just saved your Hello.java source file.
Step 4: Compile the source file using java compiler. i.e, by issuing a command as follows:
javac Hello.java
If there are any compilation errors in your program, this command will not successfully executes, instead it will throw an error saying
what went wrong. If your program is completely error free, the compilation process will be successful. You can observe that, the output
of the compilation process is a .class file which is called the java "byte code".
Step 5: Execute the .class file by giving it as an input to JVM through following command.
The program executes and the output can be seen in the console. Yes, you are done with your first Java program successfully.
Congrats :)
Observations
class Hello {
public static void main (String arg[]) {
System.out.println("Hello World. Welcome to the world of Java.");
}
}
In C++, the class was optional. i.e., you can write a C++ program with or without a class. But in java it's not like that. Nothing
can be written in Java without a class. So, you can observe the main function has been enclosed within a class.
Just like C/C++ which provides printf()/cout to print something on standard console, Java provides "println()" function to print
something in the console. This println() method is a member of a class named "PrintStream", whose object is created and
named as 'out' within a class called "System". Thus, println() function is referenced through a dot (.) notation
(System.out.println)
Please focus on the signature of the main function. This signature can't be changed.
The keyword 'public' says that, the main function can be accessed even outside the defining class. This is like
giving an access permission to JVM to execute the main function. If you mark it as private instead, it's like you are not
allowing even JVM to execute the main function and JVM throws an error if you try to run the program in that way.
The keyword 'static' has a special meaning. Generally a class member is accessed through its object. So if JVM
has to execute the main function, it has to get an object of the class enclosing the main function. But how will JVM get
this object? Somehow, JVM has to execute the main function without having its object. The keyword 'static'
comes as a solution for this. This keyword indicates that a function can be accessed without an object.
The keyword 'void' indicates that a function returns nothing. In Java, you can't return anything from the main
Comments in Java are of two types: Single line comments and Multiline comments.
Single line comment starts with // followed by the comment string.
Multi line comment starts with /* followed by the comment string and ends with */
There can be more than one class within a single .java file. The class that encloses the main function can be called as Main
Class.
A java source file should be having the same name as the class name which contains the main function. You can't choose the
name of your wish like in C/C++. This is to help the JVM to search for the main function.
In a single .java file where there are more than one classes, only one class can be marked as 'public' and this class should be
the main class. All the other classes should either be marked as private or default. It enables a more efficient lookup of source
(.java) and compiled (.class) files during compilation (import directives) and a more efficient class loading during execution.
class Three {
public static void main (String arg[]) {
class Four {
public static void main (String arg[]) {
int n=5;
for (int i=0;i<n;i++) {
for (int j=0;j<=i;j++) {
System.out.print("*\t");
}
System.out.println("\n");
}
class Five {
public static void main (String arg[]) {
int n=5;
for (int i=0;i<n;i++) {
for (int k=n;k>=i;k--)
System.out.print("\t");
for (int j=0;j<=i;j++)
System.out.print("*\t");
System.out.println("\n");
}
}
}
class Six {
public static void main (String arg[]) {
int n=5;
for (int i=0; i<n;i++) {
for (int j=0;j<n-i;j++)
System.out.print("\t");
for (int k=0;k<i;k++)
System.out.print("*\t");
for (int p=1;p<i;p++)
System.out.print("*\t");
System.out.println("\n");
}
for (int i=n; i>=0;i--) {
for (int j=0;j<n-i;j++)
System.out.print("\t");
for (int k=0;k<i;k++)
System.out.print("*\t");
for (int p=1;p<i;p++)
System.out.print("*\t");
System.out.println("\n");
}
}
}
Write a method named lastDigit that returns the last digit of an integer. For example, lastDigit(3572) should return 2. It
should work for negative numbers as well. For example, lastDigit(-947) should return 7.
class Seven {
public static void main (String arg[]) {
int n = -7676;
int ld = lastDigit(n);
System.out.println("Last Digit in "+n+" is .... "+ld);
n = 3489;
ld = lastDigit(n);
Write a method named firstDigit that returns the first digit of an integer. For example, firstDigit(3572) should return 3. It
should work for negative numbers as well. For example, firstDigit(-947) should return 9.
class Eight {
public static void main (String arg[]) {
int n = -7676;
int ld = firstDigit(n);
System.out.println("First Digit in "+n+" is .... "+ld);
n = 3489;
ld = firstDigit(n);
System.out.println("First Digit in "+n+" is .... "+ld);
}
Write a recursive function in java to print all natural numbers from 1 up to (n-1)
import java.util.Random;
public class Ten {
public static void main(String args[]) {
Random r = new Random();
int n = 100;
int ran = r.nextInt(n);
System.out.println("Random number in betwwen 0 and "+n+" is .... "+ran);
n = 200;
ran = r.nextInt(n);
System.out.println("Random number in betwwen 0 and "+n+" is .... "+ran);
Write a program to calculate the average among the elements {4,5,7,8}, using for each in java. How for each is different
from for loop?
int sum = 0;
for (int ele : arr) {
sum = sum + ele;
}
}
}
1.5.1 Variables
Variable is the name or the identifier given to the known memory location. It is used to store some program data/value which might be
referenced in future. To put it in the other way, the memory location will be accessed through the variable name.
A Data type is the classification identifying one of the various types of data, which determines the possible values for that type. There
are eight primitive data types and three reference data types in Java as described by the figure.
The Primitive data types are predefined data types, which always hold the value of the same data type, and the values of a
primitive data type don't share the state with other primitive values. These data types are named by a reserved keyword in Java
programming language.
byte: The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters
short: As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where
the memory savings actually matters.
int: For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose
something else. This data type will most likely be large enough for the numbers your program will use, but if you need a
wider range of values, use long instead
long: Use this data type when you need a range of values wider than those provided by int.
float: The float data type is a single-precision 32-bit IEEE 754 floating point. As with the recommendations for byte and
short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers.
double: The double data type is a double-precision 64-bit IEEE 754 floating point. For decimal values, this data type is
generally the default choice. As mentioned above, this data type should never be used for precise values, such as
currency.
char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum
value of '\uffff' (or 65,535 inclusive).
boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that
track true/false conditions.
In addition to the eight primitive data types listed above, the Java programming language also provides special support for
character strings via the java.lang.String class. Enclosing your character string within double quotes will automatically create
a new String object;
For example, String s = "Ashok Kumar";
String objects are immutable, which means that once created, their values cannot be changed. The String class is not
technically a primitive data type, but considering the special support given to it by the language; you'll probably tend to think of it
as such.
A Reference data type is a variable that can contain the reference or an address of dynamically created object. These types of
data type are not predefined like primitive data type.
The reference data types are arrays, classes and interfaces that are made and handled according to a programmer need.
Array: An array is a special kind of object that contains collection of similar type of elements. The java array enables
the user to store the values of the same type in contiguous memory allocations. The elements in an array are identified
by an integer index which initially starts from 0 and ends with one less than number of elements available in the array.
All elements of an array must contain the same type of value i.e. if an array is a type of integer then all the elements
must be of integer type. It is a reference data type because the class named as Array implicitly extends
java.lang.Object.
Class: The name of a class is treated as a type in a java program, so that you can declare a variable of an object-type,
and a method which can be called using that object- type variable. Whenever a variable is created, a reference to an
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
object is also created using the name of a class for its type i.e. that variable can contain either null or a reference to an
object of that class. It is not allowed to contain any other kind of values. Such type is called reference types in Java.
The object becomes an instance when the memory is allocated to that object using new keyword.
Ex:
class Box {
int h, w, l;
double getArea() {
}
void setValues (int h, int w, int l) {
}
}
Box b = new Box(); // here b is an object/instance, Box is a class type
Interface: The name of an interface can be used to specify the type of a reference. A value is not allowed to be
assigned to a variable declared using an interface type until the object implements the specified interface. Hold on
here, you will learn more about interfaces in later chapters.
It's not always necessary to assign a value when a variable (field) is declared. Fields that are declared but not initialized will be set to a
reasonable default by the compiler.
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
boolean false
1.5.4 Literals
The new keyword isn't used when initializing a variable of a primitive type. Primitive types are special data types built into
the language; they are not objects created from a class.
A literal is the source code representation of a fixed value; literals are represented directly in your code without requiring
computation.
Integer Literal: An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int. Please use the upper
case letter L because the lower case letter l is hard to distinguish from the digit 1.
Following example shows the syntax for creating the literals in binary and hexadecimal number system.
Floating-point Literal: A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double and it can
optionally end with the letter D or d. The floating point types (float and double) can also be expressed using
E or e (for scientific notation),
F or f (32-bit float literal), and
D or d (64-bit double literal; this is the default and by convention is omitted).
Examples:
double d1 = 123.4;
// same value as d1, but in scientific notation
double d2 = 1.234e2;
float f1 = 123.4f;
Character and String Literals: Literals of types char and String may contain any Unicode (UTF-16) characters. If your editor
and file system allow it, you can use such characters directly in your code. If not, you can use a "Unicode escape" such as
'\u0108' (capital C with circumflex), or "S\u00ED Se\u00F1or" (S Seor in Spanish). Always use 'single quotes' for char literals
and "double quotes" for String literals.
There is a special null literal that can be used as a value for any reference type. null may be assigned to any variable,
except variables of primitive types. null is often used in programs as a marker to indicate that some object is unavailable.
Finally, there is another literal called a class literal, formed by taking a type name and appending ".class"; for example, String
class. This refers to the object (of type Class) that represents the type itself.
Java supports a few special escape sequences for char and String literals:
\b (backspace),
\t (tab),
\n (line feed),
\f (form feed),
\r (carriage return),
\" (double quote),
We know that, a class is a template (blue print) for an object, and an object is an instance of the class.
// This is a constructor
Box(int w, int l, int h) {
this.w = w;
this.h = h;
this.l = l;
}
long getArea() {
return l*w*h;
}
}
Destroying Objects
Java provides a wonderful concept of Garbage Collection which performs automatic memory
management, so you don't need to delete the object that you've created. JVM does it for you
automatically through Garbage Collection. We will see the concept of Garbage Collection in deep at
later chapters.
One of the concepts in object-oriented programming is encapsulation. It concerns about the hiding of data in a class and making this
class available only through methods. In this way the chance of making accidental mistakes in changing values is minimized. Java
allows you to control access to classes, methods, and fields via so-called access specifiers.
public
public classes, methods, and fields can be accessed from everywhere. The only constraint is that a file with
Java source code can only contain one public class which should be a main class.
protected
protected methods and fields can only be accessed within the same class to which the methods and fields
belong, also within its subclasses but not from anywhere else. You use the protected access level when it is
appropriate for a class's subclasses to have access to the method or field, but not for unrelated classes.
private
private methods and fields can only be accessed within the same class to which the methods and fields
belong. private methods and fields are not visible within subclasses and are not inherited by subclasses. So,
the private access specifier is opposite to the public access specifier. It is mostly used for encapsulation
default
If you do not set access to specific level, then such a class, method, or field will be accessible from inside the
same package to which the class, method, or field belongs, but not from outside this package.
1.6.1 Operators
Operators are such symbols that perform some operations on one or more operands. Operators are used to manipulate primitive data
types. Once we declare and initialize the variables, we can use operators to perform certain tasks like assigning a value, adding the
numbers etc.
The list below is arranged in the order of their precedence (Highest to Lowest)
Postfix Operators
exp++, exp--
Unary Operators
++expr, --expr, +expr, -expr, ~, !
Multiplicative Operators
*, /, %
Additive Operators
+, -
Shift Operators
<<, >>, >>>
Relational Operators
<, >, <=, >=, instanceof
Equality Operators
==, !=
Bitwise Operators
Bitwise AND (&)
Bitwise EXCLUSIVE OR (^)
Bitwise OR (|)
Logical Operators
Logical AND (&&)
Logical OR (||)
Ternary Operators
?:
Assignment Operators
=, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, >>>=
Shift Operators
The signed left shift operator "<<" shifts a bit pattern to the left, and
The signed right shift operator ">>" shifts a bit pattern to the right.
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand.
The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on
sign extension.
Example:
int num2 = 5;
num2 = num2 >>> 2;
System.out.println(num2);
int num3 = 5;
num3 = num3 << 2;
System.out.println(num3);
Bitwise Operators
Example
int num2 = 5;
num2 = num2 & 2;
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
System.out.println(num2);
int num3 = 5;
num3 = ~num3;
System.out.println(num3);
Ternary Operator
The ternary operator (also known as the conditional operator) can be used as an alternative to the Java if/then/else syntax, but it goes
beyond that, and can even be used on the right hand side of Java statements.
Syntax
The condition gets evaluated first. If the condition evaluates to true, the truth block gets executed and returns, else the false block gets
executed and returns.
Example
int a = 10;
int b = 20;
Logical Operators
1.6.2 Expressions
An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of
the language, which evaluates to a single value. Some examples of expressions are illustrated in bold below:
int cadence = 0;
anArray[0] = 100;
System.out.println("Element 1 at index 0: " + anArray[0]);
The data type of the value returned by an expression depends on the elements used in the expression. The
expression cadence=0 returns an int because the assignment operator returns a value of the same data type as its left-hand operand;
in this case, cadence is an int. As you can see from the other expressions, an expression can return other types of values as well, such
as boolean or String.
The Java programming language allows you to construct compound expressions from various smaller expressions as long as the data
type required by one part of the expression matches the data type of the other. Here's an example of a compound expression:
1 * 2 * 3
In this particular example, the order in which the expression is evaluated is unimportant because the result of multiplication is
independent of order; the outcome is always the same, no matter in which order you apply the multiplications. However, this is not true
of all expressions. For example, the following expression gives different results, depending on whether you perform the addition or the
division operation first:
x + y / 100 // ambiguous
You can specify exactly how an expression will be evaluated using balanced parenthesis: ( and ). For example, to make the previous
expression unambiguous, you could write the following:
If you don't explicitly indicate the order for the operations to be performed, the order is determined by the precedence assigned to the
operators in use within the expression. Operators that have a higher precedence get evaluated first. For example, the division operator
has a higher precedence than does the addition operator. Therefore, the following two statements are equivalent:
x + y / 100
When writing compound expressions, be explicit and indicate with parentheses which operators should be evaluated first. This practice
makes code easier to read and to maintain.
Java Control statements control the order of execution in a java program, based on data values and conditional logic. There are three
main categories of control flow statements;
Selection statements
If
if-else
switch
Iteration statements
while
do-while
for
Jump statements
break
continue
return
The if statement
The if statement executes a block of code only if the specified expression is true. If the value is false, then the if block is
skipped and execution continues with the rest of the program. You can either have a single statement or a block of code
within an if statement. Note that the conditional expression must be a Boolean expression.
Syntax:
if (<conditional expression>) {
<statements>
}
Example:
The if-else statement is an extension of the if statement. If the statements in the if statement fails, the statements in the
else block are executed. You can either have a single statement or a block of code within if-else blocks. Note that the
conditional expression must be a Boolean expression.
Syntax:
if (<conditional expression>) {
<statements>
} else {
<statements>
}
Example:
The switch case statement is a multi-way branch with several choices. A switch is easier to implement than a series of
if/else statements.
The switch statement begins with a keyword, followed by an expression that equates to a no long integral value.
Following the controlling expression is a code block that contains zero or more labeled cases.
Each label must equate to an integer constant and each must be unique.
When the switch statement executes, it compares the value of the controlling expression to the values of each case
label.
The program will select the value of the case label that equals the value of the controlling expression and branch
down that path to the end of the code block.
If none of the case label values match, then none of the codes within the switch statement code block will be
executed. Java includes a default label to use in cases where there are no matches.
Syntax:
Example:
The while statement is a looping construct control statement that executes a block of code while a condition is true. You
can either have a single statement or a block of code within the while loop. The loop will never be executed if the testing
expression evaluates to false. The loop condition must be a boolean expression.
Syntax:
Example:
The do-while loop is similar to the while loop, except that the test is performed at the end of the loop instead of at the
beginning. This ensures that the loop will be executed at least once.
Syntax:
do {
<loop body>
} while (<loop condition>);
Example:
The for loop is a looping construct which can execute a set of instructions a specified number of times. Its a counter
controlled loop.
Syntax:
Example:
The break statement transfers control out of the enclosing loop (for, while, do or switch statement). You use a break
statement when you want to jump immediately to the statement following the enclosing control structure. You can also
provide a loop with a label, and then use the label in your break statement. The label name is optional, and is usually only
used when you wish to terminate the outermost loop in a series of nested loops.
Syntax:
Example:
A continue statement stops the iteration of a loop (while, do or for) and causes execution to resume at the top of the
nearest enclosing loop. You use a continue statement when you do not want to execute the remaining statements in the
loop, but you do not want to exit the loop itself.
You can also provide a loop with a label and then use the label in your continue statement. The label name is optional, and
is usually only used when you wish to return to the outermost loop in a series of nested loops.
Syntax:
Example:
The return statement exits from the current method, and control flow returns to where the method was invoked.
Syntax:
Example:
return (a + b);
}
}
JAVA/ J2EE
Notes prepared by
Mr. Ashok Kumar K
9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Unit 2:
2.1.1 Basics
Class
A class is a blueprint or prototype from which objects are created. It's just a template for an object and describes an objects behavior to
the JVM.
Object
An object is a real instance of a class. It can be any real world entity we come across in our life. Example an Animal is an Object, also a
Bank is an Object, a Human is an Object etc.
A class just describes how a Dog looks like. (Say, a dog has 4 legs, it barks, it eats etc.), but an Object refers
to a real Dog
Syntax
class <class_name> {
type1 var1;
type2 var2;
...
typeN varN;
type1 method1() {
}
type2 method2() {
}
....
typen methodN() {
}
}
An object of the class can be created using the following syntax
Example
Creating a class
class Student {
int regno;
String name;
double score;
Creating an object
Observations
For understanding purpose, lets break down the object creation statement into two steps:
Student stud;
Here stud is just like a normal local variable (allocated in stack memory) for the defining block. It
will be initially pointing to a null object (literally meaning NOTHING).
Here the object is instantiated with using a new keyword in java. A dynamic memory will be created in
the heap memory and the reference for this will be assigned to the local variable created in step 1.
The object will also be initialized by JVM. It does so by making a call to the object's constructor
(discussed later). You can pass arguments to the constructor within the parenthesis following the
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
class name on RHS of the above statement.
Variables within the class created without the keyword 'static' prefixed are called instance variables
or object variables or non-static variables. A separate memory space for these types of variables will
be created for each instance of a class.
Variables within the class created with the keyword 'static' prefixed are called class variables or static
variables. This type of variables actually shares the value among all the instances of a class. We will
see in detail with an example, a bit later.
A single .java file can contain any number of classes within it, but only one class can be made as
public and it should be the main class (main class is the one which contains the main function).
The name of the .java file should be the name of the main class.
// Class Definition.
// Instance variable
int regno;
String name;
double score;
// Methods
public void setStudentDetails(int a, String s, double d) {
regno = a;
name = s;
score = d;
}
// Main Class.
public class Example1 {
// Main function
public static void main(String[] args) {
// Object creation
Student s1 = new Student();
s1.setStudentDetails(24, "Arun", 45.89);
s1.printStudentDetails();
}
Output
2.1.2 Constructors
Definition:
A constructor is a special method that is used to initialize a newly created object and is called just after the memory is allocated for the
object. It can be used to initialize the objects to required values at the time of object creation. It is not mandatory for the coder to write a
constructor for the class.
If you don't write a constructor, Java provides a default constructor that initializes the object members to its default values.
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
boolean false
A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method
declarationsexcept that they use the name of the class and have no return type.
Example
class Student {
Student (int rno, String nm, double sc) {
regno = rno;
name = nm;
score = sc;
}
}
Observations
Parameterized Constructor
You can create more than one constructor for a class each having different signatures from one
another. Sounds something familiar? Right, it implies the constructors can be overloaded. Purpose of
having the constructor overloaded is to provide more than one ways of initializing an object. So, the
user of the object can initialize an object using any of the constructors provided. Remember, if you
don't provide any constructor, Java will provide a default zero argument constructors.
class Student {
int regno;
String name;
double score;
If the user of a class has all the three values (name, regno, and score) for a particular student,
he/she can use three argument constructor to create an object initializing it to these values, as
follows:
If the user of a class has only two values (name, and score) and the regno should be auto generated
by the class itself, then he/she can use two argument constructor to create an object, as follows:
If the user of a class doesn't have any idea about the initial values, he can simply go ahead and use
the default zero argument constructor to create an object, and he can assign the values at any time
later on.
"this" keyword
Java defines the 'this' keyword to be used within any method to refer to the current object. Within
an instance method or a constructor, this is a reference to the current object the object whose
method or constructor is being called. You can refer to any member of the current object from within
an instance method or a constructor by using 'this'.
There are many uses of 'this' keyword, but we are very young at this point of time to explore
everything. So let's see few uses of 'this' keyword which can be understood now:
'this' keyword can be used to call a constructor within another constructor of the same
class. If used, it must be the first statement in the constructor.
class Student {
int regno;
String name;
double score;
'this' keyword can be used to resolve the name space collision. Name space collision is
the situation where the member variables of a class and the local variables within a
constructor have same names.
class Student {
int regno;
String name;
double score;
'this' can be used to return an object, and 'this' can be used as a parameter for an object.
class Student {
....
public Student getStudent () {
return this;
}
}
Constructor Chaining
Like, 'this' keyword is actually a reference for the current object being used; the 'super' keyword
is actually a reference to the parent class of the current object being used. If a class does not extend
any parent class, then by default it's going to extend an Object class (present in java.lang
package). So you can think Object class as the default parent (base class) for all the classes in Java.
We are going to deal with 'super' keyword in later point of time. For now, you can think of 'super'
keyword as the way to make a call to base class constructor from its derived class.
The user of a class is invoking a class' constructor, and this class' is passing the constructor call to its
base class' constructor, and the base class' constructor in turn can pass the call to its base class'
constructor, and so on. This chain of constructor calls starting from an object continuing till Object
class' constructor can be referred as Constructor Chaining.
class Student {
Student() {
// pass the constructor call to its base class' constructor
super();
}
}
Remember, when you instantiate an object using 'new' keyword, the memory for this object will be allocated in JVM heap.
Garbage collection is a mechanism provided by JVM to reclaim heap space from objects which are eligible for Garbage collection.
Garbage collection relieves java programmer from memory management and gives more time to focus on business logic. Garbage
Collection in Java is carried by a daemon thread called Garbage Collector. You cannot force Garbage collection in Java; it will only
trigger if JVM thinks it needs a garbage collection based on Java heap size.
Observations
Java Heap is divided into three generation for sake of garbage collection. These are
Young generation (further divided into three parts: Eden space, Survivor 1, and Survivor 2 space)
Tenured or Old generation, and
Perm area.
New objects are created into young generation and subsequently moved to old generation. String pool is
created in Perm area of Heap, garbage collection can occur in perm space but depends upon JVM to JVM.
Minor garbage collection is used to move object from Eden space to Survivor 1 and Survivor 2 space and
Major collection is used to move object from young to tenured generation. Whenever Major garbage
collection occurs application threads stops during that period which will reduce applications performance
and throughput.
Every object in Java can have a finalize() method defined within it. Syntax to define a finalize() method is:
finalize() method is a special method in Java which is called just before the Garbage Collector reclaims this object. The intent is for
finalize() to release system resources such as open files, open sockets, open database connections etc, before getting collected.
The keyword protected is a specifier that prevents access to finalize() by code defined outside its class.
class Student {
}
// finalize method
protected void finalize() {
System.out.println("Inside finalize method .. ");
}
As you can see, the finalize() method is not called here. Remember, finalize() is not like a destructor in C++.
finalize() method will not be called simply because the object moves out of scope, instead it will be called only when JVM performs
a Garbage collection which is an undetermined process.
There is an alternative to invoke finalize() method, you can initiate a Garbage Collection manually by making a call to System.gc()
method. Replace the main function in above example with the one below:
Output:
It is possible to create a member of a class that can be used by itself, without reference to a specific instance. To create such a
member, precede its declaration with the keyword 'static'. When a member is declared static, it can be accessed before any
objects of its class are created, and without reference to any object.
Variables
Methods
Blocks
Static Variables
Static variables are also called class variables which actually shares the value among all the instances of a class. It is created by
prefixing the keyword 'static' while declaring a variable. It tells the compiler that there is exactly one copy of this variable in existence
regardless of how many times the class has been instantiated. Memory for static variables will be allocated in Code Segment of JVM
memory.
Example:
class Student {
int regno;
String name;
double score;
Student.principalName = Hemanth;
Student stud1 = new Student(7, "Ajay", 76.45);
Lets create another object 'stud2', and lets change the principals name.
You can now realize from the above figure, the static variable 'principalName' is actually shared among 'stud1' and 'stud2',
meaning, if you reassign a value to 'principalName' w.r.t 'stud2', this change also reflects in 'stud1' as well.
Static Methods
Conceptually, static methods are same as static variables, i.e., they are independent of any specific instance of an object. They are
bound at class level and not at object level.
Static methods can be invoked without creating an instance of its defining class. The most familiar example for static method is our
main function. We prefix the main function with static keyword thus allowing JVM to execute this method without instantiating main
class.
Example
class Student {
int regno;
String name;
double score;
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Static Blocks
Static blocks are also called Static initialization blocks. A static initialization block is a normal block of code enclosed in braces, { }, and
proceeded by the static keyword.
Syntax:
static {
// Logic
}
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The JVM guarantees that
static initialization blocks are called in the order that they appear in the source code. Remember, this code will be executed when JVM
loads the class. JVM combines all these blocks into one single static block and then executes. Restriction on static methods also
applies to static blocks.
Example:
class Student {
int regno;
String name;
double score;
static {
System.out.println("I am the static block in the Student class");
static {
System.out.println("I am the static block in the main class");
}
Output
Java allows you to define a class within another class. Such a class is called a nested class as shown below:
class OuterClass {
class NestedClass {
....
}
....
}
Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static
nested classes. Non-static nested classes are called inner classes.
class OuterClass {
static class StaticNestedClass {
....
}
class InnerClass {
....
}
....
}
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to
other members of the enclosing class, even if they are declared private. Static nested classes do not have
access to other members of the enclosing class.
It increases encapsulation
It constitutes to more readable and maintainable code
Example:
class OuterClass {
class InnerClass {
public void makeCall() {
sayHello(); // RIGHT
sayGoodMorning(); // RIGHT
}
}
static class StaticNestedClass {
public void makeCall() {
sayHello(); // RIGHT
sayGoodMorning(); // WORNG: static
nested class can't
access non static member
}
}
public static void sayHello() {
System.out.println("Hello World .. ");
}
2.2 INHERITANCE
Here, we are going to explore one of the most important characteristics of any object oriented programming language Inheritance.
2.2.1 Basics
Generally, a process by which a child class acquires the properties (state and behavior) of its parent class is referred to as Inheritance.
For example, Hyundai is a parent class whose properties are inherited by the classes named iTen, iTwenty, Verna, Getz etc.
Inheritance can also be referred to the concept of Generalization, which is the process of extracting common characteristics (states and
behavior) from two or more classes, and combining them into a generalized super class.
A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from
which the subclass is derived is called a superclass (also a base class or a parent class).
Excepting java.lang.Object, which has no superclass, every class in Java has one and only one direct superclass. In the absence of
any explicit superclass, every class is implicitly a subclass of java.lang.Object.
Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived
from the topmost class, java.lang.Object. Such a class is said to be descended from all the classes in the inheritance chain
stretching back to java.lang.Object. Below figure helps us to visualize the concept of Inheritance.
Syntax
Inheritance in Java can be done by using 'extends' keyword likewise in the following syntax.
Example
class Animal {
public void eat() {
System.out.println("EATING THRICE A DAY");
}
public void sleep() {
System.out.println("SLEEPING FOR 8 HOURS");
}
Idea behind inheritance is, when you have the same piece of code repeated in more than one class, you can avoid this duplication of
code by creating a general class that contains the duplicated code and having those classes extending this general class. Thus no
need to write the duplicated code in all the subclasses, you are writing it only once in the general class.
From the above example you can see that eat() and sleep() are the codes that are common to both Dog and a Cat. The duplication
of the code is avoided by defining a general class Animal and having the eat() and sleep() method within it. Cat and Dog just
extends the Animal class.
Observations
A subclass inherits all the public and protected members (fields, methods, and nested classes) from its superclass.
Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can
be invoked from the subclass.
A subclass does not inherit the private members of its parent class. However, if the superclass has public or
protected methods for accessing its private fields, these can also be used by the subclass.
Dog dog = new Animal(); // WRONG, because all Animals are not Dogs
}
}
Using super
super can be used here to make a call to superclass constructor from the derived class constructor.
Example:
super can also be used to refer to superclass member when there is a name collision between
superclass member and a derived class member.
Example:
class A {
int i;
}
Multilevel Inheritance
As discussed before, Java does allows a class to extend another class which further extends another class and so
on, eventually the top most class will be java.lang.Object. This type of inheritance is called as Multilevel
Inheritance (more than one level of inheritance).
Figure on the right gives an example for multilevel inheritance, where Object is
the topmost superclass and class D is at the leaf level.
class A {
A() {
System.out.println("A's Constructor");
}
}
class B extends A {
B() {
System.out.println("B's Constructor");
}
}
class C extends B {
C() {
System.out.println("C's Constructor");
}
}
class D extends C {
D() {
System.out.println("D's Constructor");
}
}
Output
No, Multiple inheritance is NOT allowed in Java. Multilevel inheritance is when a class inherits from more than one
superclass. For example,
We can think of two reasons why Java doesn't allows multiple inheritance
To avoid ambiguity error
Ambiguity error arises when Horse and Bird both defines a function
with the same name and Pegasus runs into a situation of dilemma upon
invoking that function w.r.t its object.
Multiple inheritance will be rarely used.
Java supports a limited form a multiple inheritance by allowing a class to inherit from one other class and an
unlimited number of interfaces. Meaning, a class can extend only one class but it can implement unlimited number
of interfaces.
Example:
Programming Example:
Suppose if you are a newly joined student in car driving school, assume you are allowed only to use the steering
wheel of the car on day 1 while only the trainer will be having access to brake and the accelerator.
The question here is how to implement the access restriction to the student on the car object?
Interface comes as a solution for this. Idea behind interface is, rather than using the object directly, use it through
an interface, so that you can only use that feature of an object which is defined in the interface.
Definition: An interface is a reference type, similar to a class that can contain only constants, method signatures,
and nested types. There are no method bodies. Interfaces cannot be instantiatedthey can only be implemented
by classes or extended by other interfaces
class Car {
void start() {
System.out.println("Starting Car .. ");
}
void killEngine() {
System.out.println("Engine Killled .. ");
}
}
interface Trainer {
void moveRight();
void moveLeft();
void accelerate();
void brake();
}
interface Student {
void moveLeft();
void moveRight();
}
The word "Polymorphism" refers to the ability to take more than one form. In terms of programming, the polymorphism refers to the
process in which a member function of a class behaves differently for different inputs
At this point of time, you can think of two different ways in which Java provides the Polymorphism feature.
Method Overloading
Concept:
Consider a Chess application, here we will have to implement the move() operation for all the pawns. Are we
going to select 9 different names for move() function of different pawns? How confusing it is.
To make it so simple and achieve polymorphism, we will define a different move() functions for different pawns
but the name of all these functions will be the same, move(). Only thing that differs is the argument list within
the parenthesis. We will pass 'Queen' object to call move() on queen, we will pass 'King' object to call
move() on king, and so on. This way the user of the object invokes only one function move(), and will observe
different results depending on type of input. This is what we call method overloading.
Definition:
When you have more than one method with the same name but different arguments, the methods are said to
be overloaded. The arguments list within the parenthesis should be differing either by type of parameters or
the number of parameters.
Please note, the return type of the functions will not come into picture here. Meaning, if two functions have
same function name and argument list but with different return types, you can't call them as overloaded
functions because return type alone can't decide it.
Example:
class A {
}
}
Output
More on Overloading:
Method overloading is called Static polymorphism because the call to the overloaded functions will be
resolved at compile time.
These are not overloaded functions, instead they lead to ambiguity errors
Method Overriding
Concept:
Consider our very first example on Inheritance, Dog and Cat extends Animal. Here we can see the Animal
class defines the common (general) characteristics of all its subclasses, for instance sleep() method which
makes the Animal to sleep for 8 hours. Assume a situation where all the animals in our application sleep for 8
hours but only the Dog sleeps for 4 hours. How will you implement this change in sleep() function which
should reflect only in Dog class alone? Overriding is a solution for this.
Overriding is nothing but simply redefining the sleep() function again the subclass (Dog class) so that the new
definition hides the previous definition for sleep() function in parent class (Animal class).
Definition:
An instance method in a subclass with the same signature (name, plus the number and the type of its
parameters) and return type as an instance method in the superclass overrides the superclass's method.
Note that an overriding method can also return a subtype of the type returned by the overridden method. This
is called a covariant return type.
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Example:
class Animal {
// Overridden method
public void sleep() {
System.out.println("SLEEPING FOR 8 HOURS");
}
}
// Overriding method
public void sleep() {
System.out.println("DOG SLEEPING FOR 4 HOURS");
}
}
}
Output
More on Overriding:
Method overriding is called Dynamic polymorphism because a call to overridden functions is resolved
at runtime.
Method overriding occurs only when the names and the type signatures of the two methods are
identical. If they are not, then the two methods are simply overloaded.
Concept:
Here we will focus on method overriding in bit detail. We know that a base class reference can be given to a
derived class object. The simple question I am going to answer in this topic is what if we call an overridden
method on this object?
Example:
class Animal {
// Overridden method
public void sleep() {
System.out.println("SLEEPING FOR 8 HOURS");
}
}
// Overriding method
public void sleep() {
System.out.println("DOG SLEEPING FOR 4 HOURS");
}
}
}
We can conclude from the above program, it is the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden method will be executed.
Therefore, if a superclass contains a method that is overridden by a subclass, then when different types of
objects are referred to through superclass reference variable, different versions of the method are executed.
Since this decision should be made base on the type of the object, the JVM can make this decision only at
runtime since the object will not be available at the compile time.
Definition:
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time,
rather than compile time.
Note:
If you want to invoke an overridden method (base class method) from the overriding method (derived class
method), you should use 'super' keyword as illustrated in below example.
Remember, its not mandatory that your class should override the base class method. It is completely dependent on your
implementation. Two questions for you at this point of time.
1. How will you enforce a restriction that a particular method in base class should never be overridden in the derived class?
2. How will you enforce a restriction that a particular method in base class should mandatorily be overridden in the derived
class?
Yes, Java provides a feature to enforce such restrictions. Following couple of topics deals with them.
You can use final keyword in java for three different uses.
'final' variables
A final variable can be only once assigned a value. This value cannot be changed latter. If final variable is used
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
in a class then it must assigned a value in a class constructor. Attempting to change the value of final
variable/field will generate error.
Syntax:
final <datatype> <var_name>;
Example
class Animal {
int age = 8;
final int legs = 4; // RIGHT: final variables can be assigned a value here
final int tails;
A () {
tails = 1; // RIGHT: final variable can be assigned a value in
constructor
}
void increment() {
age = age + 10;
legs = legs + 1; // ERROR: Can't modify the final variable
tails = tails + 1; // ERROR: Can't modify the final variable
}
}
If you want to enforce a restriction like, a particular method in the base class should never be overridden in the
derived class, simply prefix that method definition with the 'final' keyword.
A final method cannot be overridden by sub class.
Example:
class Animal {
// This is a final method
final public void eat() {
System.out.println("EATING THRICE A DAY");
}
public void sleep() {
System.out.println("SLEEPING FOR 8 HOURS");
}
}
// RIGHT
public void sleep() {
System.out.println("SLEEPING FOR 4 HOURS");
}
}
Unless a class definition has been prefixed with 'final', any other class can override it. There is no restriction
on that. Java provides a feature where you can restrict a class from being inherited. This can be done by
prefixing a class definition with 'final' keyword.
A class declared final cannot be sub classed. Other classes cannot extend final class. It provides some benefit to
security and thread safety.
Example
class Animal {
}
// RIGHT
final class Dog extends Animal {
}
// WRONG: Cannot subclass the final class Dog
class DomesticDog extends Dog {
Concept
There are situations in which you will want to define a superclass that declares the structure of a given abstraction without providing a
complete implementation of every method. That is, sometimes you will want to create a superclass that only defines a generalized form
that will be shared by all of its subclasses, leaving it to each subclass to fill in the details.
To put it differently, you may encounter some situations where you need to enforce a restriction that some functions in the base class
has to mandatorily overridden by the derived class. If you want to enforce this restriction on any method in base class, simply prefix its
declaration with 'abstract' keyword. Remember, you should not give the definition for abstract functions in the base class because
mandatorily it will be defined in derived classes.
If a class contains one or more abstract methods, it's like a class containing one or more methods without any definition (just the
declaration), so it's obvious that the class is not complete until any other class inherits it and gives the definition for these methods. The
conclusion is you cannot create a direct objects of the abstract class, all you can do is having its reference to the object of the derived
class.
Definitions
Abstract method
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon) like this:
abstract void fun(int a);
Abstract class
An abstract class is a class that is declared abstractit may or may not include abstract methods. Abstract classes cannot be
instantiated, but they can be subclassed. If a class includes abstract methods, the class itself must be declared abstract, as in:
class A {
abstract void fun(int a);
}
Example:
// abstract class
abstract class Animal {
void sleep() {
System.out.println("Sleeping for 8 hours");
}
2.3 EXCEPTIONS
2.3.1 Basics
Concept
There's always a tendency for erroneous situations to occur either within a program or beyond it. For example consider a program
which tries to divide a number 10 by an input number entered by the user. What if the number entered by the user is 0 (zero)? The
program attempts to divide 10 by 0 (zero) which causes the application to crash. Another example for erroneous situation is when you
try to create an object and there isn't enough space in the JVM heap to allocate the memory for it. These kind of erroneous situations
are called Exceptions. Java provides a wonderful exception handling mechanism to avoid an application crash.
Definition
Generally, Exceptions are such anomalous conditions which change the normal flow of execution of a program. Exceptions are used for
signaling erroneous (exceptional) conditions which occur during the run time processing.
In Java, Exception is an object that describes an exceptional condition that has occurred in a piece of code.
Let's see with the help of below example, what happens in Java if something goes wrong in the runtime.
When an exception occurs within a method, the method creates (throws) an object to describe the exception. This object is called as
Exception Object, which contains the complete information about what went wrong here, ex: type of exception, state of program, line
number in the source where this exception occurred and so on.
After a method throws an object, it will be caught by the block of code written to handle it. If you have not handled an exception in your
program, the exception object will be caught by the runtime system and it handles it in its own way. i.e., default exception handling will
come into picture which only does two things
You can realize this in the following output to the program shown above
You can see a short description of what went wrong and then the program has been terminated. The S.O.P statement written after the
division has not been executed.
The description of the error printed in the console is called the stack trace of the exception which prints the method call hierarchy. You
can see the method call stack for the modified version of above program.
You should clearly observe the type of object that's been created is ArithmeticException. It is one of the inbuilt classes in Java used to
represent an exception caused during arithmetic operations. There are various other types of classes in Java to represent different
scenarios where an exception occurs.
Output
Exception classes
There may be various scenarios where an exception might occur. Arithmetic exception which we saw in previous topic is one among
them. For exception in Java, there is a built in class used to represent the scenario. Hence, whenever an exception occurs, JVM will
throw an object of the corresponding class which well describes the exception scenario. Below figure shows the exception class
hierarchy. You can see, Throwable is the root of all the exceptions.
Throwable, declared in java.lang, is the root of entire exception family. It has two children, Exception and Error classes.
Exception class: Object of its subclasses are created and thrown whenever unusual condition occur which can be caught
and handled it programmatically. It can be either checked exceptions or unchecked exceptions. Example:
ArithmeticException
Error class: Error class will be created and thrown when a serious problem occurs beyond the application scope which can't
be controlled within an application. Example: OutOfMemoryError will be thrown when JVM is running short of memory.
Checked Exception classes directly inherit the Exception class while Unchecked Exception inherits from a subclass of Exception
called RuntimeException.
Below table shows the complete list of all Checked Exception classes in Java
Below table shows the complete list of all Unchecked Exception classes in Java
Java provides five keywords for exception handling. They are dealt in detail in later topics. Here we will see them in brief.
try
Program statements that you need to monitor for exception will be placed inside try block. If any exception occurs within a
try block, the corresponding exception class is created and thrown.
catch
A try block should be mandatorily followed by a catch block which will be executed if the exception object is thrown from
the try block. Technically, we say that catch block catches the exception thrown by a try block.
throw
A programmer can use throw keyword to manually throw an exception.
throws
finally
If you want some piece of code to be executed without depending on whether a exception occurs or not, you can place
such piece of code inside a finally block.
Concept
Use try block to enclose the piece of code which you need to monitor for exceptions. Exceptions thrown from the try block will be caught
by the corresponding catch block. A catch block is mandatory for every try block. Remember, a single try block can have more than one
catch block.
Syntax
try {
// Piece of code which you are monitoring for exception
} catch (Exception_Class ex) {
// This block will be executed if an exception occurs in above try block
}
Example
You can observe the above examples. In the first example there is no exception being thrown from the try block, hence the catch block
will simple be skipped. In the second example there is an ArithmeticException thrown from the try block which is caught by the catch
block which is capable of catching ArtithmeticException.
Observations
Exception description can be printed in the catch block using e.getMessage() as follows.
catch (ArithmeticException e) {
System.out.println("Exception occured");
System.out.println(e.getMessage());
}
Output
catch (ArithmeticException e) {
System.out.println("Exception occured");
e.printStackTrace();
}
Output
If you are not sure about what kind of exception is thrown from a try block, you are still able to catch it using a generic
catch clause as follows, which catches any type of exception thrown.
try {
int a = 10;
int b = 0;
int res = a/b;
} catch (Exception e) {
System.out.println("Exception occured");
e.printStackTrace();
}
Output
As mentioned earlier, in the scenario where more than one type of exception will be thrown from a single try block, you
can have more than one catch blocks, one corresponding to each type of exception object thrown.
Example, below try block is capable of throwing ArithmeticException and ArrayIndexOutOfBoundsException.
Hence I have written two catch blocks one for each of these exception.
try {
int arr[] = {2,4,5,6};
arr[10] = 90;
int a = 10;
int b = 0;
int res = a/b;
System.out.println("No Exception");
} catch (ArithmeticException e) {
System.out.println("Exception occured");
e.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception occured");
e.printStackTrace();
}
Output
When you use multiple catch statements, it is important to remember that exception subclasses must come before any
of their super classes. This is because a catch statement that uses a superclass will catch exceptions of that type plus
any of its subclasses. Thus, a subclass would never be reached if it came after its superclass. This is called unreachable
code error in Java.
Example
try {
int arr[] = {2,4,5,6};
arr[10] = 90;
int a = 10;
int b = 0;
int res = a/b;
try {
int arr[] = {2,4,5,6};
arr[10] = 90;
int a = 10;
int b = 0;
int res = a/b;
System.out.println("No Exception");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception occured");
e.printStackTrace();
} catch (Exception e) {
System.out.println("Exception occured");
e.printStackTrace();
}
You can write a try block within another try block. This kind of try blocks is called Nested try blocks. Each time a try
statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a
catch handler for a particular exception, the stack is unwound and the next outer try statements catch handlers are
inspected for a match. This continues until one of the catch statements succeeds, or until the entire nested try
statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception.
Example
try {
int arr[] = { 2, 4, 5, 6 };
arr[2] = 90;
try {
int a = 10;
int b = 20;
int res = a / b;
String s = null;
System.out.println(s.length());
} catch (ArithmeticException e) {
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception occured");
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println("Exception occured");
e.printStackTrace();
}
throw keyword
Concept
Regardless of who throws an exception (JVM or a programmer) it's always thrown with the throw statement. So far you have
only been catching an exception thrown by Java runtime system. It's also possible for you to throw an exception manually
using throw statement.
Example
try {
ArithmeticException e = new ArithmeticException("This is thrown
by me");
throw e;
} catch (Exception e) {
e.printStackTrace();
}
Output
Observations
Not all the objects can be thrown. Remember, only those objects which are subclasses of Throwable
can be thrown.
Example
public class Example {
public static void main(String[] args) {
try {
Example ex = new Example();
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
throw ex; // ERROR: can't throw this object.
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
output
throws keyword
Concept
Exception thrown by a method can be handled either within the same method or in the caller of that method. We generally
prefer the later one since caller of the method will be given full freedom to handle the exception in its own way. In this case,
the method which throws an exception should indicate to the compiler that the exception handling is not done within it but it's
done in the caller of that method, else it will give a compilation error.
Example
Observations
Since compiler is aware of only checked exceptions, it will give a compilation error only for
unhandled checked exceptions. Therefore, only checked exceptions should be specified in the
throws clause mandatorily. However, there is no restriction like you should not specify unchecked
exceptions in the throws clause
finally keyword
Concept
The finally block always executes when the try block exits. This ensures that the finally block is executed regardless of
exception occurs or not. Putting cleanup code in a finally block is always a good practice, even when no exceptions are
anticipated. Cleanup code meaning, releasing the external resources (like SQL connection, hard disk files etc).
Example
Concept
Java provides a wonderful feature where you can create your own exception class. This is definitely required in your application where
you wish to handle certain abnormal situation in your own way.
Example, in a banking application, when a person tries to withdraw the amount even though he have lesser than the minimum balance.
Java doesn't have any built in exception class that describes this scenario. You need to define one.
Syntax:
All you want to do is create a new class to represent the custom exception and extend it either directly the Throwable class or the
Exception class or the RuntimeException class
Example:
class Account {
long accnum;
static final double minBalance = 5000;
double balance = 0;
double getBalance() {
return balance;
}
}
}
Output
You can observe the above program. class LowBalanceException extends Exception class thus it is a custom exception defined by
us and it has overridden toString() method in Throwable class to print the appropriate exception message.
Concept
It is possible to associate one exception with another exception, thus recording the exact cause for an exception. That is, one exception
causing another exception is called Exception Chaining.
These are the methods and constructors added in Throwable class to support exception chaining:
Example
class Account {
long accnum;
static final double minBalance = 5000;
double balance = 0;
double getBalance() {
return balance;
}
} catch (EMIPaymentFailedException e) {
LowBalanceException e2 = new LowBalanceException();
e.initCause(e2);
throw e;
}
}
}
}
Output
The above example is a slight modification of the previous example. I have created another custom exception and added a new method
within Account class.
You can see from the output, EMIPaymentFailedException is associated with LowBalanceException. That is, these two exceptions
are in chain.
2.3 APPLETS
2.3.1 Basics
Applet is a Java program that can be embedded into HTML pages. Java applets run on the Java enables web browsers such as Mozilla
and Internet explorer.
Applet is designed to run remotely on the client browser, so there are some restrictions on it. Applet can't access system resources on
the local computer. Applets are used to make the web site more dynamic and entertaining.
The class Applet provides the foundation for creating applets in Java. The class Applet is contained in java.applet package
1. The first are those based directly on the Applet class. These applets use the Abstract Window Toolkit (AWT) to provide the
graphic user interface.
2. The second types are those based on the Swing class JApplet.
Because JApplet inherits Applet, all the features of Applet are also available in JApplet.
Observations
Applets are not stand-alone programs. Instead, they run within either a web browser or an applet viewer.
Execution of an applet does not begin at main( ). Instead, execution of an applet is started and controlled with
an entirely different mechanism,
To use an applet, it is specified in an HTML file. One way to do this is by using the <APPLET> tag.
The applet will be executed by a Java-enabled web browser when it encounters the <APPLET> tag within the
HTML file.
The list of all methods contained within Applet class is given below along with the description.
void destroy()
Called by the browser or applet viewer to inform this applet that it is being reclaimed and that it should
destroy any resources that it has allocated.
AccessibleContext getAccessibleContext()
AppletContext getAppletContext()
Determines this applet's context, which allows the applet to query and affect the environment in which it
runs.
String getAppletInfo()
Returns the AudioClip object specified by the URL and name arguments.
URL getCodeBase()
URL getDocumentBase()
Locale getLocale()
String[][] getParameterInfo()
Returns information about the parameters that are understood by this applet.
void init()
Called by the browser or applet viewer to inform this applet that it has been loaded into the system.
Boolean isActive()
Boolean isValidateRoot()
Plays the audio clip given the URL and a specifier that is relative to it.
void resize(Dimension d)
void start()
Called by the browser or applet viewer to inform this applet that it should start its execution.
void stop()
Called by the browser or applet viewer to inform this applet that it should stop its execution.
Applets are event driven. An Applet waits until an event occurs. The AWT notifies the applet about an event by calling event handler
that has been provided by the applet. The applet takes appropriate action and then quickly return control to AWT. All swing components
descend from the AWT container class. User initiates interaction with the applet (and not the other way around)
An Applet skeleton
import java.awt.*;
import java.applet.*;
/*
<applet code="AppletSkel" width=300 height=100>
1. init ()
2. start()
3. paint()
1. stop()
2. destroy()
init()
The init() method is the first method to be called. This is where you should initialize variables. This method is called only
once during the run time of your applet.
start()
The start( ) method is called after init(). It is also called to restart an applet after it has been stopped. Whereas init() is
called once - the first time an applet is loaded, start( ) is called each time an applets HTML document is displayed onscreen.
So, if a user leaves a web page and comes back, the applet resumes execution at start().
paint()
The paint() method is called each time your applets output must be redrawn.The paint() method has one parameter of type
Graphics. This parameter will contain the graphics context, which describes the graphics environment in which the applet is
running.
stop()
The stop() method is called when a web browser leaves the HTML document containing the applet - when it goes to another
page.
destroy()
The destroy() method is called when the environment determines that your applet needs to be removed completely from
memory. At this point, you should free up any resources the applet may be using. The stop() method is always called before
destroy().
2.3.3 A simple applet that sets the foreground and background colors and outputs a string.
To output a string to an applet, use drawString( ), which is a member of the Graphics class. Typically, it is called from within either
update( ) or paint( ).
import java.awt.*;
import java.applet.*;
/*
<applet code="Sample" width=300 height=50>
</applet>
*/
public class One extends Applet {
String msg;
Output:
The repaint() method is defined by the AWT. It causes the AWT run-time system to execute a call to your applets update() method,
which, in its default implementation, calls paint().
1. void repaint()
2. void repaint(int left, int top, int width, int height)
3. void repaint(long maxDelay)
4. void repaint(long maxDelay, int x, int y, int width, int height)
Here,
import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleBanner" width=300 height=50>
</applet>
*/
// Start thread
public void start() {
t = new Thread(this);
stopFlag = false;
t.start();
}
showStatus() function can be used to print the message in the status bar of an applet
Example:
import java.awt.*;
import java.applet.*;
/*
<applet code="StatusWindow" width=300 height=50>
</applet>
*/
public class StatusWindow extends Applet {
public void init() {
setBackground(Color.blue);
setForeground(Color.white);
}
Output:
Oracle currently recommends that the APPLET tag be used to start an applet from both an HTML document and from an applet viewer.
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
[HTML Displayed in the absence of Java]
</APPLET>
CODEBASE is an optional attribute that specifies the base URL of the applet code, which is the directory that will be searched
for the applets executable class file
CODE is a required attribute that gives the name of the file containing your applets compiled .class file.
ALT tag is an optional attribute used to specify a short text message that should be displayed if the browser recognizes the
APPLET tag but cant currently run Java applets.
NAME is an optional attribute used to specify a name for the applet instance.
WIDTH and HEIGHT are required attributes that give the size (in pixels) of the applet display area.
The <APPLET> tag in HTML allows you to pass parameters to your applet. To retrieve a parameter, use the getParameter() method. It
returns the value of the specified parameter in the form of a String object.
Example:
import java.awt.*;
import java.applet.*;
/*
<applet code="ParamDemo" width=300 height=80>
<param name=fontName value=Courier>
<param name=fontSize value=14>
<param name=leading value=2>
<param name=accountEnabled value=true>
</applet>
*/
public class ParamDemo extends Applet {
String fontName;
int fontSize;
float leading;
boolean active;
getDocumentBase() returns the URL of the directory holding the HTML file that started the applet.
getCodeBase() returns the URL of the directory from which the applets class file was loaded.
Example:
import java.awt.*;
import java.applet.*;
import java.net.*;
/*
<applet code="Bases" width=300 height=50>
</applet>
*/
public class Bases extends Applet {
public void paint(Graphics g) {
String msg;
URL url = getCodeBase(); // get code base
msg = "Code base: " + url.toString();
g.drawString(msg, 10, 20);
url = getDocumentBase(); // get document base
msg = "Document base: " + url.toString();
g.drawString(msg, 10, 40);
}
}
Output:
Below example is a Java applet which continuously plays an audio clip named anthem.wav loaded from applets parent directory.
import java.applet.Applet;
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
import java.applet.AudioClip;
import java.awt.Graphics;
AudioClip audioClip;
<html>
<head>
<title>Applet sound example</title>
</head>
<body>
</body>
</html>
JAVA/ J2EE
Notes prepared by
Mr. Ashok Kumar K
9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Unit 3:
Multithreaded Programming,
Event Handling
MULTITHREADED PROGRAMMING
Concurrency is the ability to run multiple parts of the program in parallel. If a program can be divided into multiple independent parts,
each performing a specific task, then executing these parts in parallel in an asynchronous way increases the throughput of the program.
This type of programming is generally referred to as Concurrent Programming.
Process Thread
Definition: Definition:
Process is an instance of an entire program Thread is an execution path or the control
in execution. flow of execution of a program.
A process has a separate execution Threads exist within a process; every process
environment. It has a complete, private set of has at least one thread. Threads share the
basic run-time resources; each process has process's resources, including memory and
its own memory space open files. Threads are called light-weight
process
Remember:
Threads have their own call stack and can access shared data. These cause two problems
Visibility problem occurs if thread A reads shared data and thread B later changes this data and the thread A is unaware of this
change.
Access problem can occur if several threads tries to access and share the same shared data at the same time.
A separate process will be created for each Java program within which one default thread (called the Main thread) starts executing the
main function. This default thread or the main thread will be created by JVM. You can also create child threads using this.
It is the thread using which other threads (child threads) can be created
Ideally it must be the last thread to finish execution because it performs various shutdown operations.
Below example does some exercise with the main thread. It first gets the access (reference) to main thread using currentThread()
method in Thread class. It prints the name of the thread whose reference we have just got. It changes the name and priority of the
thread using setName() and setPriority() methods respectively. It prints the numbers 0 through 4 with a delay of 1sec after each
number. The thread is made to sleep for 1 sec after printing one number. A thread can be sent to sleep using Thread.sleep(long)
method where the parameter is the amount of time in milliseconds.
Output
When you simply print a thread reference t, you know that it will invoke t.getString() method which printed something like this:
Thread[main, 5, main]. Here is what actually they are:
Step 1:
Simply define your own class and implement it by java.lang.Runnable interface. Define run() method and include the
business logic of the thread within the run() method, because run() is the entry point for a thread and when it returns
from this function, the thread dies. To put it differently, a thread will be active till it lies in the context of run() method.
Instance of this class is called Runnable object since it implements Runnable interface.
Step 2:
Creating a child thread is nothing but creating an instance of Thread class and passing the runnable object as a
parameter for its constructor. Remember, at this point of time you have only created a child thread, but you haven't
started its execution yet. To do so, you should invoke start() method of the thread object you just created. It causes the
child thread to start its execution. The JVM calls run() method of the child thread. The result is that two threads are
running concurrently: the current thread (which returns from the call to the start method) and the other thread (which
executes its run() method).
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed
execution.
try {
for (int i = 0; i < 5; i++) {
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Thread.sleep(1000);
System.out.println("Main .. " + i);
}
System.out.println("Main thread exiting .. ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Output:
The order of execution of two threads is not the same always. The output you are seeing above can't be predicted.
Since the main thread and the child thread both are executing in parallel you can't expect the same ordering all the time.
It just gets mixed up.
Observation:
As a component developer you should focus on both the business logic and the required resources to create a thread.
An application developer will simply makes use of this. What I meant to tell is you should allow full freedom to the user of
this thread. You should encapsulate the process of creating a thread within the custom Thread class itself, as shown
below;
MyThread() {
t = new Thread(this);
t.start();
}
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("Main .. " + i);
}
System.out.println("Main thread exiting .. ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Step 1:
Simply extend your own class with java.lang.Thread. Define run() method and include the business logic of the
thread within the run() method, because run() is the entry point for a thread and when it returns from this function, the
thread dies.
Step 2:
Creating a thread is just creating an instance of the class defined in step 1. To begin the execution of the child thread,
you should invoke the run() method of the object created.
try {
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("Main .. " + i);
}
System.out.println("Main thread exiting .. ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Observation:
As discusses previously, the logic of creating a thread should be encapsulated within the Thread class by the
component developer. Here is the optimized version of the above program.
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("Main .. " + i);
}
System.out.println("Main thread exiting .. ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Creating a thread by implementing Runnable interface is preferred over extending the Thread class for two reasons.
Inheritance should be done only if you are modifying or enhancing the base class behavior. Since our class doesn't modify or
enhance the Thread class behavior, extending the Thread class is not recommended.
If you extend the Thread class, you now don't have freedom of extending other classes (since multiple inheritances are not
allowed). So we prefer implementing the Runnable interface and extending any other class.
You can create as many threads as you want. Below example creates four threads and starts them so that the four child threads along
with the main thread prints the numbers 0 to 4 concurrently. One more thing you need to observe from below program is the method of
assigning a name to the child thread. Yes, you can set the name of a child thread by passing the name as a String argument to the
Thread class constructor.
MyThread(String name) {
t = new Thread(this, name); // 'name' is the child thread's name
t.start();
}
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("Main .. " + i);
}
System.out.println("Main thread exiting .. ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Output
You can clearly see the order in which these threads execute can't be predicted. It depends on many things including the thread
priority.
There are three possible methods to make the main thread wait till all its child threads get terminated.
Method 1:
Make the main thread to sleep for some specified amount of time just before its termination, so that all its child threads can
MyThread(String name) {
t = new Thread(this, name);
t.start();
}
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("Main .. " + i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
Output:
Drawback:
How will you choose the amount of time that the main thread should sleep to ensure the termination of all its child threads?
You would end up choosing some large amount of time therefore making the main thread sleep for some extra time
even though all its child threads are already terminated.
You would end up choosing lesser time giving no time for some of its child threads to terminate.
Method 2:
Main thread can invoke isAlive() method on each of its child threads to see if it is still running or already terminated. This
way, the main thread will be in a continuous loop until all the child threads gets terminated. isAlive() is a method defined in
Thread class and have the signature as follows:
It returns true if the thread upon which it is called is still running. It returns false otherwise.
Example
MyThread(String name) {
t = new Thread(this, name);
t.start();
}
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("Main .. " + i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
// Main Thread will come out of this loop only after all the threads
terminates
while (true) {
if (m1.t.isAlive() || m2.t.isAlive() || m3.t.isAlive() ||
m4.t.isAlive()) {
// loop again
}
else
break; // come out of the loop
}
System.out.println("Main thread exiting .. ");
}
Output
Drawback:
This method has unspecified amount of continuous looping to check the status of the child threads thus wasting the runtime
resources.
Method 3:
join() is the method we mostly use to wait for a thread to finish its execution. join() method is also defined in Thread class
with the signature as follows:
This method waits until the thread on which it is called terminates. Additional forms of join( ) allow you to specify a
maximum amount of time that you want to wait for the specified thread to terminate.
Example
MyThread(String name) {
t = new Thread(this, name);
t.start();
}
try {
for (int i = 0; i < 5; i++) {
Thread.sleep(1000);
System.out.println("Main .. " + i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
m1.t.join();
m2.t.join();
m3.t.join();
m4.t.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main thread exiting .. ");
}
Output:
Each thread in Java will have an associated priority which is an integer value ranging from 1 (minimum) to 10 (maximum). Thread
scheduler will use the thread priorities to determine the execution schedule of threads. Higher priority threads get the CPU much faster
than the lower priority threads. If two threads have the same priority, the thread scheduler treats them equally and serves them based
on First Come First Serve (FCFS) basis.
Thread class defines two methods, one for setting the thread priority and the other for returning the current priority of a thread. Their
signatures are as follows:
void setPriority(int); sets the priority of a calling thread to the one passed as an argument.
int getPriority(); returns the current priority of the calling thread
Priority range
Example:
try {
Thread.sleep(10000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Low priority thread's execution count ..
"+m1.count);
System.out.println("High priority thread's execution count ..
"+m2.count);
}
}
Output:
As you can see, for the duration of 10 seconds the high priority thread has been given more CPU cycles compared to the low priority
thread.
Definition
Whenever two or more threads accesses the shared resources we need some mechanism to make sure that only one thread is given
access to the shared resource at any point of time. The process by which this is achieved is called synchronization.
Visibility problem: It occurs if thread A reads shared data and thread B later changes this data and the thread A is unaware of
this change.
Access problem: It occurs if several threads tries to access and share the same shared data at the same time.
The block of code or in general any resources, which is shared among more than two threads and which needs to be synchronized, is
called a monitor (also known as semaphore). Only one thread can access the monitor at any point of time. When a thread enters the
monitor, we say that the thread has acquired the lock, and it prevents any other threads entering into the same monitor until it releases
the lock by exiting the monitor.
Problem demonstration
Below program has a class named Utility which defines a method called printMessage(String). It takes a string argument and prints it
within the flower braces { and }. When two threads accesses this method at the same time each one passing a different string
argument, the order in which these messages are printed are not jumbled (mixed up).
class Utility {
// this is the shared resource
public void printMessage(String msg) {
System.out.print("{");
System.out.print(msg);
System.out.println("}");
}
}
}
}
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Output
Synchronized methods
This solution is simple. Just prefix the keyword 'synchronized' to the shared resource which needs to be
synchronized. The resource can be a method, variable or any other program elements. Here the shared resource is
the printMessage() method.
class Utility {
// shared resource is synchronized
synchronized public void printMessage(String msg) {
System.out.print("{");
System.out.print(msg);
System.out.println("}");
}
}
}
}
Output
Synchronized blocks
The solution described above is simple and accepted as long as you have the access to Utility class so that you can
modify it and add synchronized keyword. But, what if you are not the owner of Utility class? Meaning, you are not
authorized to modify the class and you cannot add the synchronized keyword to its method.
In these situations, you can go with synchronized blocks. Simply put calls to the methods defined by this class inside
a synchronized block. This is the general form of the synchronized statement:
synchronized(object) {
// statements to be synchronized
}
Here, object is a reference to the object being synchronized. A synchronized block ensures that a call to a method
that is a member of object occurs only after the current thread has successfully entered objects monitor.
class Utility {
public void printMessage(String msg) {
System.out.print("{");
System.out.print(msg);
System.out.println("}");
}
}
Output
wait():
This method tells the calling thread to give up the monitor and go to sleep until some other thread enters the
same monitor and calls notify().
notify():
This method wakes up the first thread that called wait() on the same object.
notifyAll():
This method wakes up all the threads that called wait() on the same object. The highest priority thread will run
first.
class Q {
int n;
boolean valueSet = false;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
Output:
Below figure shows the various states of a thread and its life cycle starting from New state to Terminated state.
Delegation Event Model constitutes of three entities: event, source, and listener.
Event
Event is an object that describes the state change. These objects are encapsulated in a class hierarchy rooted at
java.util.EventObject. An event is propagated from a "Source" object to a "Listener" object by invoking a method on the listener
and passing in the instance of the event subclass which defines the event type generated.
Source
An Event Source is an object which originates or "fires" events. (Example, an Applet). A source must register listeners in order for the
listeners to receive notifications about a specific type of event.
Registering a listener:
Each type of event has its own registration method. Here is the general form:
Here, Type is the name of the event, and el is a reference to the event listener. For example, the method
that registers a keyboard event listener is called addKeyListener(). The method that registers a mouse
motion listener is called addMouseMotionListener().
Unregistering a listener:
A source must also provide a method that allows a listener to unregister an interest in a specific type of
event. The general form of such a method is this:
Here, Type is the name of the event, and el is a reference to the event listener. For example,
to remove a keyboard listener, you would call removeKeyListener( ).
Listener
A listener is an object which will be notified when an event occurs. A Listener is an object that implements a specific EventListener
interface extended from the generic java.util.EventListener.
First, it must have been registered with one or more sources to receive notifications about specific types of events.
Second, it must implement methods to receive and process these notifications
3.11 Event
Almost for every possible type of event that can occur (Ex, click a button, scroll the mouse, etc), Java defines a separate class for it.
java.util.EventObject is the root of all the event classes. The class java.awt.AWTEvent, is a subclass of EventObject. It is the
superclass (either directly or indirectly) of all AWT-based events used by the delegation event model.
The package java.awt.event defines various event classes to describe the events generated by various user interface elements.
Here are the few:
KeyEvent
A KeyEvent is generated when keyboard input occurs. There are three types of key events, which are identified by these integer
constants:
KEY_PRESSED
KEY_RELEASED, and
KEY_TYPED.
The first two events are generated when any key is pressed or released. The last event occurs only when a character is generated.
Remember, not all key presses result in characters. For example, pressing SHIFT does not generate a character.
There are many other integer constants that are defined by KeyEvent.
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
For example,
VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the numbers and letters.
Here are some others:
VK_ALT VK_DOWN VK_LEFT VK_RIGHT
VK_CANCEL VK_ENTER VK_PAGE_DOWN VK_SHIFT
VK_CONTROL VK_ESCAPE VK_PAGE_UP VK_UP
The KeyEvent class defines several methods, but the most commonly used ones are getKeyChar( ), which returns the character that
was entered, and getKeyCode( ), which returns the key code. Their general forms are shown here:
char getKeyChar( )
int getKeyCode( )
MouseEvent
There are eight types of mouse events. The MouseEvent class defines the following integer constants that can be used to identify them:
Two commonly used methods in this class are getX( ) and getY( ). These returns the X and Y coordinate of the mouse within the
component when the event occurred. Their forms are shown here:
int getX()
int getY()
Table below lists some of the user interface components that can generate the events described in the previous section.
Listeners are created by implementing one or more of the interfaces defined by the java.awt.event package. When an event occurs,
the event source invokes the appropriate method defined by the listener and provides an event object as its argument. Table below lists
commonly used listener interfaces and provides a brief description of the methods that they define.
KeyListener interface
MouseListener interface
MouseMotionListener interface
To handle mouse events, you must implement the MouseListener and the MouseMotionListener interfaces. The following applet
demonstrates the process.
o It displays the current coordinates of the mouse in the applets status window.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
Output:
To handle key board events, you will be implementing KeyListener interface. Before going to the program, Let's see how key events are
generated.
o When a key is pressed, a KEY_PRESSED event is generated. This results in a call to the keyPressed() event
handler.
o When the key is released, a KEY_RELEASED event is generated and the keyReleased( ) handler is executed.
o If a character is generated by the keystroke, then a KEY_TYPED event is sent and the keyTyped( ) handler is
invoked.
Thus, each time the user presses a key, at least two and often three events are generated.
Here is the program to demonstrate the handling of key events.
import java.awt.*;
import java.awt.event.*;
Output
Definition
An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you
want to receive and process ONLY some of the events that are handled by a particular event listener interface. You can define a new
Table below shows Commonly Used Listener Interfaces Implemented by Adapter Classes.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
Till now we have seen how to handle events by using this reference.
Inner classes
Below example shows how to handle the events by using an inner class.
import java.applet.*;
import java.awt.event.*;
Advantage of handling the event by using inner class is that, the inner class can directly call the showStatus() method, and there is no
need to store a reference to the applet.
An anonymous inner class is one that is not assigned a name. This example illustrates how to use anonymous inner class to handle
events.
import java.applet.*;
import java.awt.event.*;
The syntax new MouseAdapter( ) { ... } indicates to the compiler that the code between the braces defines an anonymous inner class.
Furthermore, that class extends MouseAdapter. This new class is not named, but it is automatically instantiated when this expression is
executed.
JAVA/ J2EE
Notes prepared by
Mr. Ashok Kumar K
9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Unit 4:
Swings
4.1 Basics
AWT translates its various visual components into their corresponding, platform-specific equivalents, or peers. Therefore, the look and
feel will be decided by the platform and not by Java. Therefore, AWT is referred to as heavyweight. This led to following problems
Definition
Swing API is set of extensible GUI Components to ease developer's life to create JAVA based Front End/ GUI Applications. It is built on
top of AWT API and it overcomes most of its limitations. Swing has almost every control corresponding to AWT controls.
AWT Swing
AWT components are platform-dependent Swing are platform independent
AWT is called the abstract window tool Swing is part of the java foundation classes
AWT components are heavyweight components Swing components are lightweight components because
swing sits on the top of AWT
AWT occupies more memory space Swing occupies less memory space
AWT require javax.awt package Swing requires javax.swing package
AWT is not MVC based Swing are MVC based architecture
AWT works slower Swing works faster
Lightweight
Swing component are independent of native Operating System's API as Swing API controls are
rendered mostly using pure JAVA code instead of underlying operating system calls.
Swing based GUI Applications look and feel logic can be separated from the components business
logic.
It is possible to define look and feel that is consistent across all platforms.
Conversely, it is also possible to create a look and feel that acts like a specific platform.
It is also possible to create a custom look and feel.
Look and feel can be changed dynamically at runtime.
Rich controls
Swing provides a rich set of advanced controls like Tree, TabbedPane, slider, colorpicker, table controls
Highly Customizable
Swing controls can be customized in very easy way as visual appearance is independent of internal representation
Components
Containers
A container holds a group of components. Thus, container is a special type of component that is designed to
hold other components.
There are two types of containers
Top level containers (JFrame, JApplet, JWindow, and JDialog):
These containers do not inherit the JComponent. They do directly inherit the AWT classes
Component and Container. Therefore, they are heavyweight.
They cannot be contained within any other component.
Those who inherit JComponent are the second type of container:
They are lightweight
javax.swing
javax.swing.border
javax.swing.colorchooser
javax.swing.event
javax.swing.filechooser
javax.swing.plaf
javax.swing.plaf.basic
javax.swing.plaf.metal
javax.swing.plaf.multi
javax.swing.plaf.synth
javax.swing.table
javax.swing.text
javax.swing.text.html
javax.swing.text.html.parser
javax.swing.text.rtf
javax.swing.tree
javax.swing.undo
import javax.swing.*;
class Example
{
Example()
{
// Create a new JFrame container.
JFrame frame = new JFrame("My first Swing Application");
new Example();
}
}
Output
Basics
Change in the state of an object is known as event i.e. event describes the change in state of source. Events are generated as result of
user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a
character through keyboard, selecting an item from list, scrolling the page are the activities that causes an event to happen.
Foreground events: These events require the direct interaction of the user. Example: Click on a button
Background events: These dont require the interaction of the user. Example: OS interrupt.
As we learnt in unit 3, delegation event model has the following key participants namely:
public Example()
statusLabel.setSize(350, 100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent)
{
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
okButton.setActionCommand("OK");
submitButton.setActionCommand("Submit");
cancelButton.setActionCommand("Cancel");
okButton.addActionListener(new ButtonClickListener());
submitButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
controlPanel.add(okButton);
controlPanel.add(submitButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
Output
In order to design a listener class we have to develop some listener interfaces. These Listener interfaces forecast some public abstract
callback methods which must be implemented by the listener class.
If you do not implement the any if the predefined interfaces then your class can not act as a listener class for a source object.
Concept
Swing-based applets are similar to AWT-based applets, but it extends JApplet rather than Applet. JApplet is derived from Applet.
Thus, JApplet includes all of the functionality found in Applet and adds support for Swing.
Swing applets use the same four lifecycle methods as described in unit 2: init(), start(), stop(), and destroy()
Painting is accomplished differently in Swing than it is in the AWT, and a Swing applet will not normally override the paint() method.
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
This HTML can be used to launch the applet:
<object code="MySwingApplet" width=220 height=90>
</object>
*/
public class Example extends JApplet
{
JButton button1;
JButton button2;
JLabel label;
Output
Lets discuss some of the lightweight components derived from JComponent class.
Description
A JLabel object provides text instructions or information on a GUI display a single line of read-only text, an image or both text and
image.
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)
Here,
str and icon are the text and icon used for the label.
The align argument specifies the horizontal alignment of the text and/or icon within the dimensions of
the label. It must be one of the following values: LEFT, RIGHT, CENTER, LEADING, or TRAILING.
these constants are defined in the SwingConstants interface, along with several others used by the
Swing classes.
The easiest way to obtain an icon is to use the ImageIcon class. ImageIcon implements Icon and encapsulates an image. Thus, an
object of type ImageIcon can be passed as an argument to the Icon parameter of JLabels constructor
Example:
import javax.swing.*;
@SuppressWarnings("serial")
public class Example extends JApplet
{
public void init()
{
render();
// Create a label.
JLabel label = new JLabel("This is a sample message", imgIcon, JLabel.LEFT);
Output
4.9 JTextField
Description
JTextField is an input area where the user can type in characters. If you want to let the user enter multiple lines of text, you cannot
use JTextFields unless you create several of them. The solution is to use JTextArea, which enables the user to enter multiple lines
of text.
When the user types data into them and presses the Enter key, an action event occurs. If the program registers an event listener, the
listener processes the event and can use the data in the text field at the time of the event in the program
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
Here,
str is the string to be initially presented, and
If no string is specified, the text field is initially empty. If the number of columns is not specified, the text field is sized to fit the specified
string.
Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class Example extends JApplet
{
JTextField textfield;
textfield.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
// Show text when user presses ENTER.
showStatus(textfield.getText());
}
});
}
}
Output
The text associated with the button can be read and written via the following methods
String getText()
void setText(String str)
A button generates an action event when it is pressed. Other events are also possible.
JButton
The JButton class provides the functionality of a push button. JButton allows an icon, a string, or both to be associated with
the push button. When the button is pressed, an ActionEvent is generated and it is handled by the actionPerformed()
method of registered ActionListener
It defines three constructors
JButton(Icon icon)
JButton(String str)
JButton(String str, Icon icon)
Here, str and icon are the string and icon used for the button
Example:
import java.awt.*;
import java.awt.event.*;
@SuppressWarnings("serial")
public class Example extends JApplet implements ActionListener
{
JLabel label;
Output
JToggleButton
A toggle button looks just like a push button, but it acts differently because it has two states: pushed and released. That is,
when you press a toggle button, it stays pressed rather than popping back up as a regular push button does. When you
press the toggle button a second time, it releases (pops up). Therefore, each time a toggle button is pushed; it toggles
between its two states. It generates an ItemEvent.
Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class Example extends JApplet
{
JToggleButton toggleButton;
Output
JCheckBox
The JCheckBox class provides the functionality of a check box. When the user selects or deselects a check box, an
ItemEvent is generated.
Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class Example extends JApplet implements ItemListener
{
JLabel label;
cb = new JCheckBox("C++");
cb.addItemListener(this);
add(cb);
cb = new JCheckBox("Java");
cb.addItemListener(this);
add(cb);
// Create the label and add it to the content pane.
label = new JLabel("Select languages");
add(label);
}
Output
JRadioButton
Radio buttons are a group of mutually exclusive buttons, in which only one button can be selected at any one time.
Example
import java.awt.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class Example extends JApplet implements ActionListener
{
JLabel label;
Output
4.11 JTabbedPane
Description
A JTabbedPane contains a tab that can have a tool tip and a mnemonic, and it can display both text and an image.
Example:
import javax.swing.*;
@SuppressWarnings("serial")
public class Example extends JApplet
{
public void init()
{
render();
}
@SuppressWarnings("serial")
class Sem2 extends JPanel
{
public Sem2()
{
JButton b1 = new JButton("Mathematics 2");
add(b1);
JButton b2 = new JButton("Civil");
add(b2);
JButton b3 = new JButton("Basic Electricals");
add(b3);
JButton b4 = new JButton("Physics");
add(b4);
}
}
Output
4.12 JScrollPane
Description
JScrollPane is a lightweight container that automatically handles the scrolling of another component. The component being scrolled
can either be an individual component, such as a table, or a group of components contained within another lightweight container, such
as a JPanel. In either case, if the object being scrolled is larger than the viewable area, horizontal and/or vertical scroll bars are
automatically provided, and the component can be scrolled through the pane. Because JScrollPane automates scrolling, it usually
eliminates the need to manage individual scroll bars
Example
import java.awt.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class Example extends JApplet
{
public void init()
{
render();
}
Output
4.13 JList
Description
Example
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
@SuppressWarnings("serial")
public class Example extends JApplet
{
JList<Object> list;
JLabel label;
JScrollPane scrollpane;
Output
4.14 JComboBox
Description
JComboBox is a combination of a text field and a drop-down list. A combo box normally displays one entry, but it will also display a drop-
down list that allows a user to select a different entry.
Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
@SuppressWarnings("serial")
public class Example extends JApplet
{
JLabel label;
JComboBox<Object> comboBox;
String flags[] = { "aklc", "jmaster" };
// Handle selections.
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae)
{
String s = (String) comboBox.getSelectedItem();
label.setIcon(new ImageIcon(s + ".png"));
}
});
Output
4.15 JTable
JTable is a component that displays rows and columns of data. You can drag the cursor on column boundaries to resize columns. You
can also drag a column to a new position. Depending on its configuration, it is also possible to select a row, column, or cell within the
table, and to change the data within a cell.
Example
import javax.swing.*;
/*
<applet code="JTableDemo" width=400 height=200>
</applet>
*/
@SuppressWarnings("serial")
public class Example extends JApplet
{
public void init()
{
render();
}
Output
VTU
7th sem B.E (CSE/ISE)
JAVA/ J2EE
Notes prepared by
Mr. Ashok Kumar K
9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
INTRODUCTION TO J2EE
1. Standalone applications
Standalone applications are those which works based on where you write the code is where you run the code. i.e., if you
want to run a standalone application in a clients machine, you need to have the code residing in that machine; else the
application is not runnable.
Example: Games (which requires installations), GTalk, etc
2. Web applications
Here it is not required for the code to be present in every clients machine. Instead, the application will be deployed in a
centralized sever, whereas the clients makes a request to access this application through a web browser. Server processes
multiple clients request and makes a response to each client request.
3. Mobile applications
These are the application developed for hand held devices like PDAs, mobile phones, IPODs, IPADs, etc.
J2SE (Java to Standard Edition) is a Java platform designed for standalone applications.
J2EE (Java to Enterprise Edition) is a Java platform designed for Web applications or server side
applications.
J2ME (Java to Micro Edition) is a Java platform designed for Mobile applications.`
J2EE is a multi-tier architecture (four layered architecture). The layers are named as follows:
Client tier
Web tier
Business logic tier
Database tier
Client tier
Any component that is capable of initiating a request to the server is said to sit in the client tier of the J2EE
architecture.
Example for client tier component would be a HTML page, browser, etc
Web tier
Web tier component receives the request from the client tier component and forwards the request to the
appropriate business logic tier to process it. Due to security perspective and other issues, the business logic
is delegated to the next tier.
Example for Web tier component would be a servlet.
The components in this tier are responsible for implementing the core business logic for the request from
client tier.
Example for business logic tier component would be a EJB (Enterprise Java Bean).
It might make a connection to the fourth tier to perform various database operations.
Database tier
The components in this tier are responsible for storing the applications data.
They provide the applications data to the upper tiers upon making a request.
Example: MySQL, Oracle, DB2, and Sybase database.
Unit 5:
5.1 Basics
Definition
JDBC (Java Database Connectivity) is an API for the Java programming language that defines how a client may access the database.
It provides methods for querying and updating data in a database. JDBC is oriented towards relational databases.
JDBC classes are present in java.sql package.
History
JDBC was a part of JDK 1.1 (Feb 19, 1997) and was developed by a team named Javasoft of Sun Microsystems.
JDBC Components
JDBC project by Javasoft comprises of two things: JDBC APIs and JDBC Driver
JDBC APIs
JDBC APIs are the library functions that performs common tasks associated with database usage like:
Opening/ Closing the connection with the database, Creating SQL statements, Executing that SQL queries
in the database, and Viewing & Modifying the resulting records
JDBC Driver
A JDBC driver is a software component enabling a Java application to interact with a database. It is the
actual implementation of the defined interfaces in the JDBC API for interacting with your database server.
There are many possible implementations of JDBC drivers. These implementations are categorized as follows:
These drivers implement the JDBC API as a mapping to another data access API, such as ODBC (Open Database
Connectivity). Drivers of this type are generally dependent on a native library, which limits their portability.
Example: The JDBC-ODBC Bridge.
These drivers are written partly in the Java programming language and partly in native code. These drivers use a native
client library specific to the data source to which they connect. Again, because of the native code, their portability is
limited.
Example: Oracle's OCI (Oracle Call Interface) client-side driver.
These drivers use a pure Java client and communicate with a middleware server using a database-independent protocol.
The middleware server then communicates the client's requests to the data source.
These drivers are pure Java and implement the network protocol for a specific data source. The client connects directly to
the data source.
There are five steps in the JDBC process for a Java program to communicate with the database. Let's see them in brief and later
elaborate each step.
Here you should load and initialize the class representing the MySQL JDBC Driver. The code snippet to do
this is given below:
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e) {
System.out.println("Couldn't load the Driver");
}
Next, you need to establish a connection with the data source you want to use. A data source can be a
DBMS, a legacy file system, or some other source of data with a corresponding JDBC driver. We use the
static getConnection() method in DriverManager class to get the connection. Its syntax is shown below:
Step 3: Create the SQL Statement and Execute the SQL Query
Statement st = null;
ResultSet rs = null;
String qry = "select * from student";
try {
st = con.createStatement();
rs = st.executeQuery(qry);
} catch (SQLException e) {
System.out.println("Error while processing SQL query");
}
The output of the SQL query will be encapsulated in ResultSet object. A ResultSet object contains zero
or more records (or rows). We should iterate over each record (or row) in order to print it in the console as
demonstrated below:
try {
String id, name;
int age;
double aggregate;
while (rs.next()) {
id = rs.getString("id");
name = rs.getString("name");
age = rs.getInt("age");
aggregate = rs.getDouble("aggr");
System.out.println(id + "\t" + name + "\t" + age +
"\t" + aggregate);
}
} catch (SQLException e) {
System.out.println("Error while processing SQL results");
}
At last, a very important step of all is to close the database connection. This releases the external resources
like cursor, handlers etc. Typically, closing the connection should be done in the finally block.
try {
con.close();
} catch (Exception e) {
System.out.println("Error while closing the connection");
}
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
When you are using JDBC outside of an application server, the DriverManager class manages the establishment of Connections. You
should specify to the DriverManager which JDBC drivers it should try to make Connections with. The easiest way to do this is to use
Class.forName() on the class that implements the java.sql.Driver interface. With MySQL, the name of this class is
com.mysql.jdbc.Driver.
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e) {
System.out.println("Couldn't load the Driver");
}
Make sure that the driver class (com.mysql.jdbc.Driver) is available in the classpath so that it can be loaded and initialized by the
JVM.
Concept
Once the JDBC driver has been loaded and initialized, the Java component can now obtain a connection to the external database
associated with the driver. To do this, you must invoke getConnection() method of DriverManager class passing three arguments
as shown in the syntax below:
Here,
url: a database url of the form jdbc:subprotocol:subname
user: the database user on whose behalf the connection is being made
password: the user's password
Example:
Some databases would require additional details other than username and password to grant the access to the database. The question
here is how would you provide these additional propertied to DriverManager's getConnection() method. This additional information
must be associated with a Properties object which is passed as an argument in getConnection() method.
Example:
Connection con = null;
try {
FileInputStream fis = new FileInputStream( new File("DBProps.txt") );
Properties props = new Properties();
props.load(fis);
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", props);
} catch (SQLException e) {
System.out.println("Couldn't Obtain the connection");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Setting Timeout
Whenever a J2EE component requests connection with the external database, there are possibilities where the DBMS may not respond
to it due to various reasons. In this case, the J2EE component will wait indefinitely till the DBMS responds to it. To avoid this indefinite
delay, you can set a timeout period after which the DriverManager will stall (cancel) the attempt to connect to the DBMS.
To set the timeout period, you can use setoginTimeout() method in DriverManager class whose syntax is given below:
Likewise, you can use getLoginTimeout() method to retrieve the current timeout period that has been set. Its syntax is shown below:
A Statement is an interface that represents a SQL statement. You execute Statement objects, and they generate ResultSet objects,
which is a table of data representing a database result set. You need a Connection object to create a Statement object.
For example,
stmt = con.createStatement();
Statement:
Used to implement simple SQL statements with no parameters.
Statement
The Statement object is used whenever a J2EE component needs to immediately execute a query without first having the query
compiled. Before you can use a Statement object to execute a SQL statement, you need to create one using the Connection object's
createStatement() method, as in the following example:
Statement st = null;
try {
st = con.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
Once you've created a Statement object, you can then use it to execute a SQL statement with one of its three execute methods.
boolean execute(String SQL) : Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns
false. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL.
int executeUpdate(String SQL) : Returns the numbers of rows affected by the execution of the SQL statement. Use this
method to execute SQL statements for which you expect to get a number of rows affected - for example, an INSERT,
UPDATE, or DELETE statement.
ResultSet executeQuery(String SQL) : Returns a ResultSet object. Use this method when you expect to get a result set,
as you would with a SELECT statement.
Just as you close a Connection object to save database resources, for the same reason you should also close the Statement object. A
simple call to the close() method will do the job.
Example:
import java.sql.*;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college",
"root", "lordshiva");
String qry = "select * from student";
st = con.createStatement();
rs = st.executeQuery(qry);
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
PreparedStatement
The PreparedStatement is used to compile the query first before executing it. The PreparedStatement interface extends the
Statement interface which gives you added functionality. This statement gives you the flexibility of supplying input arguments
dynamically. All parameters (arguments) are represented by the ? symbol, which is known as the place holder. You must supply values
for every parameter before executing the SQL statement. The setXXX() methods bind values to the parameters, where XXX
represents the Java data type of the value you wish to bind to the input parameter. Each parameter marker is referred to by its ordinal
position. The first marker represents position 1, the next position 2, and so forth. If you forget to supply the values, you will receive an
SQLException. All of the Statement object's methods for interacting with the database: execute(), executeQuery(), and
executeUpdate() also work with the PreparedStatement object. However, the methods are modified to use SQL statements that can
take input the parameters..
Example
PreparedStatement ps = null;
try {
String qry = "update student set name=? where id=?";
ps = con.prepareStatement(qry);
ps.setString(1, "Ashok Kumar");
ps.setString(2, "1VK06IS009");
ps.execute();
}
catch (SQLException e) {
Just as you close a Statement object, for the same reason you should also close the PreparedStatement object. A simple call to the
close() method will do the job.
CallableStatement
CallableStatement object is used to execute a call to the stored procedure from within a J2EE object. The stored procedure can be
written in PL/SQL, Transact-SQL, C, or another programming language. The stored procedure is a block of code and is identified by a
unique name.
Here is the simple MySQL stored procedure:
IN: A parameter whose value is unknown when the SQL statement is created. You bind values to IN parameters with the
setXXX() methods.
OUT: A parameter whose value is supplied by the SQL statement it returns. You should register this parameter using
registerOutParameter() method. You retrieve values from the OUT parameters with the getXXX() methods.
INOUT: A parameter that provides both input and output values. You bind variables with the setXXX() methods and retrieve
values with the getXXX() methods.
Example
CallableStatement cs = null;
try {
String qry = "{CALL getStudName (?,?) }";
cs = con.prepareCall(qry);
cs.setString(1, "1VK06IS009");
cs.registerOutParameter(2, Types.VARCHAR);
cs.execute();
Just as you close other Statement object, for the same reason you should also close the CallableStatement object. A simple call to
the close() method will do the job.
String qry = "select * from student"; String qry = "update student String qry = "{CALL
set name=? where id=?"; getStudName (?,?) }";
Statement st = con.createStatement();
PreparedStatement ps = CallableStatement cs =
rs = st.executeQuery(qry); con.prepareStatement(qry); con.prepareCall(qry);
ps.execute(); cs.execute();
As you know, the executeQuery() method is used to send the query to the DBMS and returns a ResultSet object that contains data
that was requested by the query. A ResultSet object maintains a virtual cursor that points to a row in the result set. The term "result
set" refers to the virtual table of row and column data contained in a ResultSet object. The virtual cursor is initially positioned above
the first row of data when the ResultSet is returned by executeQuery() method.
There are various methods in the ResultSet interface. These methods can be grouped into three categories as follows
Get methods: used to view the data in the columns of the current row being pointed by the virtual cursor.
Navigational methods: used to move the virtual cursor around the virtual table.
Update methods: used to update the data in the columns of the current row.
There is a get method in ResultSet interface for each of the possible data types of the form getXXX() where XXX is the data type of
the column, and each get method has two versions:
One that takes in a column name
Example:
String name = rs.getString("name");
One that takes in a column index.
Example:
String name = rs.getString(1);
Example:
import java.sql.*;
Output:
Types of ResultSet
You should specify one of the type of ResultSet while creating a Statement object. You should pass this as an argument to
createStatement() or preparedStatement() method. If you don't specify anything, the default one will be TYPE_FORWARD_ONLY.
Concurrency of ResultSet
Rows contained in ResultSet's virtual table can either be read only or be updatable. This selection can be made by passing either one
of the below as an argument to createStatement() or preparedStatement() method.
Example 1:
Statement st = null;
st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
Example 2:
Statement st = null;
st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
Scrolling a ResultSet
There are several methods in the ResultSet interface that involve moving the cursor. They are:
1
Moves the cursor to the front of this ResultSet object, just before the first row. This method has no effect if the result set
contains no rows.
2
Moves the cursor to the end of this ResultSet object, just after the last row. This method has no effect if the result set
contains no rows.
Moves the cursor to the given row number in this ResultSet object.
If the row number is positive, the cursor moves to the given row number with respect to the beginning of the result set.
The first row is row 1, the second is row 2, and so on.
5
If the given row number is negative, the cursor moves to an absolute row position with respect to the end of the result
set. For example, calling the method absolute(-1) positions the cursor on the last row; calling the method absolute(-2)
moves the cursor to the next-to-last row, and so on.
An attempt to position the cursor beyond the first/last row in the result set leaves the cursor before the first row or after
the last row.
6 Moves the cursor a relative number of rows, either positive or negative. Attempting to move beyond the first/last row in
the result set positions the cursor before/after the first/last row. Calling relative(0) is valid, but does not change the
cursor position.
Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row;
the first call to the method next makes the first row the current row; the second call makes the second row the current
8
row, and so on.
When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet
method which requires a current row will result in a SQLException being thrown.
10 Moves the cursor to the insert row. The current cursor position is remembered while the cursor is positioned on the
insert row. The insert row is a special row associated with an updatable result set. It is essentially a buffer where a new
row may be constructed by calling the updater methods prior to inserting the row into the result set
11 Moves the cursor to the remembered cursor position, usually the current row. This method has no effect if the cursor is
not on the insert row.
Note 1: Not all the Drivers are scrollable. Here is the code snippet to test whether a driver supports a
scrollable ResultSet
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = null;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college",
"root", "lordshiva");
} catch (Exception e) {
e.printStackTrace();
}
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = null;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college",
"root", "lordshiva");
Statement st = con.createStatement();
st.setFetchSize(200);
ResultSet rs = st.executeQuery("select * from student");
} catch (Exception e) {
e.printStackTrace();
}
Updating a ResultSet
The ResultSet interface contains a collection of update methods for updating the data of a result set. As with the get methods, there
are two updateXXX() methods for each data type, where XXX is the data type of the column:\
Updating a row in the result set changes the columns of the current row in the ResultSet object (virtual table), but not in the underlying
database. To update your changes to the row in the database, you need to invoke one of the following methods.
Examples:
rs = st.executeQuery(qry);
while (rs.next()) {
if (rs.getString("name").equals("Ashok")) {
rs.updateString("name", "Ashok Kumar");
rs.updateRow();
}
}
2. Deleting a Row
rs = st.executeQuery(qry);
while (rs.next()) {
if (rs.getString("name").equals("Prasad")) {
rs.deleteRow();
}
}
A Database Transaction consists of a set of SQL statements, each of which must be successfully completed for the transaction to be
completed. If one fails, SQL statements that executed successfully up to that point in the transaction must be rolled back.
A database transaction, by definition, must be atomic, consistent, isolated and durable. Database practitioners often refer to these
properties of database transactions using the acronym ACID.
Atomicity:
Atomicity requires that each transaction is "all or nothing": if one part of the transaction fails, the entire transaction fails, and
the database state is left unchanged. An atomic system must guarantee atomicity in each and every situation, including power
failures, errors, and crashes. To the outside world, a committed transaction appears (by its effects on the database) to be
indivisible ("atomic"), and an aborted transaction does not happen.
Consistency:
The consistency property ensures that any transaction will bring the database from one valid state to another. Any data written
to the database must be valid according to all defined rules, including but not limited to constraints, cascades, triggers, and
any combination thereof.
A Transactional database is a DBMS where write transactions on the database are able to be rolled back if they are not completed
properly (e.g. due to power or connectivity loss). Most modern relational database management systems fall into the category of
databases that support transactions.
A database transaction isn't completed until the J2EE component calls the commit() method of the Connection object. All SQL
statements executed prior to the call to the commit() method can be rolled back. However, once the commit() method is called, none of
the SQL statements can be rolled back.
The commit() method must be called regardless if the SQL statement is part of a transaction or not. Till now, we never issued a
commit() on the database but still we were able to save the data in the database. This is because of the auto commit feature of the
database connection.
If a J2EE component is implementing a transaction, then the auto commit feature should be turned off. This can be done as follows:
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = null;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college",
"root", "lordshiva");
con.setAutoCommit(false);
} catch (Exception e) {
e.printStackTrace();
}
Let's see a simple transaction processing example. Below program executes two SQL queries, both of which update the student's
aggregate and age. Each SQL statement will be executed separately and a commit() method is called upon success. However, if any of
the statement fails (throws an exception), the transaction is rolled back by invoking rollback() method in the catch clause.
import java.sql.*;
try {
Class.forName("com.mysql.jdbc.Driver");
st1 = con.createStatement();
st2 = con.createStatement();
st1.execute(qry1);
st2.execute(qry2);
con.commit();
} catch (Exception e) {
System.out.println("Transaction failed ..");
try {
con.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
finally {
try {
st1.close();
st2.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Using savepoints
A transaction may consist of many tasks, some of which don't need to be rolled back when the transaction fails. The J2EE component
can control the number of tasks that are rolled back by using savepoints. A savepoint is a virtual marker that defines the task at which
the rollback stops.
When you set a savepoint you define a logical rollback point within a transaction. If an error occurs past a savepoint, you can use the
rollback method to undo either all the changes or only the changes made after the savepoint.
Example,
Here we execute two SQL statements. After executing one SQL statement, a savepoint is set. The transaction is rolled back till this
savepoint after executing both the statements. Thus only second SQL statement will be rolled back and the first SQL statement will be
committed.
import java.sql.*;
try {
Class.forName("com.mysql.jdbc.Driver");
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
con = DriverManager.getConnection
"jdbc:mysql://localhost:3306/college", "root", "lordshiva");
con.setAutoCommit(false);
st1 = con.createStatement();
st2 = con.createStatement();
st1.execute(qry1);
st2.execute(qry2);
con.rollback(sp1);
con.releaseSavepoint(sp1);
con.commit();
} catch (Exception e) {
System.out.println("Transaction failed ..");
try {
con.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
finally {
try {
st1.close();
st2.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database. When you
send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving
performance.
The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the
batch. The executeBatch() is used to start the execution of all the statements grouped together.
The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update
statement. A value of -1 indicates the failure of update statement.
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes
all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove
Example
import java.sql.*;
try {
Class.forName("com.mysql.jdbc.Driver");
st1 = con.createStatement();
st1.addBatch(qry1);
st1.addBatch(qry2);
st1.addBatch(qry3);
st1.executeBatch();
st1.clearBatch();
con.commit();
} catch (Exception e) {
System.out.println("Transaction failed ..");
try {
con.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
finally {
try {
st1.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
There are two types of metadata that can be retrieved from the DBMS.
DatabaseMetaData which is the data about the database
ResultSetMetaData which is the data about the Result Set
DatabaseMetaData
Meta data is the data about the data. A J2EE component can access the metadata by using the DatabaseMetaData interface. It is used
to retrieve information about databases, tables, column, indexes, etc.
getMetaData() method of Connection object is used to retrieve the metadata about the database. Here are some of the methods
available in DatabaseMetaData interface:
Example
import java.sql.*;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/college", "root", "lordshiva");
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
ResultSetMetaData
ResultSetMetaData interface describes the Result set (virtual database). getMetaData() method of the ResultSet object can be used
to retrieve the Result set metadata. The most commonly used methods in ResultSetMetaData interface are:
Example
import java.sql.*;
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Output:
5.10 Exceptions
There are three kinds of exceptions that are thrown by JDBC methods.
SQLException:
It commonly reflects a syntax error in the query and is thrown by many of the methods contained in java.sql package.
SQLWarning:
It throws warnings received by the connection from the DBMS. The getWarning() method of the Connection object retrieves
the warning and the getNextWarning() method retrieves the subsequent warnings.
DataTruncation:
It is thrown whenever a data is lost due to the truncation of the data value.
JAVA/ J2EE
Notes prepared by
Mr. Ashok Kumar K
9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Unit 6:
Servlet
6.1 History
Earlier in client- server computing, each application had its own client program and it worked as a user interface and need to be
installed on each user's personal computer.
Later we had the era of Common Gateway Interface (CGI). The Common Gateway Interface was one of the practical techniques
developed for creating dynamic content. By using the CGI, a web server passes requests to an external program and after executing
the program the content is sent to the client as the output.
In CGI when a server receives a request it creates a new process to run the CGI program, so creating a process for each request
requires significant server resources and time, which limits the number of requests that can be processed concurrently. CGI
applications are platform dependent. There is no doubt that CGI played a major role in the explosion of the Internet but its performance,
scalability issues make it less than optimal solutions.
Java Servlets often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But Servlets offer
several advantages in comparison with the CGI.
Servlet CGI
Servlets is inexpensive in terms of memory usage CGI is more expensive than Servlets in terms of
memory usage
Servlet are platform independent CGI is platform dependent
In Servlets, the Java Virtual Machine stays up, and each request In CGI, each request is handled by a
is handled by a lightweight Java thread. heavyweight operating system process.
Java security manager on the server enforces a set of restrictions There is no support for Security Manager in CGI
to protect the resources on a server machine. So servlets are
trusted.
The full functionality of the Java class libraries is available to a CGI has limited libraries
servlet. It can communicate with applets, databases, or other
software via the sockets and RMI mechanisms that you have
seen already.
Servlets can link directly to the Web server CGI cannot directly link to Web server.
Servlets can share data among each other CGI does not provide sharing property
Servlets can perform session tracking and caching of previous CGI cannot perform session tracking and caching
computations. of previous computations.
Servlets can read and set HTTP headers, handle cookies, CGI cannot read and set HTTP headers, handle
tracking sessions cookies, tracking sessions.
Defining a Servlet
Java Servlets are programs that run on a Web or Application server and act as a middle layer between a request coming from a Web
browser or other HTTP client and databases or applications on the HTTP server. Using Servlets, you can collect input from users
through web page forms, present records from a database or another source, and create web pages dynamically.
Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. For
such applications, Java Servlet technology defines HTTP-specific servlet classes.
Prerequisite:
JDK is installed and configured properly.
Like any other Java program, you need to compile a servlet by using the Java compiler javac and after compiling the servlet application,
it would be deployed in a configured environment to test and run.
To run a Servlet, you need a web server that supports Servlet. Apache Tomcat is one of them. Apache Tomcat is an open source
software implementation of the Java Servlet and Java Server Pages (JSP) technologies and can act as a standalone server for testing
servlets and can be integrated with the Apache Web Server. Here are the steps to setup Tomcat on your machine:
In Windows
%CATALINA_HOME%\bin\startup.bat
or
C:\apache-tomcat-5.5.29\bin\startup.bat
In Linux/ Unix
$CATALINA_HOME/bin/startup.sh
or
/usr/local/apache-tomcat-5.5.29/bin/startup.sh
After startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine
then it should display following result:
In Windows
%CATALINA_HOME%\bin\shutdown
or
C:\apache-tomcat-5.5.29\bin\shutdown
In Linux
$CATALINA_HOME/bin/shutdown.sh
or
/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh
A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a
servlet.
1. Browser sends a HTTP request to the web server (through URL, submitting a form, etc)
2. Web server receives the request and maps this request to a particular Servlet. The servlet is retrieved and
dynamically loaded into the server address space
3. init() method of the servlet is called by the web server only when the servlet is first loaded into the memory. You
may pass initialization parameters to this method to configure the Servlet.
4. Web server invokes service() method of the servlet. This method is called to process the HTTP request. It is
possible to read the parameters from the request and is also possible to send a response back to the browser.
The servlet remains in the servers address space and is available to process any other HTTP requests received
from clients. The service() method is called for each HTTP request.
5. Finally, the server may decide to unload the servlet from its memory. The algorithms by which this determination
is made are specific to each server. The server calls the destroy() method to relinquish any resources such as
file handles that are allocated for the servlet.
You can visualize the servlet architecture through the following figure.
Web server
A web server uses HTTP protocol to transfer data. In a simple situation, a user type in a URL (e.g. www.jmaster.in) in browser (a client),
and get a web page to read. So what the server does is sending a web page to the client. The transformation is in HTTP protocol which
specifies the format of request and response message. Examples for noncommercial web servers are Apache Tomcat, JBoss,
GlassFish, Jetty, etc
Servlet Container
Servlet container is the component of a web server that interacts with Java servlets. A Servlet container is responsible for managing the
lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights. A web
container implements the web component contract of the Java EE architecture, specifying a runtime environment for web components
that includes security, concurrency, lifecycle management, transaction, deployment, and other services.
GenericServlet HTTPServlet
Two packages contain the classes and interfaces that are required to build servlets. These are
javax.servlet, and
javax.servlet.http.
They constitute the Servlet API. Keep in mind that these packages are not part of the Java core packages. Instead, they are standard
extensions provided by the web servers.
javax.servlet package
Below are some of the classes and interfaces defined in javax.servlet package
Interfaces
Interface Description
Servlet Declares life cycle methods for a servlet
ServletConfig Allows servlets to get initialization parameters
ServletContext Enables servlets to log events and access information about their
environment.
ServletRequest Used to read data from a client request
ServletResponse Used to write data to a client response
Classes
Class Description
GenericServlet Implements the Servlet and ServletConfig interfaces.
ServletInputStream Provides an input stream for reading requests from a client.
ServletOutputStream Provides an output stream for writing responses to a client.
ServletException Indicates a servlet error occurred.
UnavailableException Indicates a servlet is unavailable.
javax.servlet.http package
Below are some of the classes and interfaces defined in javax.servlet.http package
Interfaces
Interface Description
HttpServletRequest Enables servlets to read data from an HTTP request.
HttpServletResponse Enables servlets to write data to an HTTP response.
HttpSession Allows session data to be read and written.
HttpSessionBindingListener Informs an object that it is bound to or unbound from a
session.
Classes
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Class Description
Cookie Allows state information to be stored on a client machine.
HttpServlet Provides methods to handle HTTP requests and responses.
HttpSessionEvent Encapsulates a session-changed event.
HttpSessionBindingEvent Indicates when a listener is bound to or unbound from a session
value, or that a session attribute changed.
And, here is the structure of your dynamic web project created in Eclipse. Notice the placement of the above files in the project.
package com.aklc.servlet;
import java.io.*;
import javax.servlet.*;
<html>
<body>
<h2> Servlet Examples </h2>
<a href='hello'>Click here</a> to run a simple servlet.
</body>
</html>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>com.aklc.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
You can directly run the project in any of the web browser by entering the below URL (provided that the application is deployed in
tomcat server and it is up and running)
http://localhost:8080/<Project_name>/<url_pattern>
http://localhost:8080/PractiseApp/hello.html
The ServletRequest interface includes methods that allow you to read the names and values of parameters that are included in a
client request. We will develop a servlet that illustrates their use.
And, here is the structure of your dynamic web project created in Eclipse. Notice the placement of the above files in the project.
package com.aklc.servlet;
import java.io.*;
import javax.servlet.*;
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
String name=req.getParameter("username");
pw.println("<h2> Welcome, "+name+"</h2>");
pw.close();
}
<html>
<body>
Passing parameters to a Servlet
<form action='paramEx'>
Enter your name:
<input type='text' name='username' />
<br/> <br/>
<input type='submit' value='Click me' />
<servlet>
<servlet-name>ParamServlet</servlet-name>
<servlet-class>com.aklc.servlet.ReadParamServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ParamServlet</servlet-name>
<url-pattern>/paramEx</url-pattern>
</servlet-mapping>
Whenever the web browser fetches a file (a page, a picture, etc) from a web server, it does so using HTTP (Hypertext Transfer
Protocol). HTTP is a request/response protocol, which means your computer sends a request for some file (ex, Get me the file
'home.html'), and the web server sends back a response ("Here's the file", followed by the file itself).
The HttpServlet class provides specialized methods that handle the various types of HTTP requests. A servlet developer typically
overrides one of these methods. These methods are doDelete(), doGet(), doHead(), doOptions(), doPost(), doPut(), and doTrace().
Here we will develop a servlet that handles an HTTP GET request. The servlet is invoked when a form on a web page is submitted.
And, here is the structure of your dynamic web project created in Eclipse. Notice the placement of the above files in the project.
package com.aklc.servlet;
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
String un = req.getParameter("username");
String pwd = req.getParameter("password");
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
pw.println("<h2> Welcome, "+un+"</h2>");
pw.println("<br/><h2> Your password is .. "+pwd);
pw.close();
<html>
<body>
Handling HTTP Get Request <br/>
<form action='getReq' method='get'>
Enter your name:
<input type='text' name='username' />
<br/> <br/>
Enter your password:
<input type='password' name='password' />
<br/> <br/>
<servlet>
<servlet-name>GetReqServlet</servlet-name>
<servlet-class>com.aklc.servlet.GetRequestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetReqServlet</servlet-name>
<url-pattern>/getReq</url-pattern>
</servlet-mapping>
Upon clicking on "Click me" button, it takes you to the below screen.
Here we will develop a servlet that handles an HTTP POST request. The servlet is invoked when a form on a web page is submitted.
And, here is the structure of your dynamic web project created in Eclipse. Notice the placement of the above files in the project.
package com.aklc.servlet;
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
String un = req.getParameter("username");
String pwd = req.getParameter("password");
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
pw.println("<h2> Welcome, "+un+"</h2>");
pw.println("<br/><h2> Your password is .. "+pwd);
pw.close();
<html>
<body>
Handling HTTP Post Request <br/>
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
<form action='postReq' method='post'>
Enter your name:
<input type='text' name='username' />
<br/> <br/>
Enter your password:
<input type='password' name='password' />
<br/> <br/>
<servlet>
<servlet-name>PostReqServlet</servlet-name>
<servlet-class>com.aklc.servlet.PostRequestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PostReqServlet</servlet-name>
<url-pattern>/postReq</url-pattern>
</servlet-mapping>
Upon clicking on "Click me" button, it takes you to the below screen.
Parameters for an HTTP GET request are included as Parameters for an HTTP POST request are NOT
part of the URL that is sent to the web server. included as part of the URL that is sent to the web
server.
Example:
http://localhost:8080/PractiseApp/getReq? Example: http://localhost:8080/PractiseApp/postReq
username=Ashok&password=lordshiva
6.7 Cookies
Concept
Web applications are typically a series of HTTP requests and responses. As HTTP is a stateless protocol, information is not
automatically saved between HTTP requests. Web applications use cookies to store state information on the client. Cookies can be
used to store information about the user, the user's shopping cart, and so on.
Cookies are small bits of textual information that a Web server sends to a browser. By having the server read cookies it sent the client
previously, the site can provide visitors with a number of conveniences like
Identifying a user during e-commerce session
Avoiding username and password entered again and again
Customizing a site based on user's browsing history
Focusing Advertisement
The Cookie class provides an easy way for servlet to read, create, and manipulate HTTP cookies on the web browser. A servlet uses
the getCookies() method of HTTPServletRequest class to retrieve cookies as request. The addCookie() method of
HTTPServletResponse class sends a new cookie to the browser. You can set the age of cookie by setMaxAge() method.
And, here is the structure of your dynamic web project created in Eclipse. Notice the placement of the above files in the project.
package com.aklc.servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
String id = req.getParameter("id");
Cookie mycookie = new Cookie("RegID", id);
resp.addCookie(mycookie);
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
pw.println("<h2> Cookie has been successfully created .. </h2>");
pw.close();
<html>
<body>
Creating a cookie .. <br/><br/>
<form action='writeCookie' >
Enter your Reg ID:
<input type='text' name='id' />
<br/><br/>
<input type='submit' value='Click me' />
</form>
</body>
</html>
<servlet>
<servlet-name>WriteCookie</servlet-name>
<servlet-class>com.aklc.servlet.WriteCookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WriteCookie</servlet-name>
<url-pattern>/writeCookie</url-pattern>
</servlet-mapping>
Here we will develop a simple web application that creates a new Cookie variable by name 'RegID' in the browser.
And, here is the structure of your dynamic web project created in Eclipse. Notice the placement of the above files in the project.
package com.aklc.servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
<html>
<body>
Reading a cookie .. <br/><br/>
<form action='readCookie' >
<input type='submit' value='Click me' />
</form>
</body>
</html>
<servlet>
<servlet-name>readCookie</servlet-name>
<servlet-class>com.aklc.servlet.ReadCookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>readCookie</servlet-name>
<url-pattern>/readCookie</url-pattern>
</servlet-mapping>
As mentioned earlier, HTTP is a "stateless" protocol which means each time when a client retrieves a web page, the client opens a
separate connection to the web server and the server does not keep any record of previous client request. The question here is how
can we maintain the session between the client and a server?
What happens if we don't maintain the session between the client and the server?
To understand this, take an example of online shopping experience. When you are doing on-line shopping,
if the session is not maintained then it makes our shopping application problematic. When you add an entry
to your cart, how does the server know what's already in your cart? Even if servers did retain contextual
information, you'd still have problems with e-commerce. When you move from the page where you specify
what you want to buy (hosted on the regular web server) to the page that takes your credit card number
and shipping address (hosted on the secure server that uses SSL), how does the server remember what
you were buying?
Cookies
A web server can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they
can be recognized using the received cookie.
Drawback: This may not be an effective way because many time browser does not support a cookie.
Hidden fields
A web server can send a hidden HTML form field along with a unique session ID as follows:
<input type="hidden" name="sessionid" value="12345">
This entry means that, when the form is submitted, the specified name and value are automatically included in the request.
Each time when web browser sends request back, then session_id value can be used to keep the track of different web
browsers.
Drawback: Clicking on a regular (< a href='' > ) anchor link does not result in a form submission, so hidden form fields also
cannot support general session tracking.
URL Rewriting
Drawback: You would have generate every URL dynamically to assign a session ID though page is simple static HTML page
HttpSession
Servlet provides HttpSession Interface which provides a way to identify a user across more than one page request or visit to
a Web site and to store information about that user. The servlet container uses this interface to create a session between an
HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page
request from the user.
Example
You would get HttpSession object by calling the public method getSession() of HttpServletRequest, as below:
Here we will develop a simple web application that demonstrates the session handling.
And, here is the structure of your dynamic web project created in Eclipse. Notice the placement of the above files in the project.
package com.aklc.servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
<html>
<body>
Session Handling DEMO <br/><br/>
<a href='sessionTrack'> Visit my website </a>
</body>
</html>
<servlet>
<servlet-name>SessionTrack</servlet-name>
<servlet-class>com.aklc.servlet.SessionTrackServlet</servlet-class>
</servlet>
<servlet-mapping>
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
<servlet-name>SessionTrack</servlet-name>
<url-pattern>/sessionTrack</url-pattern>
</servlet-mapping>
First time when you click on the link, you see the page shown below.
Refreshing it, meaning visiting it again, you see the below page
JAVA/ J2EE
Notes prepared by
Mr. Ashok Kumar K
9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Unit 7:
7.1 Basics
Servlets are powerful and sometimes they are a bit cumbersome when it comes to generating complex HTML. Most servlets contain a
little code that handles application logic and a lot more code that handles output formatting (presentation logic). This can make it difficult
to separate and reuse portions of the code when a different output format is needed. For these reasons, web application developers
turn towards JSP as their preferred servlet environment.
Below is the snap shot of the servlet program that we have seen in previous chapter. Notice the application logic and presentation logic
are coupled together which is not recommended. In later sections we see how JSP helps in separating the application logic from the
presentation logic.
Defining a JSP
A JSP page is a text based document containing static HTML and dynamic actions which describe how to process a response to the
client in a more powerful and flexible manner. Most of a JSP file is a plain HTML but it also will be interspersed with special JSP tags.
Java Server Pages (JSP) is a server side program that is similar in design and functionality to a java Servlet. A JSP is called by client to
provide a web service, the nature of which depends on the J2EE Application.
Servlet is written using Java programming language and JSP is written in HTML, XML, or in the clients
responses are encoded as an output string object that is format that is interspersed with the scripting
passed to the println() method. The output string object is elements, directives, and actions comprised of
formatted in HTML, XML, or whatever format are required by Java programming language and JSP syntax
the client
Servlets use println statements for printing an HTML document which is usually very difficult to use. JSP has no such
tedious task to maintain.
JSP needs no compilation, CLASSPATH setting and packaging.
In a JSP page visual content and logic are separated, which is not possible in a servlet.
There is automatic deployment of a JSP; recompilation is done automatically when changes are made to JSP pages.
Usually with JSP, Java Beans and custom tags web application is simplified
Reduces Development time
A JSP page is executed in a JSP container (or JSP engine), which is installed in a web server (or an application server). When a client
requests for a JSP page the engine wraps up the request and delivers it to the JSP page along with a response object. The JSP page
processes the request and modifies the response object to incorporate the communication with the client. The container or the engine,
on getting the response, wraps up the responses from the JSP page and delivers it to the client. The underlying layer for a JSP is
actually a servlet implementation. The abstraction of the request and response are the same as the ServletRequest and
ServletResponse respectively. If the protocol used is HTTP, then the corresponding objects are HttpServletRequest and
HttpServletResponse.
The first time when the engine intercepts a request for a JSP, it compiles this translation unit (the JSP page and other dependent files)
into a class file that implements the servlet protocol. If the dependent files are other JSPs they are compiled into their own classes.
Since most JSP pages use HTTP, their implementation classes must actually implement the javax.servlet.jsp.HttpJspPage
interface, which is a sub interface of javax.servlet.jsp.JspPage.
This method is invoked when the JSP is initialized and the page authors are free to provide
initialization of the JSP by implementing this method in their JSPs.
This method is invoked when the JSP is about to be destroyed by the container. Similar to above,
page authors can provide their own implementation.
This method generated by the JSP container, is invoked, every time a request comes to the JSP. The
request is processed and the JSP generates appropriate response. This response is taken by the
container and passed back to the client.
JSP tags define java code that is to be executed before the output of a JSP program is sent to the browser.
There are five types of JSP tags:
1. Comment Tag
2. Declaration statement Tag
3. Directive Tag
4. Expression Tag
5. Scriptlet Tag
Comment Tag
A comment tag opens with <%-- and closes with --%>, and is followed by a comment that usually describes the functionality of
statements that follow the comment tag.
Ex:
<%--
This is a JSP Comment
--%>
A Declaration statement tag opens with <%! and is followed by a Java declaration statements that define variables, objects, and
methods.
Ex:
<%!
int a; String s;
Employee e = new Employee();
%>
Directive Tag
A Directive tag opens with <%@ and closes with %>. There are three commonly used directives.
Import
Used to import java packages into JSP program
Ex: <%@ page import = java.sql.* %>
Include
It inserts a specified file into the JSP program replacing the include tag
Ex: <%@ include file = Keogh\book.html %>
Taglib
It specifies a file that contains a tag library
Ex: <%@ taglib uri = myTags.tld %>
Expression Tag
An expression tag opens with <%= and is used for an expression statement whose result replaces the expression tag. It closes with %>
Ex:
<%! int a = 5, b = 10; %>
<%= a+b %>
Scriptlet Tag
A scriptlet tag opens with <% and contains commonly used java control statements and loops. It closes with %>
JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call
them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.
JSP supports nine Implicit Objects which are listed below:
Object Description
request This is the HttpServletRequest object associated with the
request.
response This is the HttpServletResponse object associated with the
response to the client.
out This is the PrintWriter object used to send output to the
client.
session This is the HttpSession object associated with the request.
application This is the ServletContext object associated with application
context.
config This is the ServletConfig object associated with the page.
pageContext This encapsulates use of server-specific features like higher
performance JspWriters.
page This is simply a synonym for this, and is used to call the
methods defined by the translated servlet class.
Exception The Exception object allows the exception data to be
accessed by designated JSP.
<html>
<body>
<%!
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
int a = 10;
String s = "TEST";
%>
<p>
int value is <%= a %>
String value is <%= s %>
</p>
</body>
</html>
<html>
<body>
<%!
int findSum(int a, int b) {
return a+b;
}
%>
<p>
sum of 2 and 5 is <%=findSum(2,5) %>
</p>
</body>
</html>
<html>
<body>
<%!
int grade = 70;
%>
<html>
<body>
The browser generates a user request string whenever the submit button is selected.
The user request string consists of:
1. URL
2. Query String
Example
Query String
JSP program should parse the query string to extract the values of fields that are to be processed by a JSP. A JSP can parse the query
string in two ways:
a) Using request.getParameter()
getParameter() method requires an argument, which is the name of the field whose value you want to retrieve.
Ex:
<%!
String uname = request.getParameter(username);
String pword = request.getParameter(password);
%>
b) Using request.getParameterValues()
Multi valued fields (such as checkboxes and select menus) can be read using getParameterValues() method.
It returns multiple values from the field specified as an argument to this method.
Ex:
<%!
String[] games = request.getParameterValues(favgames);
%>
Example Program
Here we will develop a sample JSP to read the parameters from the client request.
<html>
<body>
<form action='readParam.jsp'>
Enter your name: <input type='text' name='username' /> <br />
<br /> Select your favourite games : <br/>
<select name='games' multiple=multiple>
<option value='Cricket'>Cricket</option>
<option value='Football'>Football</option>
<option value='Hockey'>Hockey</option>
<option value='Tennis'>Tennis</option>
</select> <br />
<br /> <input type='submit' value='Click me' />
</form>
</body>
</html>
<html>
<body>
<%
String name = request.getParameter("username");
String games[] = request.getParameterValues("games");
%>
Step 3:
Run param.html by entering the direct URL in the browser.
URL
Protocol
It defines the rules that are used to transfer the request string from the browser to JSP program. Three commonly used
protocols are HTTP, HTTPS, and FTP
Host
It is the internet protocol address (IP) or name of the server that contains the JSP program.
Port
It is the port that the host monitors. If the port is not specified, it is defaulted to 80.
Whenever HTTP is used, the host will be monitoring the port 80
Virtual path to JSP program
The server maps this virtual path to the physical path
As mentioned earlier, HTTP is a "stateless" protocol which means each time when a client retrieves a web page, the client opens a
separate connection to the web server and the server does not keep any record of previous client request. The question here is how
can we maintain the session between the client and a server?
As explained in the previous chapter, there are four possible ways to maintain the session between client and a server
Cookies
Hidden fields
URL Rewriting
HttpSession interface (session object)
A hidden field is a field in HTML form whose value isnt displayed on the HTML page. You can assign a value to the hidden field in a
JSP program before the program sends the HTML page to the browser.
Consider a login screen which asks for username and password.
Here is how the session is tracked using hidden field:
Upon submitting the form, the browser sends the username and password to the JSP program.
The JSP program then validates the username and password and generates another dynamic HTML page. This newly
generated HTML page has a form that contains hidden field which is assigned a userID along with other fields as well.
When the user submits the form in the new HTML page, the userID stored in the hidden field and other information on the form
are sent to the JSP program.
This cycle continues where the JSP program processing the request string receives the userID as a parameter and then
passes the userID to the next dynamically built HTML page as a hidden field.
In this way, each HTML page and subsequent JSP program has access to userID and therefore can track the session.
7.7.2 Cookies
A cookie is a small piece of information created by a JSP program that is stored in the clients hard disk by the browser. Cookies are
used to store various kind of information such as username, password, and user preferences, etc.
<html>
<body>
<%!
String cName = "userID";
String cValue = "1VK06IS009";
Cookie myCookie = new Cookie (cName, cValue);
<html>
<body>
<%!
String cName = "userID";
String name;
String value;
int found = 0;
%>
<%
Cookie[] myCookies = request.getCookies();
for (int i=0;i<myCookies.length;i++) {
name = myCookies[i].getName();
if (name.equals(cName)) {
value = myCookies[i].getValue();
found = 1;
}
}
if (found==1) { %>
<p> Cookie Name: <%= cName %> </p>
<p> Cookie Value: <%= value %> </p>
<% } else { %>
<p> Cookie NOT FOUND </p>
<%>} %>
</body>
</html>
A JSP database system is able to share information among JSP programs within a session by using a session object. Each time a
session is created, a unique ID is assigned to the session and stored as a cookie. The unique ID enables JSP programs to track
multiple sessions simultaneously while maintaining data integrity of each session. In addition to session ID, a session object is also
used to store other types of information called attributes.
<html>
<body>
<%!
String attName = "userID";
String attValue = "1VK06IS009";
%>
<%
session.setAttribute(attName, attValue);
%>
</body>
</html>
<html>
<body>
<%!
Enumeration<String> e;
%>
<%
e = session.getAttributeNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
String value = (String) session.getAttribute(name);
%>
<p> Attribute name : <%= name %></p>
<p> Attribute value : <%= value %></p>
<%
}
%>
</body>
</html>
A Java object runs within a JVM. Likewise, a J2EE application runs within JVM; however, objects used by a J2EE application do not
need to run on the same JVM as the J2EE application. This is because a J2EE application and its components can invoke objects
located on different JVM by using Java RMI system.
RMI is used for remote communication between Java applications and components, both of which must be written in Java
Programming language.
RMI handles transmission of requests and provides the facility to load the objects bytecode, which is referred to as dynamic code
loading
When client references a remote object, the RMI passes a remote stub for the remote object. The remote stub is the local proxy for the
remote object. The client calls the method on the local stub whenever the client wants to invoke one of the remote objects methods.
There are three steps necessary to make an object available to remote clients
1. Design an object
2. Compile the object
Designing an object
Besides defining the business logic of an object, the developer must define a remote interface for the object, which identifies methods
that are available to remote clients.
In addition to methods that can be invoked by remote clients, the developer must also define other methods that support the processing
of client invoked methods. There are referred as server methods, while methods invoked by a client are called client methods.
It is done by loading the object into a server. Make sure the RMI remote object registry is running. If not, type the following at the
command line:
C:\> start rmiregistry
Server side of RMI consists of a remote interfaces and methods. Remote interfaces provide the API for clients to access the methods.
Methods provide the business logic that fulfills a clients request whenever the client remotely invokes them.
HelloInterface.java
import java.rmi.*;
public interface HelloInterface extends Remote {
public String say() throws RemoteException;
}
Hello.java
import java.rmi.*;
import java.rmi.server.*;
Below program in the server side makes the Remote object available to the clients by binding it to the naming registry.
HelloServer.java
import java.rmi.Naming;
Clients can access the remote object by looking up the naming registry for the appropriate entry.
Below example shows how a client can lookup the naming registry to get an instance of the remote object. It also illustrates how a client
can use the remote object to call its methods.
HelloClient.java
import java.rmi.Naming;
JAVA/ J2EE
Notes prepared by
Mr. Ashok Kumar K
9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Unit 8:
An Enterprise Java Bean (EJB) is a component of the J2EE architecture that primarily provides business logic
to a J2EE application and interacts with other server side J2EE components. The nature of business logic and
the interaction with the other server side J2EE components are dependent on the J2EE application.
EJB provides an architecture to develop and deploy component based enterprise applications considering
robustness, high scalability and high performance. An EJB application can be deployed on any of the
application server compliant with J2EE 1.3 standard specification..
Advantages of EJB
Types of EJBs
Session Bean
Session bean contains business logic used to provide a service to a client and exists for the
duration of the client server session. A session bean terminates once the session with their
client server terminates.
Entity Bean
Entity beans represent persistent data storage. User data can be saved to database via
entity beans and later on can be retrieved from the database in the entity bean.
EJB container is a vendor provided entity located on the EJB server that manages system level services for
EJB. EJB container is one of the several containers, each of which handles a J2EE component such as JSP or
servlets.
A clients request for web services is made to a web server, which forwards the clients request to the
appropriate server. Typically either the JSP or Servlet receives the client request and uses JNDI to look up the
EJB resource. The EJB object is returned and is used to get the EJBs home or local class. The home class is
used to reference the bean class through the EJBs remote class.
Deployment descriptor describes how EJBs are managed at runtime and enables the customization of EJB behavior
without modification to the EJB code such as describing runtime attributes of transactional context. The behavior of an
EJB can be modified within the deployment descriptor without having to modify the EJB class or the EJB interface.
A deployment descriptor is written in a file using XML syntax. Many times an IDE (Integrated Development Environment)
like Eclipse will automatically generates the deployment descriptor. The deployment descriptor file is packaged in the Java
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Archive (JAR) file along with other files that are required to deploy EJB. An EJB container references the deployment
descriptor file to understand how to deploy and manage EJBs contained in the package.
<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>myEJB</ejb-name>
<home>com.aklc.ejb.MyEJBHome</home>
<remote>com.aklc.ejb.MyEJBRemote</remote>
<ejb-class>com.aklc.ejb.MyEJB</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<reentrant>False</reentrant>
</entity>
</enterprise-beans>
</ejb-jar>
<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>myEJB</ejb-name>
<home>com.aklc.ejb.MyEJBHome</home>
<remote>com.aklc.ejb.MyEJBRemote</remote>
<local-home>com.aklc.ejb.MyEJBHomeLocal</local-home>
<local>com.aklc.ejb.MyEJBLocal</local>
<ejb-class>com.aklc.ejb.MyEJB</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<reentrant>False</reentrant>
</entity>
</enterprise-beans>
</ejb-jar>
Element Description
<!DOCTYPE> Defines the URL for the DTD and the organization that defines
the DTD
<enterprise-bean> Describes one or more EJB contained within a JAR file
<entity> Describes the type of EJB as entity bean
<session> Describes the type of EJB as session bean
<message-driven> Describes the type of EJB as message driven bean
The <env-entry> element is used in the deployment descriptor to define values that an EJB can use to customize the
EJBs behavior
<env-entry>
<env-entry-name>PassingGrade</env-entry-name>
<env-entry-type>java.lang.Integer</env-entry-type>
<env-entry-value>35</env-entry-value>
</env-entry>
Security elements
<security-role-ref>
<description>myEJB security role</description>
<role-name>Supervisor</role-name>
</security-role-ref>
Transaction elements
A transaction is a single unit of work items which follows the ACID properties. ACID stands for Atomic, Consistent,
Isolated and Durable.
Atomic: If any of work items fails, the complete unit is considered failed. Success meant all items executes
successfully.
Consistent: A transaction must keep the system in consistent state.
Isolated: Each transaction executes independent of any other transaction.
Durable: Transaction should survive system failure if it has been executed or committed.
EJB Container/Servers are transaction servers and handles transactions context propagation and distributed transactions.
Transactions can be managed by the container or by custom code handling in bean's code.
Container Managed Transactions: In this type, container manages the transaction states.
Bean Managed Transactions: In this type, developer manages the life cycle of transaction states.
REQUIRED
Indicates that business method has to be executed within transaction otherwise a new transaction will be started
for that method.
REQUIRES_NEW
Indicates that a new transaction is to be started for the business method.
SUPPORTS:
Indicates that business method will execute as part of transaction.
NOT_SUPPORTED:
Indicates that business method should not be executed as part of transaction.
MANDATORY:
Indicates that business method will execute as part of transaction otherwise exception will be thrown.
NEVER:
Indicates if business method executes as part of transaction then an exception will be thrown.
A session bean contains business logic used to provide a service to a client and exists for the duration of the client server
session. A session bean terminates once the session with the client server terminates. A session bean is not persistent.
(That is, its data is not saved to a database)
A stateful session bean retains the state (data) between the method calls with a client during a session.
Because the client interacts (talks) with its bean, this state is often called the conversational state. As
its name suggests, a session bean is similar to an interactive session. A session bean is not shared; it
can have only one client, in the same way that an interactive session can have only one user. When the
client terminates, its session bean appears to terminate and is no longer associated with the client. The
state is retained for the duration of the client/bean session. If the client removes the bean, the session
ends and the state disappear. This transient nature of the state is not a problem, however, because
when the conversation between the client and the bean ends, there is no need to retain the state.
A stateless session bean does not retain the state between method calls and typically performs
business logic that doesnt require data to be maintained during the session.
When a client invokes the methods of a stateless bean, the beans instance variables may contain a
state specific to that client but only for the duration of the invocation. When the method is finished, the
client-specific state should not be retained. Clients may, however, change the state of instance
variables in pooled stateless beans, and this state is held over to the next invocation of the pooled
stateless bean. Except during method invocation, all instances of a stateless bean are equivalent,
allowing the EJB container to assign an instance to any client. That is, the state of a stateless session
bean should apply across all clients. Because they can support multiple clients, stateless session
beans can offer better scalability for applications that require large numbers of clients. Typically, an
application requires fewer stateless session beans than stateful session beans to support the same
number of clients. A stateless session bean can implement a web service, but a stateful session bean
cannot.
Retains state between the method calls Does not retain state between the method
calls
Cannot be shared between clients Can be shared between clients
Its life time is controlled by clients Its life time is controlled by the container
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.ejb.EJBException;
import java.rmi.RemoteException;
Entity bean is used to manage a collection of data retrieved from a database and stored in memory. An entity bean
inserts, updates, and removes data while maintaining the integrity of the data.
Data collected and managed by an entity bean is referred to as persistent data and is managed in one of the two ways
Container managed persistence
Bean managed persistence
A container managed persistence (CMP) bean requires the container to manage the persistence. A CMP entity is heavily
dependent on support from the EJB container. The EJB container synchronizes the state of the entity bean with the
database. However, EJB container support varies by vendor. Most vendors support automatic persistence between the
entity bean and a relational database.
}
public Product getProduct() {
return myProduct;
}
public void setProduct(Product prod) {
myProduct = prod;
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
}
public void setEntityContext(EntityContext cntx) {
}
public void unsetEntityContext() {
}
public void ejbLoad() {
}
public void ejbStore() {
}
public void ejbActivate() {
}
public void ejbPassivate() {
}
public void ejbRemove() {
}
}
The product object definition
import java.io.Serializable;
Home interface
Remote Interface
A bean managed persistence (CMP) bean requires a bean to manage the persistence. A BMP bean uses the JDBC API
or another appropriate database API to interface with the database. However, these interactions take place under the
direction of the EJB container. That is, the EJB container tells the BMP bean when to insert a new record, retrieve data,
modify data, or delete data.
A message driven bean is designed for clients to invoke server side business logic using asynchronous communication,
which is a special case of a stateless session bean.
Skeleton of a MDB
}
public void ejbCreate() {
}
public void ejbRemove() {
}
public void onMessage(Message clientMessage) {
}
}
The onMessage() method is where the MDB processes messages received indirectly from a client.
Concept
EJB classes and related files are packaged together into a Java Archive (JAR) file for deployment. The JAR file is a
compressed file format that was originally designed to reduce the size of software so it could be easily be transported.
The JAR file used to package an EJB must contain the following; however it is customary to keep the dependent classes
and interfaces in different JAR files.
EJB classes
Dependent classes
Remote interface
Home interface
Dependent interface
Primary key class
Deployment descriptor
You can use the JAR utility by entering jar cf followed by name of the JAR file, and then followed by the path and names
of files that will be archived.