0% found this document useful (0 votes)
12 views60 pages

Attachment

The document outlines a course on Java programming, covering topics such as array and collection processing, event-driven programming, inheritance, encapsulation, polymorphism, Java Servlets, JSP, and database access with JDBC. It provides detailed explanations of Java arrays, including single and multidimensional arrays, their declaration, instantiation, initialization, and methods for passing and returning arrays. Additionally, it discusses matrix operations and event-driven programming concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views60 pages

Attachment

The document outlines a course on Java programming, covering topics such as array and collection processing, event-driven programming, inheritance, encapsulation, polymorphism, Java Servlets, JSP, and database access with JDBC. It provides detailed explanations of Java arrays, including single and multidimensional arrays, their declaration, instantiation, initialization, and methods for passing and returning arrays. Additionally, it discusses matrix operations and event-driven programming concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 60

LECTURE NOTES ON COM 211-Programming Language

using Java 2

Course Outline

1.0 Understand Array and collection Processing in Java.

2.0 Understand Event driven programs.

3.0 Know the concept of inheritance, encapsulation and Polymorphism

4.0 Know how to use Java Servlet, and Java Server Pages (JSP)

5.0 Understand Database Access with JDBC

6.0 Understand the process of general enterprise solution using Java

Java Arrays

Normally, an array is a collection of similar type of elements which has


contiguous memory location. Java array is an object which contains
elements of a similar data type. Additionally, the elements of an array are
stored in a contiguous memory location. It is a data structure where we store
similar elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the
0th index, 2nd element is stored on 1st index and so on. Unlike C/C++, we
can get the length of the array using the length member. In C/C++, we need
to use the sizeof operator.

In Java, array is an object of a dynamically generated class. Java array


inherits the Object class, and implements the Serializable as well as
Cloneable interfaces. We can store primitive values or objects in an array in
Java. Like C/C++, we can also create single dimentional or multidimentional
arrays in Java. Moreover, Java provides the feature of anonymous arrays
which is not available in C/C++.
Advantages

o Code Optimization: It makes the code optimized, we can retrieve or


sort the data efficiently.
o Random access: We can get any data located at an index position.

Disadvantages

o Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.

Types of Array in java

There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single Dimensional Array in Java

Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in Java

1. arrayRefVar=new datatype[size];

Example of Java Array

