Attachment
Attachment
using Java 2
Course Outline
4.0 Know how to use Java Servlet, and Java Server Pages (JSP)
Java Arrays
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.
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.
1. arrayRefVar=new datatype[size];
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
We can declare, instantiate and initialize the java array together by:
Output:
33
3
4
5
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.
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.
Output:
33
3
4
5
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.
Output:
Output:
10
30
50
90
60
In such case, data is stored in row and column based index (also known as
matrix form).
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;
Let's see the simple example to declare, instantiate, initialize and print the
2Dimensional array.
Output:
123
245
445
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.
Output:
Output:
caffein
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.
Output:
268
6 8 10
Output:
666
12 12 12
18 18 18
Java Inheritance
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).
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
class Calculation {
int z;
javac My_Calculation.java
java My_Calculation
Output
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.
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.
The super keyword is similar to this keyword. Following are the scenarios
where the super keyword is used.
Sample Code
Example
class Super_class {
int num = 20;
Compile and execute the above code using the following syntax.
javac Super_Demo
java Super
Output
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;
}
Compile and execute the above code using the following syntax.
javac Subclass
java Subclass
Output
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.
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
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.
class One {
public void printOne() {
System.out.println("printOne() method of One class.");
}
}
// Calling methods
obj.printOne();
obj.printTwo();
}
}
Output
Java Encapsulation
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 −
Output
Benefits of Encapsulation
A read-only class can have only getter methods to get the values of the
attributes, there should not be any setter method.
// Class "Person"
class Person {
private String name = "Robert";
private int age = 21;
// Getter methods
public String getName() {
return this.name;
}
Output
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.
Now, the Deer class is considered to be polymorphic since this has multiple
inheritance. Following are true for the above examples −
When we apply the reference variable facts to a Deer object reference, the
following declarations are legal −
All the reference variables d, a, v, o refer to the same Deer object in the
heap.
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;
Output
true
true
true
true
An exception can occur for many different reasons. Following are some
scenarios where an exception occurs.
Checked exceptions
Unchecked exceptions
Errors
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.
You can create your own exceptions in Java. Keep the following points in
mind when writing your own exception classes −
Syntax
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.
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)
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.
Thread Priorities
Every Java thread has a priority that helps the operating system determine
the order in which threads are scheduled.
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.
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 −
As a second step, you will instantiate a Thread object using the following
constructor −
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();
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
Sr.N
Method & Description
o.
Java 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.
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 following steps occur when establishing a TCP connection between two
computers using sockets −
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.
Sr.N
Method & Description
o.
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.
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.
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;
}
}
}
Output
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.
Servlets Architecture
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.
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
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.
$ 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.
Servlet Deployment
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
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
Advantage of Applet
Drawback of 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.
java.applet.Applet class
java.awt.Component class
1. By html file.
2. By appletViewer tool (for testing purpose).
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>
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.
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
package com.vinayak.jdbc;
import java.sql.*;
{ String driverClassName
= "sun.jdbc.odbc.JdbcOdbcDriver";
String url = "jdbc:odbc:XE";
String query
Class.forName(driverClassName);
// Obtain a connection
// Obtain a statement
Statement st = con.createStatement();
System.out.println(
+ count);
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.