Java Course Contents
Java Course Contents
INTRODUCTION
Java is a pure object oriented programming language and some of the key advantages of
Java Programming are :
Object Oriented − In Java, everything is an Object. Java can be easily extended since
it is based on the Object model.
Platform Independent − Unlike many other programming languages including C
and C++, when Java is compiled, it is not compiled into platform specific machine,
rather into platform independent byte code. This byte code is distributed over the web
and interpreted by the Virtual Machine (JVM) on whichever platform it is being run
on.
Secure − With Java's secure feature it enables to develop virus-free, tamper-free
systems. Authentication techniques are based on public-key encryption.
Architecture-neutral − Java compiler generates an architecture-neutral object file
format, which makes the compiled code executable on many processors, with the
presence of Java runtime system.
Portable − Being architecture-neutral and having no implementation dependent
aspects of the specification makes Java portable. Compiler in Java is written in ANSI
C with a clean portability boundary, which is a POSIX subset.
Example:
public class MyFirstJavaProgram
} //eoc
NB: A different number of programs can be taken into account for programming practice(s)
with respect different concepts.
Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
2
Control Statements :
There may be a situation when you need to execute a block of code several number of times.
In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −
Variable(s): A variable provides us with named storage that our programs can manipulate.
Each variable in Java has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and the set of
operations that can be applied to the variable.
Array: Java provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type.
3
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
Example: int Roll[] = new int [5] OR
Example:
interface Animal{
public void eat();
public void dance();
}
1. IDENTIFIER- Identifiers are the names that we specify for the variables, types,
classes, objects, methods and labels in the java program. Declaring these in a
declaration section creates identifiers. An identifier is a programmer-defined
4
name that represent some elements of a program. Variable names and class
names are the examples of the identifiers.
2. Keyword: are those special words whose meanings are prefixed by the java
compiler. Please note that you can’t use keyword to name classes or variables.
Also note that the keyword also called as the reserved words. some examples of
java’s keywords are as follow-
abstract char double for int private super try Boolean class else
goto interface protected switch void break const extends if long
public synchronized volatile byte continue final implements native
return this while case default finally import new short throw catch
do float instanceof package static transient
3. Variable- A variable is a container that holds values that are used in a Java
program. Every variable must be declared to use a data type. For example, a
variable could be declared to use one of the eight primitive data types: byte,
short, int, long, float, double, char or boolean.
*Declaration of variable
To declare a variable in Java, all that is needed is the data type followed by
the variable name:
int numberOfDays;
5
In the above example, a variable called "numberOfDays" has been declared
with a data type of int. Notice how the line ends with a semi-colon (;).
Integers
Floating-point numbers
6
Characters
Boolean
OPERATORS ( IN JAVA)
1. ARITHMETIC OPERATORS
2. RELATIONAL OPERATORS
7
3. LOGICAL OPERATORS
8
2. Exception & Graphics Programming
Inheritance
Inheritance: Inheritance can be defined as the process where one class acquires the
properties (methods and fields) 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).
extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword.
Example:
Example:
NB: Different FORMS of Inheritance can be implemented by using interface technology for
multiple inheritance.
Life Cycle of a Thread: 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.
11
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.
Example:
12
ThreadDemo T2 = new ThreadDemo(); T2.start();
} // eom
}// eoc
Example
//String class
class A22
{
public static void main(String[] ar)
{
String s1=new String("A QUICK FOX JUMP OVER THE LAZY
DOG");
System.out.println(s1.length());
System.out.println(s1.charAt(5));
System.out.println(s1.indexOf('A'));
System.out.println(s1.indexOf('A',5));
System.out.println(s1.substring(4));
System.out.println(s1.substring(4,20));
System.out.println(s1.equals("A QUICK fox JUMP OVER THE
LAZY DOG"));
System.out.println(s1.equalsIgnoreCase("A QUICK fox JUMP
OVER THE LAZY DOG"));
}
}
//Constructor
class Employee
{
int a=20;
Employee()
{
System.out.println("SIMPLE CLASS");
a=220;
System.out.println(a);
}
{
System.out.println(a);
}
}
class A52
{
public static void main(String[] ar)
{
Employee e=new Employee();
} }
//Parsing
13
class M1
{
public static void main(String[] ar)
{
int p=Integer.parseInt(ar[0]);
for(int i=p;i>0;i--)
{
for(int j=0;j<i;j++)
{
System.out.print('*');
}
System.out.print("\n");
}
}
}
Handling/ Event
Exception: 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.
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.
Example: as above in try-catch block. Different number of Exceptions must be tried in
programming form.
//Exception Handling
class Customer
{
int balance;
Customer(int balance)throws Exception
{
if(balance>500)
{
this.balance=balance;
}
else
{
throw new Exception("BALANCE CANT BE LESS THAN 500");
14
}
}
}
class A24
{
public static void main(String[] ar)
{
try
{
Customer c=new Customer(200);
}catch(Exception ee)
{
System.out.println("this is the error"+ee);
}
}
}
Wrapper classes are those whose objects wraps a primitive data type within them.
In the java.lang package java provides a separate class for each of the primitive data types
namely Byte, Character, Double, Integer, Float, Long, Short.
At the time of instantiation, these classes accept a primitive datatype directly, or in the form
of String.
Wrapper classes provide methods to, convert primitive datatypes within them to String
objects and, to compare them with other objects etc.
Using wrapper classes, you can also add primitive datatypes to various Collection objects
such as ArrayList, HashMap etc. You can also pass primitive values over a network using
wrapper classes.
Need of Wrapper Classes
1. They convert primitive data types into objects. Objects are needed if we wish to modify
the arguments passed into a method (because primitive types are passed by value).
2. The classes in java.util package handles only objects and hence wrapper classes help in
this case also.
3. Data structures in the Collection framework, such as ArrayList and Vector, store only
objects (reference types) and not primitive types.
Each web browser that supports JAVA VIRTUAL MACHINE (JVM) built right into
it and it loads .class file. It is also evident that when a program is interpreted, it
generally runs substantially slower then it would run if compiled to an
executable code. But remember that the use of the byte-code enables the java run
time system to execute program faster. Sun has introduced just in time compiler
(JIT) for byte- code. Just in time compiler (JIT compiler) is part of JVM. Its job is to
take the generic i.e. cross-platform byte-codes and compile them into more
machine specific instructions allowing the program to run faster. Even though it
is referred to as a JIT compiler, it is the part of the virtual machine. When JIT is
part of a JVM, it compiles byte-codes into executable code in real time, on
demand basis, this is so because JVM perform various run time checks that can be
done only at the run-time. Instead, JIT compiles the code as it is needed during
the execution. JVM code is designed so that it is easy to translate it into machine
instructions for real machine, so the second part of the translation to real
machine instructions is done in the browser on the user’s machine. Please
understand that the browser takes the applet JVM code that it gets from the
server and translates from JVM code to the machine code the browser is
using. This compiler in the browser is often called as a JIT compiler. Also
understand that JIT means that the last part of the compilation is done
before running the program.
16
Autoboxing: Automatic conversion of primitive types to the object of their corresponding
wrapper classes is known as autoboxing. For example – conversion of int to Integer, long to
Long, double to Double etc.
Example:
17
Concept of WRAPPER CLASS
18
CONCEPT OF VECTOR CLASS
Vector implements a dynamic array. It is similar to ArrayList, but with two differences −
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections framework.
Vector proves to be very useful if you don't know the size of the array in advance or you just
need one that can change sizes over the lifetime of a program.
Example:
import java.util.*;
v.addElement(new Double(5.45));
if(v.contains(new Integer(3)))
System.out.println();
Graphics Class
In Java, the drawing takes place via a Graphics object, this is an instance of
the java.awt.Graphics class.
Each Graphics object has its own coordinate system and all the methods of Graphics
including those for drawing Strings, lines, rectangles, circles, polygons and etc.
20
We can get access to the Graphics object through the paint(Graphics g) method.
We can use the drawRoundRect() method that accepts x-coordinate, y-
coordinate, width, height, arcWidth, and arc height to draw a rounded rectangle.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RoundedRectangleTest extends JFrame {
public RoundedRectangleTest() {
setTitle("RoundedRectangle Test");
setSize(350, 275);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawRoundRect(10, 50, 150, 150, 50, 30); // to draw a rounded rectangle.
}
public static void main(String []args) {
new RoundedRectangleTest();
}
}
NB: The concept of event handling/ AWT may either be practiced with Applet programing as
per the library functions ( Methods ) availabe in Java.
//awt
import java.lang.*;
import java.awt.*;
class A45
{
public static void main(String[] ar)
{
Frame f=new Frame();
f.setSize(500,500);
f.setVisible(true);
}
}
21
//graphics example
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class Frame1 extends Frame
{
Label l=new Label();
Button b=new Button();
Frame1(String title)
{
this.setSize(500,600);
this.setLayout(null);
this.add(l);
l.setBounds(10,100,200,30);
this.add(b);
b.setBounds(210,100,200,30);
b.addActionListener(new ActionListener(){public void
actionPerformed(ActionEvent e){add();}});
this.addMouseMotionListener(new MouseAdapter(){public
void mouseMoved(MouseEvent e){f1(e);}});
this.addMouseMotionListener(new MouseAdapter(){public
void mouseMoved(MouseEvent e){add();}});
}
int r=0;
void add()
{
r=r+60;
repaint();
}
void f1(MouseEvent e)
{
int x=e.getX();
int y=e.getY();
l.setText("x="+x+"y="+y);
}
public void paint(Graphics g)
{
g.drawRect(10,35,100,50);
g.setColor(Color.RED);
g.fillRect(110,35,100,50);
g.fillOval(250,250,200,20);
g.fillArc(30,400,200,100,0+r,30);
g.setColor(Color.GREEN);
g.fillArc(30,400,200,100,30+r,60);
g.setColor(Color.YELLOW);
g.fillArc(30,400,200,100,90+r,60);
g.setColor(Color.GRAY);
g.fillArc(30,400,200,100,150+r,90);
g.setColor(Color.PINK);
g.fillArc(30,400,200,100,240+r,120);
}
22
}
class A73
{
public static void main(String[] ar)
{
new Frame1("").setVisible(true);
}
}
An applet is a Java program that runs in a Web browser. An applet can be a fully functional
Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application,
including the following −
An applet is a Java class that extends the java.applet.Applet class.
A main() method is not invoked on an applet, and an applet class will not define main().
Applets are designed to be embedded within an HTML page.
When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment
The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser. The security of
an applet is often referred to as sandbox security, comparing the applet to a child
playing in a sandbox with various rules that must be followed.
Four methods in the Applet class gives you the framework on which you build any serious
applet −
init − This method is intended for whatever initialization is needed for your applet. It is
called after the param tags inside the applet tag have been processed.
start − This method is automatically called after the browser calls the init method. It is
also called whenever the user returns to the page containing the applet after having
gone off to other pages.
stop − This method is automatically called when the user moves off the page on which
the applet sits. It can, therefore, be called repeatedly in the same applet.
destroy − This method is only called when the browser shuts down normally. Because
applets are meant to live on an HTML page, you should not normally leave resources
behind after a user leaves the page that contains the applet.
paint − Invoked immediately after the start() method, and also any time the applet
needs to repaint itself in the browser. The paint() method is actually inherited from the
java.awt.
import java.applet.*;
import java.awt.*;
23
public class HelloWorldApplet extends Applet {
public void paint (Graphics g) {
g.drawString ("Hello World", 25, 50);
}
}
Every applet is an extension of the java.applet.Applet class. The base Applet class provides
methods that a derived Applet class may call to obtain information and services from the
browser context.
These include methods that do the following −
Get applet parameters
Get the network location of the HTML file that contains the applet
Get the network location of the applet class directory
Print a status message in the browser
Fetch an image
Fetch an audio clip
Play an audio clip
Resize the applet
Invoking an Applet
An applet may be invoked by embedding directives in an HTML file and viewing the file
through an applet viewer or Java-enabled browser.
The <applet> tag is the basis for embedding an applet in an HTML file. Following is an
example that invokes the "Hello, World" applet −
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code = "HelloWorldApplet.class" width = "320" height = "120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>
Note − You can refer to HTML Applet Tag to understand more about calling applet from
HTML.
The code attribute of the <applet> tag is required. It specifies the Applet class to run. Width
and height are also required to specify the initial size of the panel in which an applet runs.
The applet directive must be closed with an </applet> tag.
24
If an applet takes parameters, values may be passed for the parameters by adding <param>
tags between <applet> and </applet>. The browser ignores text and other tags between the
applet tags.
Non-Java-enabled browsers do not process <applet> and </applet>. Therefore, anything that
appears between the tags, not related to the applet, is visible in non-Java-enabled browsers.
Event Handling
Applets inherit a group of event-handling methods from the Container class. The Container
class defines several methods, such as processKeyEvent and processMouseEvent, for
handling particular types of events, and then one catch-all method called processEvent.
In order to react to an event, an applet must override the appropriate event-specific method.
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.applet.Applet;
import java.awt.Graphics;
25
// Draw a Rectangle around the applet's display area.
g.drawRect(0, 0,
getWidth() - 1,
getHeight() - 1);
<html>
<title>Event Handling</title>
<hr>
<applet code = "ExampleEventHandling.class"
width = "300" height = "300">
</applet>
<hr>
</html>
Initially, the applet will display "initializing the applet. Starting the applet." Then once you
click inside the rectangle, "mouse clicked" will be displayed as well.
Stream represents a sequence of objects from a source, which supports aggregate operations.
Following are the characteristics of a Stream −
26
Sequence of elements − A stream provides a set of elements of specific type in a
sequential manner. A stream gets/computes elements on demand. It never stores the
elements.
Source − Stream takes Collections, Arrays, or I/O resources as input source.
Aggregate operations − Stream supports aggregate operations like filter, map, limit,
reduce, find, match, and so on.
Pipelining − Most of the stream operations return stream itself so that their result can
be pipelined. These operations are called intermediate operations and their function is
to take input, process them, and return output to the target. collect() method is a
terminal operation which is normally present at the end of the pipelining operation to
mark the end of the stream.
Automatic iterations − Stream operations do the iterations internally over the source
elements provided, in contrast to Collections where explicit iteration is required.
The java.io package contains nearly every class you might ever need to perform input and
output (I/O) in Java. All these streams represent an input source and an output destination.
The stream in the java.io package supports many data such as primitives, object, localized
characters, etc.
A stream can be defined as a sequence of data. There are two kinds of Streams −
InPutStream − The InputStream is used to read data from a source.
OutPutStream − The OutputStream is used for writing data to a destination.
Java provides strong but flexible support for I/O related to files and networks but this tutorial
covers very basic functionality related to streams and I/O. We will see the most commonly
used examples one by one −
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream. Following is an example which makes use of
these two classes to copy an input file into an output file −
import java.io.*;
public class CopyFile {
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
27
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
} } } }
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode. Though
there are many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two classes to copy an
input file (having unicode characters) into an output file −
import java.io.*;
public class CopyFile {
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
28
Reading and Writing Files
As described earlier, a stream can be defined as a sequence of data. The InputStream is used
to read data from a source and the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.
FileInputStream
This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the
file −
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file. First
we create a file object using File() method as follows −
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create a file,
if it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write
the file −
OutputStream f = new FileOutputStream("C:/java/hello")
29
Following constructor takes a file object to create an output stream object to write the file.
First, we create a file object using File() method as follows −
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand, then there is a list of helper methods, which can
be used to write to stream or to do other operations on the stream.
NB: Depending upon the operations the corresponding methods/ objects may be called upon
accordingly.
//DataInputStream
import java.io.*;
class A30
{
public static void main(String[] ar)throws IOException
{
DataInputStream ds=new DataInputStream(System.in);
System.out.println(ds.readInt());
System.out.println((ds.write());
}
}
UNIT-II
5. SWING
SWING - Overview
Swing API is a set of extensible GUI Components to ease the developer's life to create JAVA
based Front End/GUI Applications. It is build on top of AWT API and acts as a replacement
of AWT API, since it has almost every control corresponding to AWT controls. Swing
component follows a Model-View-Controller architecture to fulfill the following criterias.
A single API is to be sufficient to support multiple look and feel.
API is to be model driven so that the highest level API is not required to have data.
API is to use the Java Bean model so that Builder Tools and IDE can provide better
services to the developers for use.
30
MVC Architecture
Swing API architecture follows loosely based MVC architecture in the following manner.
Model represents component's data.
View represents visual representation of the component's data.
Controller takes the input from the user on the view and reflects the changes in
Component's data.
Swing component has Model as a seperate element, while the View and Controller part
are clubbed in the User Interface elements. Because of which, Swing has a pluggable
look-and-feel architecture.
Swing Features
Light Weight − Swing components 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.
Rich Controls − Swing provides a rich set of advanced controls like Tree, TabbedPane,
slider, colorpicker, and table controls.
Highly Customizable − Swing controls can be customized in a very easy way as visual
apperance is independent of internal representation.
Pluggable look-and-feel − SWING based GUI Application look and feel can be
changed at run-time, based on available values.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showEventDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java SWING Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
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);
}
private void showEventDemo(){
headerLabel.setText("Control in action: Button");
okButton.setActionCommand("OK");
32
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);
}
private class ButtonClickListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
33
6. Java - Networking
The term 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.
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.
Socket Programming
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.
34
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.
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.
// File Name GreetingClient.java
import java.net.*;
import java.io.*;
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 −
// File Name GreetingServer.java
import java.net.*;
import java.io.*;
35
public class GreetingServer extends Thread {
private ServerSocket serverSocket;
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; } } }
36
7. Advanced Applet Programming
Hierarchy of Applet
As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing.
The JApplet class extends the Applet class.
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class EventJApplet extends JApplet implements ActionListener{
JButton b;
JTextField tf;
public void init(){
tf=new JTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
37
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
myapplet.html
1. <html>
2. <body>
3. <applet code="EventJApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of MouseMotionListener.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseDrag extends Applet implements MouseMotionListener{
In the above example, getX() and getY() method of MouseEvent is used to get the current x-axis and y-axis. T
method of Component class returns the object of Graphics.
myapplet.html
1. <html>
2. <body>
3. <applet code="MouseDrag.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet
class provides a method named getParameter(). Syntax:
import java.applet.Applet;
import java.awt.Graphics;
myapplet.html
39
1. <html>
2. <body>
3. <applet code="UseParam.class" width="300" height="300">
4. <param name="msg" value="Welcome to applet">
5. </applet>
6. </body>
7. </html>
40
8. Java JDBC & Packages
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database. There are four types of JDBC drivers:
We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.
The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is
based on the X/Open SQL Call Level Interface. The java.sql package contains classes and
interfaces for JDBC API. A list of popular interfaces of JDBC API are given below:
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface
41
Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).
We can use JDBC API to handle database using Java program and can perform the following
activities:
JDBC Driver
JDBC Driver is a software component that enables java application to interact with the database. There are 4
drivers:
42
Java Database Connectivity with 5 Steps
1. Register the driver class
2. Create the connection object
3. Create the Statement object
4. Execute the query
5. Close the connection object
There are 5 steps to connect any java application with the database using JDBC. These steps are as follows:
Example
import java.sql.*;
// implementing DriverAction interface
class JdbcExample implements DriverAction{
// implementing deregister method of DriverAction interface
@Override
public void deregister() {
System.out.println("Driver deregistered");
}
public static void main(String args[]){
try{
// Creating driver instance
Driver driver = new com.mysql.jdbc.Driver();
// Creating Action Driver
DriverAction da = new JdbcExample();
// Registering driver by passing driver and driverAction
DriverManager.registerDriver(driver, da);
// Creating connection
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/student"
,"root","mysql");
//Here student is database name, root is username and password is mysql
Statement stmt=con.createStatement();
// Executing SQL query
ResultSet rs=stmt.executeQuery("select * from user");
while(rs.next()){
System.out.println(rs.getInt(1)+""+rs.getString(2)+""+rs.getString(3));
43
}
// Closing connection
con.close();
// Calling deregisterDriver method
DriverManager.deregisterDriver(driver);
}catch(Exception e){ System.out.println(e);}
}
//Example
import java.sql.*;
class A105
{
public static void main(String[] ar)
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE
","System","java");
Statement s=con.createStatement();
String query="insert into sliet
values('Ankit','GAAYA',20)";
s.executeUpdate(query);
}catch(Exception ee)
{
System.out.println(ee+""); } } }
NB: A number of operations can be performed according to the need of the concepts.
Similarly, the client server model can be practicized with servlet technology.
JSP
JSP technology is used to create web application just like Servlet technology. It can be
thought of as an extension to Servlet because it provides more functionality than servlet such
as expression language, JSTL, etc.
44
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than
Servlet because we can separate designing and development. It provides some additional
features such as Expression Language, Custom Tags, etc.
There are many advantages of JSP over the Servlet. They are as follows:
1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all the features of the
Servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression
language and Custom tags in JSP, that makes JSP development easy.
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with
presentation logic. In Servlet technology, we mix our business logic with the presentation
logic.
If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet
code needs to be updated and recompiled if we have to change the look and feel of the
application.
Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side programming
45
language. However, there were many disadvantages to this technology. We have discussed
these disadvantages below.
There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.
Advantages of Servlet
There are many advantages of Servlet over CGI. The web container creates threads for
handling the multiple requests to the Servlet. Threads have many benefits over the Processes
such as they share a common memory area, lightweight, cost of communication between the
threads are low. The advantages of Servlet are as follows:
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory
leak, garbage collection , etc.
4. Secure: because it uses java language.
46
Objective Type Question-Bank (MCQ)
All objective type(s) questions [ 01-50 ], Short Answer type [ 5 questions 1-80], Long
Answer/ descriptive type questions [81-100]
Q2. What is the size of float and double in java? ( Ans. 32 and 64 )
Q3. Automatic type conversion is possible in which of the possible cases? ( Ans. int to long
)
Q4. When an array is passed to a method, what does the method receive? ( Ans. Reference
of the array )
Q7. To which package does the class string belong to : ( Ans. java.lang. )
Q9. Find the output of the following code. ( Ans. Compilation Error)
Q10. Identify the return type of a method that does not return any value. (Ans. void)
Q11. Identify the modifier which cannot be used for constructor. (Ans. static)
Q12. What is the variables declared in a class for the use of all methods of the class called?
(Ans. instance variable)
Q14. Identify the prototype of the default constructor. Public class Solution {}
(Ans. public Solution() )
Q18. Which of the following statements are true about finalize() method?
Q20. Which of the following is used to find and fix bugs in the program?
JDK JRE JVM JDB (Ans.)
Q22. Which of these cannot be used for a variable name in Java? (Ans. keywords)
a) MAVEN_Path
b) JavaPATH
c) JAVA
d) JAVA_HOME (Ans.)
Q25. What is the use of “this” keyword in Java? (Ans. to address the current class
references)
Q27. What is the extension of compiled java classes? (Ans. *.class extension)
48
Q28. Which of these statements is incorrect about Thread?
a) start() method is used to begin execution of the thread
b) run() method is used to begin execution of a thread before start() method in special cases
(Ans.)
c) A thread can be formed by implementing Runnable interface only
d) A thread can be formed by a class that extends Thread class
a) Numeric
b) Boolean
c) Characters
d) Both Numeric & Characters (Ans.)
49
Q36. What is meant by the classes and objects that dependents on each other?
a. Tight Coupling (Ans) b.Cohesion c. Loose Coupling d. None of the above
a. Only one thread b. Multiple threads (Ans) c).Only main (main() method) thread
d. Two threads
Q39. Which component is used to compile, debug and execute the java programs?
a) JRE b) JIT c) JDK (Ans) d) JVM
Q41. Which type of loop is best known for its boolean condition that controls entry to the
loop?
A. do-while loop B. for (traditional) C. for-each D. While (Ans)
Q42. Java is an object-oriented programming language developed by ____
a. Oracle b. Sun Micro Systems (Ans) c.Unix d. Netcape
Q43. Java is also a general-purpose programming language for developing programs that are
easly usable and portable across different ________
a. Tables b. Stands c. Libraries d. Platforms (Ans)
Q44. Using ________ one can take full advantage of object-oriented methodology and its
capabilities of creating flexible, modular and reusable code.
a. Java Language (Ans) b. C- Language c. Basic- Language d. PHP
Q46. The machine language for the Java Virtual Machine is called ___
a. Compiler b. Interpreter (Ans) c. Translator d. None of these
Q47. A Java program should have at least one ___ and it must have main __ in it.
a. Class, Procedure b. Class, Variable c. Class, method (Ans) d. Class, code
Q48. Java source file can be creaated using any plain _____ text editor.
a. Native b. Original c. ASCII (Ans d. Binary
Q49. Java ___ files are given the same name as the class defined with an extension of Java.
a. Beginning b. Destination c. Source (Ans) d. Binary
50
Q50. In Java the ___ name is case sensitive.
a. File b. Folder c. Class (Ans ) d. First
Q55. What is meant by the Local variable and the Instance variable?
51
Q69. What is Array and ArrayList?
Q82. Discuss different data types in Java with a suitable programming code.
Q83. Discuss the different control structures in Java with a suitable progmming code.
Q84. Write a program to read a number form the keyboard and find its factorial.
Q86. Explain the concept of Arrays in Java and demonstrate the additoin of matix having a
size 3x3.
Q89. What is multithreaded programming? Show how threads can be created in Java?
Q90 Explain the following AWT components – Label, Checkbox, Radio Button and List
control with a suitable programming code in Java.
Q95. Explain the concept and significance of Autoboxing and Wrapper class in Java.
Q96. Explain the concept of event-driven programming in java with suitable example.
Q97. Explain the concept of User-defined Package. Also demonstrate with a suitable
program.
Q100. Explain the significant features of Vector class and methods associated with it. How
Vector is best than the concept of Arrays
53
LIST OF PRACTICALS
1) Write a Program to create the variables of different data types and also show the effect
of type conversions. Also demonstrate the output of each.
2) Write a program to illustrate the behaviour of print() and println() methods of System
class.
3) Write a program to convert the given temperature in Fahrenheit to Celsius.
4) Write a program to find all the numbers of and sum of all the integers
5) Write a program to print multiplication table using do-while loop.
6) Write a program to reverse the digits of a number using while loop.
7) Write a program to print the Fibonacci series.
8) Write a prorgram to read a number from console and calculate its factorial.
9) Write a program to illustrate the concept of constructors.
10) Write a program to illustrate the concept of single (multiple using interface)
inheritance.
11) Write a program to illustrate the use of an array for sorting a list of numbers.
12) Write a program to illustrate the use of some commonly used wrapper class methods.
13) Write a program to illustrate the use of Thread class for creating and running threads
in an application.
54