Let's see the simple example of java array, where we are going to declare,
instantiate, initialize and traverse an array.
1. //Java Program to illustrate how to declare, instantiate, initialize
2. //and traverse the Java array.
3. class Testarray{
4. public static void main(String args[]){
5. int a[]=new int[5];//declaration and instantiation
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
9. a[3]=40;
10. a[4]=50;
11. //traversing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14. }}
Test it Now

Output:

10
20
70
40
50

Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

1. int a[]={33,3,4,5};//declaration, instantiation and initialization

Let's see the simple example to print this array.

1. //Java Program to illustrate the use of declaration, instantiation


2. //and initialization of Java array in a single line
3. class Testarray1{
4. public static void main(String args[]){
5. int a[]={33,3,4,5};//declaration, instantiation and initialization
6. //printing array
7. for(int i=0;i<a.length;i++)//length is the property of array
8. System.out.println(a[i]);
9. }}
Test it Now

Output:

33
3
4
5

For-each Loop for Java Array

We can also print the Java array using for-each loop. The Java for-each loop
prints the array elements one by one. It holds an array element in a variable,
then executes the body of the loop.

The syntax of the for-each loop is given below:

1. for(data_type variable:array){
2. //body of the loop
3. }
Let us see the example of print the elements of Java array using the for-each
loop.

1. //Java Program to print the array elements using for-each loop


2. class Testarray1{
3. public static void main(String args[]){
4. int arr[]={33,3,4,5};
5. //printing array using for-each loop
6. for(int i:arr)
7. System.out.println(i);
8. }}

Output:
33
3
4
5

Passing Array to a Method in Java

We can pass the java array to method so that we can reuse the same logic
on any array.

Let's see the simple example to get the minimum number of an array using a
method.

1. //Java Program to demonstrate the way of passing an array


2. //to method.
3. class Testarray2{
4. //creating a method which receives an array as a parameter
5. static void min(int arr[]){
6. int min=arr[0];
7. for(int i=1;i<arr.length;i++)
8. if(min>arr[i])
9. min=arr[i];
10.
11. System.out.println(min);
12. }
13.
14. public static void main(String args[]){
15. int a[]={33,3,4,5};//declaring and initializing an array
16. min(a);//passing array to method
17. }}
Test it Now

Output:

Anonymous Array in Java


Java supports the feature of an anonymous array, so you don't need to
declare the array while passing an array to the method.

1. //Java Program to demonstrate the way of passing an anonymous array


2. //to method.
3. public class TestAnonymousArray{
4. //creating a method which receives an array as a parameter
5. static void printArray(int arr[]){
6. for(int i=0;i<arr.length;i++)
7. System.out.println(arr[i]);
8. }
9.
10. public static void main(String args[]){
11. printArray(new int[]{10,22,44,66});//passing anonymous array to met
hod
12. }}
Test it Now
Output:
10
22
44
66

Returning Array from the Method

We can also return an array from the method in Java.

1. //Java Program to return an array from the method


2. class TestReturnArray{
3. //creating method which returns an array
4. static int[] get(){
5. return new int[]{10,30,50,90,60};
6. }
7.
8. public static void main(String args[]){
9. //calling method which returns an array
10. int arr[]=get();
11. //printing the values of an array
12. for(int i=0;i<arr.length;i++)
13. System.out.println(arr[i]);
14. }}
Test it Now

Output:

10
30
50
90
60

Multidimensional Array in Java

In such case, data is stored in row and column based index (also known as
matrix form).

Syntax to Declare Multidimensional Array in Java

1. dataType[][] arrayRefVar; (or)


2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java

1. int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in Java

1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;

Example of Multidimensional Java Array

Let's see the simple example to declare, instantiate, initialize and print the
2Dimensional array.

1. //Java Program to illustrate the use of multidimensional array


2. class Testarray3{
3. public static void main(String args[]){
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6. //printing 2D array
7. for(int i=0;i<3;i++){
8. for(int j=0;j<3;j++){
9. System.out.print(arr[i][j]+" ");
10. }
11. System.out.println();
12. }
13. }}
Test it Now

Output:

123
245
445

Jagged Array in Java

If we are creating odd number of columns in a 2D array, it is known as a


jagged array. In other words, it is an array of arrays with different number of
columns.

1. //Java Program to illustrate the jagged array


2. class TestJaggedArray{
3. public static void main(String[] args){
4. //declaring a 2D array with odd columns
5. int arr[][] = new int[3][];
6. arr[0] = new int[3];
7. arr[1] = new int[4];
8. arr[2] = new int[2];
9. //initializing a jagged array
10. int count = 0;
11. for (int i=0; i<arr.length; i++)
12. for(int j=0; j<arr[i].length; j++)
13. arr[i][j] = count++;
14.
15. //printing the data of a jagged array
16. for (int i=0; i<arr.length; i++){
17. for (int j=0; j<arr[i].length; j++){
18. System.out.print(arr[i][j]+" ");
19. }
20. System.out.println();//new line
21. }
22. }
23. }
Test it Now
Output:
012
3456
78

What is the class name of Java array?

In Java, an array is an object. For array object, a proxy class is created whose
name can be obtained by getClass().getName() method on the object.

1. //Java Program to get the class name of array in Java


2. class Testarray4{
3. public static void main(String args[]){
4. //declaration and initialization of array
5. int arr[]={4,4,5};
6. //getting the class name of Java array
7. Class c=arr.getClass();
8. String name=c.getName();
9. //printing the class name of Java array
10. System.out.println(name);
11.
12. }}
Test it Now

Output:

Copying a Java Array

We can copy an array to another by the arraycopy() method of System class.

Syntax of arraycopy method

1. public static void arraycopy(


2. Object src, int srcPos,Object dest, int destPos, int length
3. )

Example of Copying an Array in Java

1. //Java Program to copy a source array into a destination array in Java


2. class TestArrayCopyDemo {
3. public static void main(String[] args) {
4. //declaring a source array
5. char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
6. 'i', 'n', 'a', 't', 'e', 'd' };
7. //declaring a destination array
8. char[] copyTo = new char[7];
9. //copying array using System.arraycopy() method
10. System.arraycopy(copyFrom, 2, copyTo, 0, 7);
11. //printing the destination array
12. System.out.println(String.valueOf(copyTo));
13. }
14. }
Test it Now

Output:

caffein

Cloning an Array in Java

Since, Java array implements the Cloneable interface, we can create the
clone of the Java array. If we create the clone of a single-dimensional array,
it creates the deep copy of the Java array. It means, it will copy the actual
value. But, if we create the clone of a multidimensional array, it creates the
shallow copy of the Java array which means it copies the references.

1. //Java Program to clone the array


2. class Testarray1{
3. public static void main(String args[]){
4. int arr[]={33,3,4,5};
5. System.out.println("Printing original array:");
6. for(int i:arr)
7. System.out.println(i);
8.
9. System.out.println("Printing clone of the array:");
10. int carr[]=arr.clone();
11. for(int i:carr)
12. System.out.println(i);
13.
14. System.out.println("Are both equal?");
15. System.out.println(arr==carr);
16.
17. }}
Output:

Printing original array:


33
3
4
5
Printing clone of the array:
33
3
4
5
Are both equal?
false

Addition of 2 Matrices in Java

Let's see a simple example that adds two matrices.

1. //Java Program to demonstrate the addition of two matrices in Java


2. class Testarray5{
3. public static void main(String args[]){
4. //creating two matrices
5. int a[][]={{1,3,4},{3,4,5}};
6. int b[][]={{1,3,4},{3,4,5}};
7.
8. //creating another matrix to store the sum of two matrices
9. int c[][]=new int[2][3];
10.
11. //adding and printing addition of 2 matrices
12. for(int i=0;i<2;i++){
13. for(int j=0;j<3;j++){
14. c[i][j]=a[i][j]+b[i][j];
15. System.out.print(c[i][j]+" ");
16. }
17. System.out.println();//new line
18. }
19.
20. }}
Test it Now

Output:

268
6 8 10

Multiplication of 2 Matrices in Java

In the case of matrix multiplication, a one-row element of the first matrix is


multiplied by all the columns of the second matrix which can be understood
by the image given below.

Let's see a simple example to multiply two matrices of 3 rows and 3


columns.

1. //Java Program to multiply two matrices


2. public class MatrixMultiplicationExample{
3. public static void main(String args[]){
4. //creating two matrices
5. int a[][]={{1,1,1},{2,2,2},{3,3,3}};
6. int b[][]={{1,1,1},{2,2,2},{3,3,3}};
7.
8. //creating another matrix to store the multiplication of two matrices
9. int c[][]=new int[3][3]; //3 rows and 3 columns
10.
11. //multiplying and printing multiplication of 2 matrices
12. for(int i=0;i<3;i++){
13. for(int j=0;j<3;j++){
14. c[i][j]=0;
15. for(int k=0;k<3;k++)
16. {
17. c[i][j]+=a[i][k]*b[k][j];
18. }//end of k loop
19. System.out.print(c[i][j]+" "); //printing matrix element
20. }//end of j loop
21. System.out.println();//new line
22. }
23. }}
Test it Now

Output:

666
12 12 12
18 18 18

Event-driven programming is a paradigm where the execution of a


program is determined by events such as user actions or messages.
Programs respond to events with predefined actions, allowing for
asynchronous and responsive behavior, often seen in GUI applications and
distributed systems.
Advantages of Event-Driven Programming Paradigm
 Enables asynchronous processing, optimizing resource utilization and
responsiveness, crucial for real-time applications and user interfaces.
 Encourages modular code design, simplifying maintenance and
scalability by separating concerns and promoting code reusability.
 Enhances user experience by responding promptly to user inputs,
delivering a smoother and more interactive interface.
 Facilitates easier integration of new features or modifications,
promoting adaptability to changing requirements in dynamic
environments.
 Components communicate through events, reducing dependencies and
enhancing system flexibility, making it easier to maintain and modify.
Disadvantages of Event-Driven Programming Paradigm
 Event-driven systems can be challenging to debug due to their
asynchronous nature, making it harder to trace errors.
 Concurrent events may introduce race conditions, leading to
unpredictable behavior and making debugging and synchronization
complex.
 Event-driven systems may lead to inversion of control, making code
harder to follow and understand for developers unfamiliar with the
design.
 A series of interconnected events can lead to cascading effects,
making it harder to predict the outcome and manage the system state.
 Continuous listening for events can consume system resources,
leading to potential inefficiencies in resource utilization and impacting
overall system performance.

Java Inheritance

In Java programming, the inheritance is an important of concept of Java


OOPs. Inheritance is a process where one class acquires the properties
(methods and attributes) of another. With the use of inheritance, the
information is made manageable in a hierarchical order.

The class which inherits the properties of other is known as subclass (derived
class, child class) and the class whose properties are inherited is known as
superclass (base class, parent class).

Need of Java Inheritance

 Code Reusability: The basic need of an inheritance is to reuse the


features. If you have defined some functionality once, by using the
inheritance you can easily use them in other classes and packages.
 Extensibility: The inheritance helps to extend the functionalities of a
class. If you have a base class with some functionalities, you can
extend them by using the inheritance in the derived class.
 Implantation of Method Overriding: Inheritance is required to
achieve one of the concepts of Polymorphism which is Method
overriding.
 Achieving Abstraction: Another concept of OOPs that is abstraction
also needs inheritance.

Implementation of Java Inheritance

To implement (use) inheritance in Java, the extends keyword is used. It


inherits the properties (attributes or/and methods) of the base class to the
derived class. The word "extends" means to extend functionalities i.e., the
extensibility of the features.

Syntax to implement inheritance

Consider the below syntax to implement (use) inheritance in Java:

class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}

Java Inheritance Example

Following is an example demonstrating Java inheritance. In this example, you


can observe two classes namely Calculation and My_Calculation.

Using extends keyword, the My_Calculation inherits the methods addition()


and Subtraction() of Calculation class.

Copy and paste the following program in a file with name


My_Calculation.java

Java Program to Implement Inheritance

class Calculation {
int z;

public void addition(int x, int y) {


z = x + y;
System.out.println("The sum of the given numbers:"+z);
}

public void Subtraction(int x, int y) {


z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}

public class My_Calculation extends Calculation {


public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}

public static void main(String args[]) {


int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}

Compile and execute the above code as shown below.

javac My_Calculation.java
java My_Calculation

After executing the program, it will produce the following result −

Output

The sum of the given numbers:30


The difference between the given numbers:10
The product of the given numbers:200

In the given program, when an object to My_Calculation class is created, a


copy of the contents of the superclass is made within it. That is why, using
the object of the subclass you can access the members of a superclass.
The Superclass reference variable can hold the subclass object, but using
that variable you can access only the members of the superclass, so to
access the members of both classes it is recommended to always create
reference variable to the subclass.

If you consider the above program, you can instantiate the class as given
below. But using the superclass reference variable ( cal in this case) you
cannot call the method multiplication(), which belongs to the subclass
My_Calculation.

Calculation demo = new My_Calculation();


demo.addition(a, b);
demo.Subtraction(a, b);

Note − A subclass inherits all the 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.

Java Inheritance: The super Keyword

The super keyword is similar to this keyword. Following are the scenarios
where the super keyword is used.

 It is used to differentiate the members of superclass from the


members of subclass, if they have same names.
 It is used to invoke the superclass constructor from subclass.

Differentiating the Members

If a class is inheriting the properties of another class. And if the members of


the superclass have the names same as the sub class, to differentiate these
variables we use super keyword as shown below.
super.variable
super.method();

Sample Code

This section provides you a program that demonstrates the usage of


the super keyword.

In the given program, you have two classes


namely Sub_class and Super_class, both have a method named display()
with different implementations, and a variable named num with different
values. We are invoking display() method of both classes and printing the
value of the variable num of both classes. Here you can observe that we
have used super keyword to differentiate the members of superclass from
subclass.

Copy and paste the program in a file with name Sub_class.java.

Example

class Super_class {
int num = 20;

// display method of superclass


public void display() {
System.out.println("This is the display method of superclass");
}
}

public class Sub_class extends Super_class {


int num = 10;

// display method of sub class


public void display() {
System.out.println("This is the display method of subclass");
}

public void my_method() {


// Instantiating subclass
Sub_class sub = new Sub_class();

// Invoking the display() method of sub class


sub.display();

// Invoking the display() method of superclass


super.display();

// printing the value of variable num of subclass


System.out.println("value of the variable named num in sub class:"+
sub.num);

// printing the value of variable num of superclass


System.out.println("value of the variable named num in super class:"+
super.num);
}

public static void main(String args[]) {


Sub_class obj = new Sub_class();
obj.my_method();
}
}

Compile and execute the above code using the following syntax.

javac Super_Demo
java Super

On executing the program, you will get the following result −

Output

This is the display method of subclass


This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20
Invoking Superclass Constructor

If a class is inheriting the properties of another class, the subclass


automatically acquires the default constructor of the superclass. But if you
want to call a parameterized constructor of the superclass, you need to use
the super keyword as shown below.

super(values);

Sample Code

The program given in this section demonstrates how to use the super
keyword to invoke the parametrized constructor of the superclass. This
program contains a superclass and a subclass, where the superclass contains
a parameterized constructor which accepts a integer value, and we used the
super keyword to invoke the parameterized constructor of the superclass.

Copy and paste the following program in a file with the name Subclass.java

Example

class Superclass {
int age;

Superclass(int age) {
this.age = age;
}

public void getAge() {


System.out.println("The value of the variable named age in super class
is: " +age);
}
}

public class Subclass extends Superclass {


Subclass(int age) {
super(age);
}

public static void main(String args[]) {


Subclass s = new Subclass(24);
s.getAge();
}
}

Compile and execute the above code using the following syntax.

javac Subclass
java Subclass

Output

The value of the variable named age in super class is: 24

Types of Java Inheritance

In Java, there are mainly three types of inheritances Single, Multilevel,


and Hierarchical. Java does not support Multiple and Hybrid inheritance.
A very important fact to remember is that Java does not support multiple and
hybrid inheritances. This means that a class cannot extend more than one
class. Therefore, following is illegal −

1. Java Single Inheritance

The inheritance in which there is only one base class and one derived class is
known as single inheritance. The single (or, single-level) inheritance inherits
data from only one base class to only one derived class.

Example of Java Single Inheritance

class One {
public void printOne() {
System.out.println("printOne() method of One class.");
}
}
public class Main extends One {
public static void main(String args[]) {
// Creating object of the derived class (Main)
Main obj = new Main();

// Calling method
obj.printOne();
}
}

Output

printOne() method of One class.

2. Java Multilevel Inheritance

The inheritance in which a base class is inherited to a derived class and that
derived class is further inherited to another derived class is known as multi-
level inheritance. Multilevel inheritance involves multiple base classes.

Example of Java Multilevel Inheritance

class One {
public void printOne() {
System.out.println("printOne() method of One class.");
}
}

class Two extends One {


public void printTwo() {
System.out.println("printTwo() method of Two class.");
}
}

public class Main extends Two {


public static void main(String args[]) {
// Creating object of the derived class (Main)
Main obj = new Main();

// Calling methods
obj.printOne();
obj.printTwo();
}
}

Output

printOne() method of One class.


printTwo() method of Two class.

Java Encapsulation

Encapsulation is one of the four fundamental OOP concepts. The other


three are inheritance, polymorphism, and abstraction.

Encapsulation in Java is a mechanism of wrapping the data (variables) and


code acting on the data (methods) together as a single unit. In
encapsulation, the variables of a class will be hidden from other classes, and
can be accessed only through the methods of their current class. Therefore,
it is also known as data hiding.

Achieving Encapsulation in Java

To achieve encapsulation in Java −

 Declare the variables of a class as private.


 Provide public setter and getter methods to modify and view the
variables values.

Java Encapsulation Example

Following is an example that demonstrates how to achieve Encapsulation in


Java −

/* File name : EncapTest.java */


public class EncapTest {
private String name;
private String idNum;
private int age;

public int getAge() {


return age;
}

public String getName() {


return name;
}

public String getIdNum() {


return idNum;
}

public void setAge( int newAge) {


age = newAge;
}

public void setName(String newName) {


name = newName;
}

public void setIdNum( String newId) {


idNum = newId;
}
}

The public setXXX() and getXXX() methods are the access points of the
instance variables of the EncapTest class. Normally, these methods are
referred as getters and setters. Therefore, any class that wants to access the
variables should access them through these getters and setters.

The variables of the EncapTest class can be accessed using the following
program −

/* File name : RunEncap.java */


public class RunEncap {
public static void main(String args[]) {
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");

System.out.print("Name : " + encap.getName() + " Age : " +


encap.getAge());
}
}

public class EncapTest {


private String name;
private String idNum;
private int age;

public int getAge() {


return age;
}

public String getName() {


return name;
}

public String getIdNum() {


return idNum;
}

public void setAge( int newAge) {


age = newAge;
}

public void setName(String newName) {


name = newName;
}
public void setIdNum( String newId) {
idNum = newId;
}
}

Output

Name : James Age : 20

Benefits of Encapsulation

 The fields of a class can be made read-only or write-only.


 A class can have total control over what is stored in its fields.

Java Encapsulation: Read-Only Class

A read-only class can have only getter methods to get the values of the
attributes, there should not be any setter method.

Example: Creating Read-Only Class

In this example, we defined a class Person with two getter


methods getName() and getAge(). These methods can be used to get the
values of attributes declared as private in the class.

// Class "Person"
class Person {
private String name = "Robert";
private int age = 21;

// Getter methods
public String getName() {
return this.name;
}

public int getAge() {


return this.age;
}
}
public class Main {
public static void main(String args[]) {
// Object to Person class
Person per = new Person();

// Getting and printing the values


System.out.println("Name of the person is: " + per.getName());
System.out.println("Age of the person is: " + per.getAge());
}
}

Output

Name of the person is: Robert


Age of the person is: 21

Polymorphism in Java

Polymorphism is the ability of an object to take on many forms.


Polymorphism is an important feature of Java OOPs concept and it allows us
to perform multiple operations by using the single name of any method
(interface). Any Java object that can pass more than one IS-A test is
considered to be polymorphic. In Java, all Java objects are polymorphic since
any object will pass the IS-A test for its own type and for the class Object.

Use of Polymorphism in Java

The most common use of polymorphism in OOP occurs when a parent class
reference is used to refer to a child class object.

It is important to know that the only possible way to access an object is


through a reference variable. A reference variable can be of only one type.
Once declared, the type of a reference variable cannot be changed.

The reference variable can be reassigned to other objects provided that it is


not declared final. The type of the reference variable would determine the
methods that it can invoke on the object.
A reference variable can refer to any object of its declared type or any
subtype of its declared type. A reference variable can be declared as a class
or interface type.

Java Polymorphism Example

Let us look at an example.

public interface Vegetarian{}


public class Animal{}
public class Deer extends Animal implements Vegetarian{}

Now, the Deer class is considered to be polymorphic since this has multiple
inheritance. Following are true for the above examples −

 A Deer IS-A Animal


 A Deer IS-A Vegetarian
 A Deer IS-A Deer
 A Deer IS-A Object

When we apply the reference variable facts to a Deer object reference, the
following declarations are legal −

Deer d = new Deer();


Animal a = d;
Vegetarian v = d;
Object o = d;

All the reference variables d, a, v, o refer to the same Deer object in the
heap.

Java Polymorphism Implementation

In this example, we're showcasing the above concept by creating the object
of a Deer and assigning the same to the references of superclasses or
implemented interface.

interface Vegetarian{}
class Animal{}
public class Deer extends Animal implements Vegetarian{
public static void main(String[] args) {
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;

System.out.println(d instanceof Deer);


System.out.println(a instanceof Deer);
System.out.println(v instanceof Deer);
System.out.println(o instanceof Deer);
}
}

Output

true
true
true
true

Types of Java Polymorphism

There are two types of polymorphism in Java:

1. Compile Time Polymorphism


2. Run Time Polymorphism

Compile Time Polymorphism in Java

Compile-time polymorphism is also known as static polymorphism and it is


implemented by method overloading.

Run Time Polymorphism in Java

Run time polymorphism is also known as dynamic method dispatch and it is


implemented by the method overriding.

What Is an Exception in Java?

An exception (or exceptional event) is a problem that arises during the


execution of a program. When an Exception occurs the normal flow of the
program is disrupted and the program/Application terminates abnormally,
which is not recommended, therefore, these exceptions are to be handled.
Why Exception Occurs?

An exception can occur for many different reasons. Following are some
scenarios where an exception occurs.

 A user has entered an invalid data.


 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications
or the JVM has run out of memory.

Some of these exceptions are caused by user error, others by programmer


error, and others by physical resources that have failed in some manner.

Java Exception Categories

Based on these, we have the following categories of Exceptions. You need to


understand them to know how exception handling works in Java.

 Checked exceptions
 Unchecked exceptions
 Errors

Java Checked Exceptions

A checked exception is an exception that is checked (notified) by the


compiler at compilation-time, these are also called as compile time
exceptions. These exceptions cannot simply be ignored, the programmer
should take care of (handle) these exceptions.

Java Unchecked Exceptions

An unchecked exception is an exception that occurs at the time of execution.


These are also called as Runtime Exceptions. These include programming
bugs, such as logic errors or improper use of an API. Runtime exceptions are
ignored at the time of compilation.

Java Errors

These are not exceptions at all, but problems that arise beyond the control of
the user or the programmer. Errors are typically ignored in your code
because you can rarely do anything about an error. For example, if a stack
overflow occurs, an error will arise. They are also ignored at the time of
compilation.

Note the following −


 A catch clause cannot exist without a try statement.
 It is not compulsory to have finally clauses whenever a try/catch block
is present.
 The try block cannot be present without either catch clause or finally
clause.
 Any code cannot be present in between the try, catch, finally blocks.

User-defined Exceptions in Java

You can create your own exceptions in Java. Keep the following points in
mind when writing your own exception classes −

 All exceptions must be a child of Throwable.


 If you want to write a checked exception that is automatically enforced
by the Handle or Declare Rule, you need to extend the Exception class.
 If you want to write a runtime exception, you need to extend the
RuntimeException class.

Syntax

We can define our own Exception class as below −

class MyException extends Exception {


}

You just need to extend the predefined Exception class to create your own
Exception. These are considered to be checked exceptions. The
following InsufficientFundsException class is a user-defined exception
that extends the Exception class, making it a checked exception. An
exception class is like any other class, containing useful fields and methods.

Example: Creating user-defined exception

// File Name InsufficientFundsException.java


import java.io.*;

public class InsufficientFundsException extends Exception {


private double amount;

public InsufficientFundsException(double amount) {


this.amount = amount;
}
public double getAmount() {
return amount;
}
}

To demonstrate using our user-defined exception, the following


CheckingAccount class contains a withdraw() method that throws an
InsufficientFundsException.

// File Name CheckingAccount.java


import java.io.*;

public class CheckingAccount {


private double balance;
private int number;

public CheckingAccount(int number) {


this.number = number;
}

public void deposit(double amount) {


balance += amount;
}

public void withdraw(double amount) throws InsufficientFundsException {


if(amount <= balance) {
balance -= amount;
}else {
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}

public double getBalance() {


return balance;
}
public int getNumber() {
return number;
}
}

The following BankDemo program demonstrates invoking the deposit() and


withdraw() methods of CheckingAccount.

// File Name BankDemo.java


public class BankDemo {

public static void main(String [] args) {


CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);

try {
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
} catch (InsufficientFundsException e) {
System.out.println("Sorry, but you are short $" + e.getAmount());
e.printStackTrace();
}
}
}

Compile all the above three files and run BankDemo. This will produce the
following result −

Output

Depositing $500...

Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)

Common Java Exceptions

In Java, it is possible to define two catergories of Exceptions and Errors.

 JVM Exceptions − These are exceptions/errors that are exclusively or


logically thrown by the JVM. Examples: NullPointerException,
ArrayIndexOutOfBoundsException, ClassCastException.
 Programmatic Exceptions − These exceptions are thrown explicitly
by the application or the API programmers. Examples:
IllegalArgumentException, IllegalStateException.

Java Multithreading

Java is a multi-threaded programming language which means we can


develop multi-threaded program using Java. A multi-threaded program
contains two or more parts that can run concurrently and each part can
handle a different task at the same time making optimal use of the available
resources specially when your computer has multiple CPUs. By definition,
multitasking is when multiple processes share common processing resources
such as a CPU. Multi-threading extends the idea of multitasking into
applications where you can subdivide specific operations within a single
application into individual threads. Each of the threads can run in parallel.
The OS divides processing time not only among different applications, but
also among each thread within an application.

Multi-threading enables you to write in a way where multiple activities can


proceed concurrently in the same program. To achieve the multithreading
(or, write multithreaded code), you need java.lang.Thread class.

Life Cycle of a Thread in Java Multithreading

A thread goes through various stages in its life cycle. For example, a thread
is born, started, runs, and then dies. The following diagram shows the
complete life cycle of a thread.

Following are the stages of the life cycle −


 New − A new thread begins its life cycle in the new state. It remains in
this state until the program starts the thread. It is also referred to as
a born thread.
 Runnable − After a newly born thread is started, the thread becomes
runnable. A thread in this state is considered to be executing its task.
 Waiting − Sometimes, a thread transitions to the waiting state while
the thread waits for another thread to perform a task. A thread
transitions back to the runnable state only when another thread signals
the waiting thread to continue executing.
 Timed Waiting − A runnable thread can enter the timed waiting state
for a specified interval of time. A thread in this state transitions back to
the runnable state when that time interval expires or when the event it
is waiting for occurs.
 Terminated (Dead) − A runnable thread enters the terminated state
when it completes its task or otherwise terminates.

Thread Priorities

Every Java thread has a priority that helps the operating system determine
the order in which threads are scheduled.

Java thread priorities are in the range between MIN_PRIORITY (a constant of


1) and MAX_PRIORITY (a constant of 10). By default, every thread is given
priority NORM_PRIORITY (a constant of 5).

Threads with higher priority are more important to a program and should be
allocated processor time before lower-priority threads. However, thread
priorities cannot guarantee the order in which threads execute and are very
much platform dependent.

Create a Thread by Implementing a Runnable Interface

If your class is intended to be executed as a thread then you can achieve this
by implementing a Runnable interface. You will need to follow three basic
steps −

Step 1: Implement run() Method

As a first step, you need to implement a run() method provided by


a Runnable interface. This method provides an entry point for the thread
and you will put your complete business logic inside this method. Following is
a simple syntax of the run() method −
public void run( )

Step 2: Instantiate a Thread Object

As a second step, you will instantiate a Thread object using the following
constructor −

Thread(Runnable threadObj, String threadName);

Where, threadObj is an instance of a class that implements


the Runnable interface and threadName is the name given to the new
thread.

Step 3: Call Thread using start() Method

Once a Thread object is created, you can start it by calling start() method,
which executes a call to run( ) method. Following is a simple syntax of start()
method −

void start();

Example: Create Thread by Implementing Runnable Interface

Here is an example that creates a new thread and starts running it −

class RunnableDemo implements Runnable {


private Thread t;
private String threadName;

RunnableDemo( String name) {


threadName = name;
System.out.println("Creating " + threadName );
}

public void run() {


System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}

public void start () {


System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}

public class TestThread {

public static void main(String args[]) {


RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();

RunnableDemo R2 = new RunnableDemo( "Thread-2");


R2.start();
}
}

Output

Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

Thread Methods

Following is the list of important methods available in the Thread class.

Sr.N
Method & Description
o.

public void start()


1 Starts the thread in a separate path of execution, then invokes
the run() method on this Thread object.

public void run()


If this Thread object was instantiated using a separate
2
Runnable target, the run() method is invoked on that Runnable
object.

public final void setName(String name)


3 Changes the name of the Thread object. There is also a
getName() method for retrieving the name.

public final void setPriority(int priority)


4 Sets the priority of this Thread object. The possible values are
between 1 and 10.

public final void setDaemon(boolean on)


5
A parameter of true denotes this Thread as a daemon thread.

public final void join(long millisec)


The current thread invokes this method on a second thread,
6
causing the current thread to block until the second thread
terminates or the specified number of milliseconds passes.
public void interrupt()
7 Interrupts this thread, causing it to continue execution if it was
blocked for any reason.

public final boolean isAlive()


8 Returns true if the thread is alive, which is any time after the
thread has been started but before it runs to completion.

Java Networking

Java networking (or, Java network programming) refers to writing


programs that execute across multiple devices (computers), in which the
devices are all connected to each other using a network.

Advantages of Java Networking

 Creating server-client applications


 Implementing networking protocols
 Implement socket programming
 Creating web services

Package Used in Networking

The java.net package of the J2SE APIs contains a collection of classes and
interfaces that provide the low-level communication details, allowing you to
write programs that focus on solving the problem at hand.

The java.net package provides support for the two common network
protocols −

 TCP − TCP stands for Transmission Control Protocol, which allows for
reliable communication between two applications. TCP is typically used
over the Internet Protocol, which is referred to as TCP/IP.
 UDP − UDP stands for User Datagram Protocol, a connection-less
protocol that allows for packets of data to be transmitted between
applications.

This chapter gives a good understanding on the following two subjects −

 Socket Programming − This is the most widely used concept in


Networking and it has been explained in very detail.
 URL Processing − This would be covered separately. Click here to
learn about URL Processing in Java language.

Socket Programming in Java Networking


Sockets provide the communication mechanism between two computers
using TCP. A client program creates a socket on its end of the
communication and attempts to connect that socket to a server.

When the connection is made, the server creates a socket object on its end
of the communication. The client and the server can now communicate by
writing to and reading from the socket.

The java.net.Socket class represents a socket, and the java.net.ServerSocket


class provides a mechanism for the server program to listen for clients and
establish connections with them.

The following steps occur when establishing a TCP connection between two
computers using sockets −

 The server instantiates a ServerSocket object, denoting which port


number communication is to occur on.
 The server invokes the accept() method of the ServerSocket class. This
method waits until a client connects to the server on the given port.
 After the server is waiting, a client instantiates a Socket object,
specifying the server name and the port number to connect to.
 The constructor of the Socket class attempts to connect the client to
the specified server and the port number. If communication is
established, the client now has a Socket object capable of
communicating with the server.
 On the server side, the accept() method returns a reference to a new
socket on the server that is connected to the client's socket.

After the connections are established, communication can occur using I/O
streams. Each socket has both an OutputStream and an InputStream. The
client's OutputStream is connected to the server's InputStream, and the
client's InputStream is connected to the server's OutputStream.

TCP is a two-way communication protocol, hence data can be sent across


both streams at the same time. Following are the useful classes providing
complete set of methods to implement sockets.

ServerSocket Class Constructors

The java.net.ServerSocket class is used by server applications to obtain a


port and listen for client requests.

The ServerSocket class has four constructors −

Sr.N Method & Description


o.

public ServerSocket(int port) throws IOException


Attempts to create a server socket bound to the specified port.
1
An exception occurs if the port is already bound by another
application.

public ServerSocket(int port, int backlog) throws


IOException
2
Similar to the previous constructor, the backlog parameter
specifies how many incoming clients to store in a wait queue.

public ServerSocket(int port, int backlog, InetAddress


address) throws IOException
Similar to the previous constructor, the InetAddress parameter
3 specifies the local IP address to bind to. The InetAddress is
used for servers that may have multiple IP addresses, allowing
the server to specify which of its IP addresses to accept client
requests on.

public ServerSocket() throws IOException


Creates an unbound server socket. When using this
4
constructor, use the bind() method when you are ready to bind
the server socket.

If the ServerSocket constructor does not throw an exception, it means that


your application has successfully bound to the specified port and is ready for
client requests.

ServerSocket Class Methods

Following are some of the common methods of the ServerSocket class −

Sr.N
Method & Description
o.

public int getLocalPort()


Returns the port that the server socket is listening on. This
1
method is useful if you passed in 0 as the port number in a
constructor and let the server find a port for you.

2 public Socket accept() throws IOException


Waits for an incoming client. This method blocks until either a
client connects to the server on the specified port or the
socket times out, assuming that the time-out value has been
set using the setSoTimeout() method. Otherwise, this method
blocks indefinitely.

public void setSoTimeout(int timeout)


3 Sets the time-out value for how long the server socket waits
for a client during the accept().

public void bind(SocketAddress host, int backlog)


Binds the socket to the specified server and port in the
4 SocketAddress object. Use this method if you have
instantiated the ServerSocket using the no-argument
constructor.

When the ServerSocket invokes accept(), the method does not return until a
client connects. After a client does connect, the ServerSocket creates a new
Socket on an unspecified port and returns a reference to this new Socket. A
TCP connection now exists between the client and the server, and
communication can begin.

Socket Class Methods

Some methods of interest in the Socket class are listed here. Notice that
both the client and the server have a Socket object, so these methods can be
invoked by both the client and the server.

Sr.N
Method & Description
o.

public void connect(SocketAddress host, int timeout)


throws IOException
1 This method connects the socket to the specified host. This
method is needed only when you instantiate the Socket using
the no-argument constructor.

public InetAddress getInetAddress()


2 This method returns the address of the other computer that
this socket is connected to.

public int getPort()


3 Returns the port the socket is bound to on the remote
machine.

public int getLocalPort()


4
Returns the port the socket is bound to on the local machine.
public SocketAddress getRemoteSocketAddress()
5
Returns the address of the remote socket.

public InputStream getInputStream() throws


IOException
6
Returns the input stream of the socket. The input stream is
connected to the output stream of the remote socket.

public OutputStream getOutputStream() throws


IOException
7
Returns the output stream of the socket. The output stream is
connected to the input stream of the remote socket.

public void close() throws IOException


8 Closes the socket, which makes this Socket object no longer
capable of connecting again to any server.

Implementing Socket Client in Java

The following GreetingClient is a client program that connects to a server by


using a socket and sends a greeting, and then waits for a response.

Example: Socket Client

// File Name GreetingClient.java


import java.net.*;
import java.io.*;

public class GreetingClient {

public static void main(String [] args) {


String serverName = args[0];
int port = Integer.parseInt(args[1]);
try {
System.out.println("Connecting to " + serverName + " on port " +
port);
Socket client = new Socket(serverName, port);

System.out.println("Just connected to " +


client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);

out.writeUTF("Hello from " + client.getLocalSocketAddress());


InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);

System.out.println("Server says " + in.readUTF());


client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Implementing Socket Server in Java

The following GreetingServer program is an example of a server application


that uses the Socket class to listen for clients on a port number specified by
a command-line argument −

Example: Socket Server

// File Name GreetingServer.java


import java.net.*;
import java.io.*;

public class GreetingServer extends Thread {


private ServerSocket serverSocket;

public GreetingServer(int port) throws IOException {


serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}

public void run() {


while(true) {
try {
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();

System.out.println("Just connected to " +


server.getRemoteSocketAddress());
DataInputStream in = new
DataInputStream(server.getInputStream());

System.out.println(in.readUTF());
DataOutputStream out = new
DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to " +
server.getLocalSocketAddress()
+ "\nGoodbye!");
server.close();

} catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}

public static void main(String [] args) {


int port = Integer.parseInt(args[0]);
try {
Thread t = new GreetingServer(port);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Compile the client and the server and then start the server as follows −

$ java GreetingServer 6066


Waiting for client on port 6066...

Check the client program as follows −

Output

$ java GreetingClient localhost 6066


Connecting to localhost on port 6066
Just connected to localhost/127.0.0.1:6066
Server says Thank you for connecting to /127.0.0.1:6066
Goodbye!

What are Servlets?

Java Servlets are programs that run on a Web or Application server and act
as a middle layer between a requests 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.

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.

 Performance is significantly better.


 Servlets execute within the address space of a Web server. It is not
necessary to create a separate process to handle each client request.
 Servlets are platform-independent because they are written in Java.
 Java security manager on the server enforces a set of restrictions to
protect the resources on a server machine. So servlets are trusted.
 The full functionality of the Java class libraries is available to a servlet.
It can communicate with applets, databases, or other software via the
sockets and RMI mechanisms that you have seen already.

Servlets Architecture

The following diagram shows the position of Servlets in a Web Application.


Servlets Tasks

Servlets perform the following major tasks −

 Read the explicit data sent by the clients (browsers). This includes an
HTML form on a Web page or it could also come from an applet or a
custom HTTP client program.
 Read the implicit HTTP request data sent by the clients (browsers). This
includes cookies, media types and compression schemes the browser
understands, and so forth.
 Process the data and generate the results. This process may require
talking to a database, executing an RMI or CORBA call, invoking a Web
service, or computing the response directly.
 Send the explicit data (i.e., the document) to the clients (browsers).
This document can be sent in a variety of formats, including text
(HTML or XML), binary (GIF images), Excel, etc.
 Send the implicit HTTP response to the clients (browsers). This includes
telling the browsers or other clients what type of document is being
returned (e.g., HTML), setting cookies and caching parameters, and
other such tasks.

Servlets Packages

Java Servlets are Java classes run by a web server that has an interpreter
that supports the Java Servlet specification.

Servlets can be created using


the javax.servlet and javax.servlet.http packages, which are a standard
part of the Java's enterprise edition, an expanded version of the Java class
library that supports large-scale development projects.
These classes implement the Java Servlet and JSP specifications. At the time
of writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.

Java servlets have been created and compiled just like any other Java class.
After you install the servlet packages and add them to your computer's
Classpath, you can compile servlets with the JDK's Java compiler or any other
current compiler.

Servlets are Java classes which service HTTP requests and implement
the javax.servlet.Servlet interface. Web application developers typically
write servlets that extend javax.servlet.http.HttpServlet, an abstract class
that implements the Servlet interface and is specially designed to handle
HTTP requests.

Sample Code

Following is the sample source code structure of a servlet example to show


Hello World −

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException {


// Do required initialization
message = "Hello World";
}

public void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {

// Set response content type


response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy() {
// do nothing.
}
}

Compiling a Servlet

Let us create a file with name HelloWorld.java with the code shown above.
Place this file at C:\ServletDevel (in Windows) or at /usr/ServletDevel (in
Unix). This path location must be added to CLASSPATH before proceeding
further.

Assuming your environment is setup properly, go in ServletDevel directory


and compile HelloWorld.java as follows −

$ javac HelloWorld.java

If the servlet depends on any other libraries, you have to include those JAR
files on your CLASSPATH as well. I have included only servlet-api.jar JAR file
because I'm not using any other library in Hello World program.

This command line uses the built-in javac compiler that comes with the Sun
Microsystems Java Software Development Kit (JDK). For this command to
work properly, you have to include the location of the Java SDK that you are
using in the PATH environment variable.

If everything goes fine, above compilation would


produce HelloWorld.class file in the same directory. Next section would
explain how a compiled servlet would be deployed in production.

Servlet Deployment

By default, a servlet application is located at the path <Tomcat-


installationdirectory>/webapps/ROOT and the class file would reside in
<Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes.

If you have a fully qualified class name of com.myorg.MyServlet, then this


servlet class must be located in WEB-INF/classes/com/myorg/MyServlet.class.

For now, let us copy HelloWorld.class into


<Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes and create
following entries in web.xml file located in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>

Above entries to be created inside <web-app>...</web-app> tags available


in web.xml file. There could be various entries in this table already available,
but never mind.

You are almost done, now let us start tomcat server using <Tomcat-
installationdirectory>\bin\startup.bat (on Windows) or <Tomcat-
installationdirectory>/bin/startup.sh (on Linux/Solaris etc.) and finally
type http://localhost:8080/HelloWorld in the browser's address box. If
everything goes fine, you would get the following result

Java Applet

Applet is a special type of program that is embedded in the webpage to


generate the dynamic content. It runs inside the browser and works at client
side.

Advantage of Applet

There are many advantages of applet. They are as follows:

o It works at client side so less response time.


o Secured
o It can be executed by browsers running under many plateforms,
including Linux, Windows, Mac Os etc.

Drawback of Applet

o Plugin is required at client browser to execute applet.

Hierarchy of Applet
Lifecycle of Java Applet

1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

The java.applet.Applet class 4 life cycle methods and java.awt.Component


class provides 1 life cycle methods for an applet.

java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited. It


provides 4 life cycle methods of applet.

1. public void init(): is used to initialized the Applet. It is invoked only


once.
2. public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when
Applet is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked
only once.

java.awt.Component class

The Component class provides 1 life cycle method of applet.

1. public void paint(Graphics g): is used to paint the Applet. It


provides Graphics class object that can be used for drawing oval,
rectangle, arc etc.

Who is responsible to manage the life cycle of an applet?

Java Plug-in software.

How to run an Applet?

There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:

To execute the applet by html file, create an applet and compile it. After that
create an html file and place the applet code in html file. Now click the html
file.

1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome",150,150);
8. }
9.
10. }

Note: class must be public because its object is created by Java Plugin
software that resides on the browser.

myapplet.html

1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Introduction to JDBC (Java Database Connectivity)

JDBC stands for Java Database Connectivity. JDBC is a Java API to


connect and execute the query with the database. It is a specification from
Sun Microsystems that provides a standard abstraction (API or Protocol) for
Java applications to communicate with various databases. It provides the
language with Java database connectivity standards. It is used to write
programs required to access databases. JDBC, along with the database
driver, can access databases and spreadsheets. The enterprise data stored
in a relational database(RDB) can be accessed with the help of JDBC APIs.

Definition of JDBC (Java Database Connectivity)


JDBC is an API (Application programming interface) used in Java
programming to interact with databases. The classes and interfaces of
JDBC allow the application to send requests made by users to the specified
database. The current version of JDBC is JDBC 4.3, released on 21st
September 2017.
Purpose of JDBC
Enterprise applications created using the JAVA EE technology need to
interact with databases to store application-specific information. So,
interacting with a database requires efficient database connectivity, which
can be achieved by using the ODBC(Open database connectivity) driver. This
driver is used with JDBC to interact or communicate with various kinds of
databases such as Oracle, MS Access, Mysql, and SQL server database.
Components of JDBC
There are generally four main components of JDBC through which it can
interact with a database. They are as mentioned below:
1. JDBC API: It provides various methods and interfaces for easy
communication with the database. It provides two packages as follows,
which contain the java SE and Java EE platforms to exhibit WORA(write once
run anywhere) capabilities. The java.sql package contains interfaces and
classes of JDBC API.
2. JDBC Driver manager: It loads a database-specific driver in an
application to establish a connection with a database. It is used to make a
database-specific call to the database to process the user request.
3. JDBC Test suite: It is used to test the operation(such as insertion,
deletion, updation) being performed by JDBC Drivers.
4. JDBC-ODBC Bridge Drivers: It connects database drivers to the
database. This bridge translates the JDBC method call to the ODBC function
call. It makes use of the sun.jdbc.odbc package which includes a native
library to access ODBC characteristics.

Architecture of JDBC

Description:
1. Application: It is a java applet or a servlet that communicates with a
data source.
2. The JDBC API: The JDBC API allows Java programs to execute SQL
statements and retrieve results. Some of the important classes and
interfaces defined in JDBC API are as follows:
3. DriverManager: It plays an important role in the JDBC architecture. It
uses some database-specific drivers to effectively connect enterprise
applications to databases.
4. JDBC drivers: To communicate with a data source through JDBC, you
need a JDBC driver that intelligently communicates with the respective
data source.

Types of JDBC Architecture(2-tier and 3-tier)


The JDBC architecture consists of two-tier and three-tier processing
models to access a database. They are as described below:
1. Two-tier model: A java application communicates directly to the data
source. The JDBC driver enables the communication between the
application and the data source. When a user sends a query to the data
source, the answers for those queries are sent back to the user in the
form of results.
The data source can be located on a different machine on a network to
which a user is connected. This is known as a client/server
configuration, where the user’s machine acts as a client, and the
machine has the data source running acts as the server.

2. Three-tier model: In this, the user’s queries are sent to middle-tier


services, from which the commands are again sent to the data source.
The results are sent back to the middle tier, and from there to the user.
This type of model is found very useful by management information
system directors.

What is API?
Before jumping into JDBC Drivers, let us know more about API.
API stands for Application Programming Interface. It is essentially a set
of rules and protocols which transfers data between different software
applications and allow different software applications to communicate with
each other. Through an API one application can request information or
perform a function from another application without having direct access to
its underlying code or the application data.
JDBC API uses JDBC Drivers to connect with the database.

JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on
the server) that convert requests from Java programs to a protocol that the
DBMS can understand. There are 4 types of JDBC drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver (partially java driver)
3. Type-3 driver or Network Protocol driver (fully java driver)
4. Type-4 driver or Thin driver (fully java driver)
Interfaces of JDBC API
A list of popular interfaces of JDBC API is given below:
 Driver interface
 Connection interface
 Statement interface
 PreparedStatement interface
 CallableStatement interface
 ResultSet interface
 ResultSetMetaData interface
 DatabaseMetaData interface
 RowSet interface
Classes of JDBC API
A list of popular classes of JDBC API is given below:
 DriverManager class
 Blob class
 Clob class
 Types class
Working of JDBC
Java application that needs to communicate with the database has to be
programmed using JDBC API. JDBC Driver supporting data sources such as
Oracle and SQL server has to be added in java application for JDBC support
which can be done dynamically at run time. This JDBC driver intelligently
communicates the respective data source.
Creating a simple JDBC application:
Java

//Java program to implement a simple JDBC application

package com.vinayak.jdbc;

import java.sql.*;

public class JDBCDemo {

public static void main(String args[])

throws SQLException, ClassNotFoundException

{ String driverClassName

= "sun.jdbc.odbc.JdbcOdbcDriver";
String url = "jdbc:odbc:XE";

String username = "scott";

String password = "tiger";

String query

= "insert into students values(109, 'bhatt')";

// Load driver class

Class.forName(driverClassName);

// Obtain a connection

Connection con = DriverManager.getConnection(

url, username, password);

// Obtain a statement

Statement st = con.createStatement();

// Execute the query

int count = st.executeUpdate(query);

System.out.println(

"number of rows affected by this query= "

+ count);

// Closing the connection as per the


// requirement with connection is completed

con.close();

} // class

The above example demonstrates the basic steps to access a database using
JDBC. The application uses the JDBC-ODBC bridge driver to connect to the
database. You must import java.sql package to provide basic SQL
functionality and use the classes of the package.

What is the need of JDBC?


JDBC is a Java database API used for making connection between java
applications with various databases. Basically, JDBC used for establishing
stable database connection with the application API. To execute and process
relational database queries (SQL or Oracle queries), multiple application can
connect to different types of databases which supports both standard (SE)
and enterprise (EE) edition of java.

You might also like