Document 305265

SEC
CSE/V
JAVA LAB MANUAL
SRINIVASAN ENGINEERING COLLEGE
COMPUTER SCIENCE AND ENGINEERING
ANNA UNIVERSITY CHENNAI
REGULATION 2009
III CSE (2013-2014)
CS 2309
JAVA LAB MANUAL
PREPARED BY
S.NANDHINI DEVI, Assistant Professor
K.RAMESH, Assistant Professor
1
SEC
CSE/V
JAVA LAB MANUAL
Preface
This laboratory manual is prepared by the Department of Computer Science
and engineering for JAVA L A B (CS 2309). This lab manual can be used as instructional
book for students, staff and instructors to assist in performing and understanding the
experiments. In the first part of the manual, experiments as per syllabus are described and in
the second part of the manual, experiments that are beyond the syllabus but expected for
university laboratory examination
are
displayed.
This manual
will
be
available
in
electronic form from College’s official website, for the betterment of students.
Acknowledgement
We would like to express our profound gratitude and deep regards to the support
offered by the Chairman Shri. A.Srinivasan. We also take this opportunity to express a deep
sense of gratitude
to
our
Principal
Dr.B.Karthikeyan,M.E,Ph.D,
for
his
valuable
information and guidance, which helped us in completing this task through various stages. We
extend our hearty thanks to our head of the department Asst.Prof.S.JAYANTHI M.E for her
constant encouragement and constructive comments.
Finally the valuable comments from fellow faculty and assistance provided by the
department are highly acknowledged.
2
SEC
CSE/V
CHAPTER NO
JAVA LAB MANUAL
TOPIC
PAGE NO
Introduction to the language
Main Features
Advantages
Limitations
Applications
I
II
III
IV
V
VI
Syllabus
System Requirements
Description about each experiment
Aim
Overview of each experiment
Learning Objective
General procedure to execute programs
4
8
9
10
Experiments
To implement rational number class in Java
1
To implement date class in Java
2
12
18
3
To implement Lisp-like list in Java
22
4
To design a Java interface for ADT Stack
29
5
To design a Vehicle class hierarchy in Java
44
6
To implement random generation of objects
51
7
To implement calculator in Java
60
8
To implement multithreading in Java
72
9
To implement Simple OPAC system for Library
79
10
To implement multithreaded Echo Server and client
90
Experiments beyond the syllabus
101
3
SEC
CSE/V
JAVA LAB MANUAL
CHAPTER I
INTRODUCTION OF THE LANGUAGE (CORRESPONDING VERSION)
JAVA
Java is an Object Oriented programming language developed by Sun Microsystems in
1991.Initially it was known as Oak but latter it renamed to java. Java was developed by taking the
best points from other programming languages, primarily C and C++. Java is such a great language
and platform for any kind of application. It is open, fast, powerful, runs on any platform, and there
are more jobs for Java than any other programming language.Java is a well known technology which
allows you for software designed and written only once for an "virtual machine" to run on a
different computers, supports various Operating System like Windows PCs, Macintoshes, and Unix
computers.Error prone tasks such as pointers and memory management have either been eliminated
or are handled by the Java environment automatically rather than by the programmer.
Advantages of JAVA
JAVA offers a number of advantages to developers.
Java is simple: Java was designed to be easy to use and is therefore easy to write, compile, debug,
and learn than other programming languages. The reason that why Java is much simpler than C++
Java is object-oriented: Java is object-oriented because programming in Java is centered on
creating objects, manipulating objects, and making objects work together. This allows you to
create modular programs and reusable code.
Java is platform-independent: One of the most significant advantages of Java is its ability to
move easily from one computer system to another.
Java is distributed: Distributed computing involves several computers on a network
working together. Java is designed to make distributed computing easy with the networking
capability that is inherently integrated into it. Writing network programs in Java is like
sending and receiving data to and from a file.
4
SEC
CSE/V
JAVA LAB MANUAL
Java is interpreted: An interpreter is needed in order to run Java programs. The programs are
compiled into Java Virtual Machine code called bytecode. The bytecode is machine independent
and is able to run on any machine that has a Java interpreter.
Java is secure: Java is one of the first programming languages to consider security as part of its
design. The Java language, compiler, interpreter, and runtime environment were each developed
with security in mind.
Current Limitations and Disadvantages of Java
These exist mostly because the language is still evolving.
1. Slow
o
Internet as a whole

Potential huge show-stopper problem.

Bandwidth is a limited resource that is easily squandered.

Minimal incentive for people to conserve.

Potential demand is unbounded, potential supply is bounded.
Solutions:

Write applications instead of applets (but then you lose
some advantages)

Cache your applets (only partial solution).
Java compiler:

Not yet well optimized.

Takes more time to compile a large program than a good C++
compiler.
5
SEC
CSE/V
JAVA LAB MANUAL
2. Environment limitations
Currently lacks:

Browser

Interactive source-level debugger

User interface builder
3. Applet limitations imposed due to security

Cannot access local data

Can only download data from the site where the applet is located

Cannot make system calls

Solution: Use applications
4. Programming language limitations

No `Templates' yet.
 Limits

ability to create really good data structures
No `Function pointers' or `blocks'
 These
would allow greater abstraction and more flexible data-structure
design
 Available

in both C++ and Smalltalk
Basic classes in class library are lacking important features
 The
class library was created to quickly and has now been widely
adopted, making it hard to change.
 This
is also a problem with other languages
6
SEC
CSE/V
JAVA LAB MANUAL


 We
can expect the current widespread standardization to fragment as
vendors introduce competing classes to fill the gaps
5. Platform limitations
Full environment available only for:
Windows 95/NT

Macintosh

Sun Solaris
Other platforms must wait for 3rd party support
Application Java programming Language :
 Since Java has inbuilt networking features so it is widely used for developing network
related programs and softwares. Socket Programming using JAVA is very simple and
efficient and simple as compared to c.
 It is widely used for creating web applications and it can also generate static HTML
content like PHP and JavaScript so it is used in website designing too.
 In application software development Java is widely used because it is a fully Object
Oriented programming language.
 Creating Graphical User Interface(GUI) in Java is very simple and efficient as compared to C
and C++.So it is also used in creating GUI for applications.
7
SEC
CSE/V
JAVA LAB MANUAL
CHAPTER II
SYLLABUS
CS2309 – JAVA LAB
LIST OF EXPERIMENTS
1. To implement rational number class in Java
2. To implement date class in Java
3. To implement Lisp-like list in Java
4. To design a Java interface for ADT Stack
5. To design a Vehicle class hierarchy in Java
6. To implement random generation of objects
7. To implement calculator in Java
8. To implement multithreading in Java
9. To implement Simple OPAC system for library
10. To implement multithreaded Echo Server and client
8
SEC
CSE/V
JAVA LAB MANUAL
CHAPTER III
SYSTEM REQUIREMENTS
1 HARDWARE REQUIREMENTS:
Intel Pentium 915 GV
80GB SATA II
512MB DDR
2 SOFTWARE REQUIREMENTS:
JAVA
9
SEC
CSE/V
JAVA LAB MANUAL
CHAPTER IV
DESCRIPTION ABOUT EACH EXPERIMENT
AIM
The aim of the J a v a lab is to give students a good understanding of basic concepts
of Java language and to develop real time applications
OVERVIEW OF THE EXPERIMENTS
EXPERIMENT NO 1: TO IMPLEMENT RATIONAL NUMBER CLASS IN JAVA
To develop a Rational number class in Java, using JavaDoc comments for documentation.
EXPERIMENT NO 2: TO PERFORM DATE CLASS IN JAVA
To develop Date class in Java similar to the one available in java.util package.Use JavaDoc
comments.
EXPERIMENT NO 3: TO IMPLEMENT LISP LIKE LIST IN JAVA
To implement Lisp-like list in Java. To perform the basic operations such as 'car', 'cdr',
and 'cons'.
EXPERIMENT NO 4: TO DESIGN A JAVA INTERFACE FOR ADT STACK
To design a Java interface for ADT Stack and to develop two different classes that
implements this interface, one using array and the other using linked-list.
EXPERIMENT NO 5: TO DESIGN A VEHICLE CLASS HIERARCHY IN JAVA
To design a Vehicle class hierarchy in Java and to demonstrate polymorphism.
EXPERIMENT NO 6: TO IMPLEMENT RANDOM GENERATION OF OBJECTS
To design classes namely Currency, Rupee, and Dollar. To write a program that randomly
generates Rupee and Dollar objects and writes them into a file using object serialization.
10
SEC
CSE/V
JAVA LAB MANUAL
EXPERIMENT NO 7: TO IMPLEMENT CALCULATOR IN JAVA
To design a calculator using event-driven programming paradigm of Java.
EXPERIMENT NO 8: TO IMPLEMENT MULTITHREADING IN JAVA
To write a program in Java that prints all the prime numbers in the Fibonacci series below 10000
using multithreading.
EXPERIMENT NO 9: TO IMPLEMENT SIMPLE OPAC SYSTEM FOR LIBRARY
To develop a simple OPAC system for library using event-driven and concurrent programming
paradigms of Java. JDBC is used to connect to a back-end database.
EXPERIMENT NO 10: TO PERFORM MULTITHREADED ECHO SERVER AND CLIENT
To develop a multithreaded echo server and a corresponding client.
LEARNING OBJECTIVES
To understand the need of developing JAVA applications.
To learn the object oriented programming concepts and exception handling
To learn the protocol handling and its functions.
GENERAL PROCEDURE FOR EXECUTING PROGRAMS
First of all the source code gets compiled and the class file is genearted i.e.byte
code(machine language).Then the byte code generated using java compiler and combines them
into a single executable program. Now when the program is executed then the .java file is first
loaded into the memory and then executed by the processor.
In short the steps are:
1.Compilation
2.Byte code generation
3.Loading
4.execution
11
SEC
CSE/V
JAVA LAB MANUAL
CHAPTER V
EX NO: 1
TO IMPLEMENT RATIONAL NUMBER CLASS IN JAVA
DESCRIPTION ABOUT THE EXPERIMENT
To develop a rational number class in Java. We also use JavaDoc comments
for documentation of the rational number.
Objective
The implementation should use efficient representation for a rational number. A Rational
class that extended java.math package. We add the fractions with the methods that declared in the
rational class.
How it is being achieved?
For a rational number, i.e. (500 / 1000) should be represented as (½)
Syntax & keywords
Returns the rational number:
return this.times(b.reciprocal());
HOW TO EXECUTE THE SOURCE CODE

Create a java program and save it using the class name as sample.java file.

Then compile sample.java using the command – javac sample.java

Run the java program to get the output using the command – java sample
12
SEC
CSE/V
JAVA LAB MANUAL
REQUIREMENTS FOR EXECUTION
S.No.
Facilities required
Quantity
1
System
1
2
O/S
Windws 98
3
Compiler
JAVA
EXPECTED OUTPUT AND ITS FORM
This program takes numerator and denominator values as input and display the reciprocal
as output
ADVANTAGES


An fast incremental program
Use only integer calculations
ALGORITHM
Step 1: Start the program.
Step 2: Define a class with two integer data fields’ numerator and denominator.
Step 3: Define a constructor to initialize the rational number and to simplify it.
Step 4: Define methods to perform the basic arithmetic operations such as addition, subtraction,
multiplication, division and reciprocal.
Step 5: Call the appropriate functions with the corresponding arguments and display the result.
Step 6: Stop the program.
PROGRAM :
import java.io.*;
import java.math.*;
13
SEC
CSE/V
JAVA LAB MANUAL
public class TestRationalClass
{
private int num;
private int den;
public TestRationalClass(int numerator,int denominator)
{
if(denominator==0)
{
throw new RuntimeException("denominator is zero!");
}
int g=gcd(numerator,denominator);
num=numerator /g;
den=denominator /g;
}
public String toString()
{
if(den==1)
{
return(num+" ");
}
else
{
return(" "+den);
14
SEC
CSE/V
JAVA LAB MANUAL
}}
public TestRationalClass times(TestRationalClass b)
{
return new TestRationalClass(this.num*b.num,this.den*b.den);
}
public TestRationalClass plus(TestRationalClass b)
{
int numerator=(this.num*b.den)+(this.den*b.num);
int denominator=this.den*b.den;
return new TestRationalClass(numerator,denominator);
}
public TestRationalClass subtract(TestRationalClass b)
{
int numerator=(this.num*b.den)-(this.den*b.num);
int denominator=this.den*b.den;
return new TestRationalClass(numerator,denominator);
}
public TestRationalClass reciprocal()
{
return new TestRationalClass(den,num);
}
public TestRationalClass divides(TestRationalClass b)
15
SEC
CSE/V
JAVA LAB MANUAL
{
return this.times(b.reciprocal());
}
private static int gcd(int m,int n)
{
if(0==n)
return m;
else
return(gcd(n,m%n));
}
public static void main(String [] args)
{
TestRationalClass r1=new TestRationalClass(16,2);
TestRationalClass r2=new TestRationalClass(12,3);
System.out.println("Rational numbers class");
System.out.println(r1 +" + "+r2+ " = "+r1.plus(r2));
System.out.println(r1 +" - "+r2+ " = "+r1.subtract(r2));
System.out.println(r1 +" * "+r2+ " = "+r1.times(r2));
System.out.println(r1 +" / "+r2+ " = "+r1.divides(r2));
}
}
16
SEC
CSE/V
JAVA LAB MANUAL
OUTPUT:
RESULT
Thus the program to develop a rational number class with methods to perform the basic
arithmetic operations was executed and the output was verified successfully
VIVA QUESTIONS
1.Define rational number?
For some types of numerical calculation it is useful to work with rational numbers. These
are numbers whose value is expressed as the ratio or quotient of two integers. This means that
many fractional values (such as 1/7 and 2/3) can be stored exactly, something that isn't possible
using normal floating point numbers.
2. Define a constructor?
A constructor is a special method of a class or structure in object-oriented programming
that initializes an object of that type. A constructor is an instance method that usually has the same
name as the class, and can be used to set the values of the members of an object, either to default or
to user-defined values.
17
SEC
CSE/V
EX NO: 2
JAVA LAB MANUAL
TO IMPLEMENT DATE CLASS IN JAVA
DESCRIPTION ABOUT THE EXPERIMENT
To develop Date class in Java using JavaDoc comments.
Objective
To develop Date class in Java similar to the one available in java.util package.
How it is being achieved?
Date class develops date to be displayed in short,medium, long ,string formats.
Syntax & keywords
Obtain calendar date using:
Date today=Calendar.getInstance().getTime();
Display date in short format:
DateFormat shortFormatter= SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT);
HOW TO EXECUTE THE SOURCE CODE

Create a java program and save it using the class name as sample.java file.

Then compile sample.java using the command – javac sample.java

Run the java program to get the output using the command – java sample
REQUIREMENTS FOR EXECUTION
S.No.
Facilities required
Quantity
1
System
1
2
O/S
Windows 98
3
Compiler
JAVA
18
SEC
CSE/V
JAVA LAB MANUAL
EXPECTED OUTPUT AND ITS FORM:
This program takes calendar date in an instance as input and display the date as output in
different formats.
ADVANTAGES

Calendar date is displayed .

Date with time is displayed in different formats
ALGORITHM
Step 1: Start the program.
Step 2: Define an object today to the Date class and store the current date in that object.
Step 3: Change the Date Format to Short, Long and Medium and display the date.
Step 4: Convert the Date to String and print it.
Step 5: Stop the program.
19
SEC
CSE/V
JAVA LAB MANUAL
PROGRAM
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class BasicDateFormatting
{
public static void main(String[] args)throws Exception
{
Date today=Calendar.getInstance().getTime();
DateFormat
shortFormatter= SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT);
DateFormatlongFormatter=
SimpleDateFormat.getDateInstance(SimpleDateFormat.LONG);
DateFormat
mediumFormatter=
SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.MEDIUM,SimpleDateFormat.
LONG);
System.out.println(shortFormatter.format(today));
System.out.println(longFormatter.format(today));
System.out.println(mediumFormatter.format(today));
String DateAsText=shortFormatter.format(today);
Date TextAsDate=shortFormatter.parse(DateAsText);
20
SEC
CSE/V
JAVA LAB MANUAL
System.out.println(TextAsDate);
}
}
OUTPUT:
RESULT:
Thus the program to develop a Date class was executed and the output was verified
successfully.
VIVA QUESTIONS
1.What is date class ?
Java provides the Date class available in java.util package, this class encapsulates the
current date and time.The Date class supports two constructors. The first constructor initializes the
object with the current date and time.
2. Application of Java.util package ?
Java.util package contains the collections framework, legacy collection classes, event
model, date and time facilities, internationalization, and miscellaneous utility classes.
21
SEC
CSE/V
EX NO: 3
JAVA LAB MANUAL
TO IMPLEMENT LISP LIKE LIST IN JAVA
DESCRIPTION ABOUT THE EXPERIMENT
To implement Lisp-like list in Java
Objective
To perform the basic operation such as 'car', 'cdr', and 'cons'.
How it is being achieved?
We get the elements in the list and execute the lisp commands.
Syntax & keywords
To get System name in login mode to perform the lisp commands:
Logger.getLogger(LispCommands.class.getName());
LOGGER.info(tokenList[0]);
HOW TO EXECUTE THE SOURCE CODE

Create a java program and save it using the class name as sample.java file.

Then compile sample.java using the command – javac sample.java

Run the java program to get the output using the command – java sample
22
SEC
CSE/V
JAVA LAB MANUAL
REQUIREMENTS FOR EXECUTION
S.No.
Facilities required
Quantity
1
System
1
2
O/S
Windws 98
3
Compiler
JAVA
EXPECTED OUTPUT AND ITS FORM
This program takes respective argument and with functions car,cdr,cons to return
leading element ,list starting from second element , adds element to the front of the list.
ALGORITHM
Step 1: Start the program.
Step 2: Create a class Lisp Commands with a list in it.
Step 3: Define a function parse to write the elements into the list.
Step 4: Define a function car to return the leading element of the list.
Step 5: Define a function cdr to return the list starting from the second element.
Step 6: Define a function cons which adds an element to the front of the list.
Step 7: Call the respective functions with the appropriate arguments.
Step 8: Stop the program.
23
SEC
CSE/V
JAVA LAB MANUAL
PROGRAM:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Logger;
public class LispCommands
{
private String[] tokenList;
private static Logger LOGGER =
Logger.getLogger(LispCommands.class.getName());
public LispCommands()
{
}
private void car()
{
LOGGER.info(tokenList[0]);
}
24
SEC
CSE/V
JAVA LAB MANUAL
private void cdr()
{
List<String> list = Arrays.asList(tokenList);
ArrayList<String> slist = new ArrayList<String>(list);
slist.remove(0);
display(slist);
}
private void cons(String args)
{
List<String> arrayList = new ArrayList<String>(Arrays.asList(tokenList));
arrayList.add(args);
Collections.reverse(arrayList);
display(arrayList);
}
private void parse(String args)
{
ArrayList<String> tokenList = new ArrayList<String>();
25
SEC
CSE/V
JAVA LAB MANUAL
if(args != null)
{
StringTokenizer tokens = new StringTokenizer(args,"[]");
while (tokens.hasMoreElements())
{
StringTokenizer commaTokens
= new StringTokenizer(tokens.nextToken(),",");
while (commaTokens.hasMoreElements())
{
String token = commaTokens.nextToken();
if(token != null && !token.trim().equals(""))
tokenList.add(token.trim());
}
}
}
this.tokenList = tokenList.toArray(new String[0]);
}
private void display(Object result)
{
System.out.println();
26
SEC
CSE/V
JAVA LAB MANUAL
if(result instanceof String)
LOGGER.info(result.toString());
else if(result.getClass().getName().equals("java.util.ArrayList"))
LOGGER.info(result.toString());
}
public static void main(String[] args)
{
LispCommands L = new LispCommands();
L.parse("[3, 0, 2, 5]");
L.car();
L.cdr();
L.cons("7");
}
}
27
SEC
CSE/V
JAVA LAB MANUAL
OUTPUT:
RESULT:
Thus the program to implement Lisp-like list in Java was executed and the output was
verified successfully.
VIVA QUESTIONS
1.Define Lisp Commands?
Lisp is a big and deep language. This quickstart is only intended to get you introduced to
very basic concepts in Lisp, not any of the really cool stuff Lisp does. As such it's geared to how to
do C in Lisp, not good functional style (no closures, no macros). It's enough to get you up to speed
so you can more easily understand a good book (ANSI Common Lisp, etc.)
2.Define logger?
The logger will keep a record of what's happened in your program, so if there's a crash or a
bug later on, you can see what happened. Whether this is recorded to a text file, or to a database
somewhere, will be down to the implementation of your logger.
28
SEC
CSE/V
EX NO:4
JAVA LAB MANUAL
TO DESIGN A JAVA INTERFACE FOR ADT STACK
DESCRIPTION ABOUT THE EXPERIMENT
To design a Java interface for ADT Stack and to develop two different classes that
implements this interface, one using array and the other using linked-list.
Objective
Java interface is developed for the stack to implement its operations using array or linked list interface.
How it is being achieved?
The elements are filled in the array or linked list to implement the ADT Stack functions.
Syntax & keywords
Using Linked list- Input obtained from keyboard using the syntax
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
In a loop the stack elements are inserted in the list
System.out.println("Enter the element");
int ele=Integer.parseInt(br.readLine());
stack[++top]=ele;
HOW TO EXECUTE THE SOURCE CODE

Create a java program and save it using the class name as sample.java file.

Then compile sample.java using the command – javac sample.java

Run the java program to get the output using the command – java sample
29
SEC
CSE/V
JAVA LAB MANUAL
REQUIREMENTS FOR EXECUTION
S.No.
Facilities required
Quantity
1
System
1
2
O/S
Windows 98
3
Compiler
JAVA
EXPECTED OUTPUT AND ITS FORM
This program is used to perform the PUSH, POP functions of stack using array or
linked list interfaces.
ALGORITHM
Step 1: Start the program.
Step 2: Design an interface for Stack ADT with functions push, pop and display.
Step 3: Define a class to implement the stack using array.
Step 4: Define the functions of the interface accordingly and handle the stack overflow and
underflow exceptions.
Step 5: Define a class to implement the stack using linked list.
Step 6: Define the functions of the interface accordingly and handle the exceptions.
Step 7: Stop the program.
30
SEC
CSE/V
JAVA LAB MANUAL
PROGRAM:
import java.io.*;
import java.util.*;
interface Mystack
{
public void pop();
public void push();
public void display();
}
class Stack_array implements Mystack
{
final static int n=5;
int stack[]=new int[n];
int top=-1;
public void push()
{
try
{
BufferedReader
br=new BufferedReader(new InputStreamReader(System.in));
31
SEC
CSE/V
JAVA LAB MANUAL
if(top==(n-1))
{
System.out.println(" Stack Overflow");
return;
}
else
{
System.out.println("Enter the element");
int ele=Integer.parseInt(br.readLine());
stack[++top]=ele;
}
}
catch(IOException e)
{
System.out.println("e");
}
}
32
SEC
CSE/V
JAVA LAB MANUAL
public void pop()
{
if(top<0)
{
System.out.println("Stack underflow");
return;
}
else
{
int popper=stack[top];
top--;
System.out.println("Popped element:" +popper);
}
}
public void display()
{
33
SEC
CSE/V
JAVA LAB MANUAL
if(top<0)
{
System.out.println("Stack is empty");
return;
}
else
{
String str=" ";
for(int i=0;i<=top;i++)
str=str+" "+stack[i]+" <--";
System.out.println("Elements are:"+str);
}
}
}
class Link
{
public int data;
public Link nextLink;
34
SEC
CSE/V
JAVA LAB MANUAL
public Link(int d)
{
data= d;
nextLink=null;
}
public void printLink()
{
System.out.print(" --> "+data);
}
}
class Stack_List implements Mystack
{
private Link first;
public Stack_List()
{
first = null;
}
35
SEC
CSE/V
JAVA LAB MANUAL
public boolean isEmpty()
{
return first == null;
}
public void push()
{
try
{
BufferedReaderbr=newBufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the element");
int ele=Integer.parseInt(br.readLine());
Link link = new Link(ele);
link.nextLink = first;
first = link;
}
catch(IOException e)
{
System.err.println(e);
}
36
SEC
CSE/V
JAVA LAB MANUAL
}
public Link delete()
{
Link temp = first;
try
{
first = first.nextLink;
}
catch(NullPointerException e)
{
throw e;
}
return temp;
}
public void pop()
{
try
{
Link deletedLink = delete();
37
SEC
CSE/V
JAVA LAB MANUAL
System.out.println("Popped: "+deletedLink.data);
}
catch(NullPointerException e)
{
throw e;
}
}
public void display()
{
if(first==null)
System.out.println("Stack is empty");
else
{
Link currentLink = first;
System.out.print("Elements are: ");
while(currentLink != null)
{
currentLink.printLink();
currentLink = currentLink.nextLink;
}
38
SEC
CSE/V
JAVA LAB MANUAL
System.out.println("");
}
}
}
class StackADT
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Implementation of Stack using Array");
Stack_array stk=new Stack_array();
int ch=0;
do
{
System.out.println("1.Push 2.Pop 3.Display");
System.out.println("Enter your choice:");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
39
SEC
CSE/V
JAVA LAB MANUAL
case 1:
stk.push();
break;
case 2:
stk.pop();
break;
case 3:
stk.display();
break;
}
}while(ch<4);
System.out.println("Implementation of Stack using Linked List");
Stack_List stk1=new Stack_List();
ch=0;
do
{
System.out.println("1.Push 2.Pop 3.Display");
System.out.println("Enter your choice:");
ch=Integer.parseInt(br.readLine());
40
SEC
CSE/V
JAVA LAB MANUAL
switch(ch)
{
case 1:
stk1.push();
break;
case 2:
try
{
stk1.pop();
}
catch(NullPointerException e)
{
System.out.println("Stack underflown");
}
break;
case 3:
stk1.display();
break;
}
41
SEC
CSE/V
JAVA LAB MANUAL
}while(ch<4);
}
}
OUTPUT:
RESULT:
Thus the program to implement Stack ADT using array and linked list was executed
and the output was verified successfully.
42
SEC
CSE/V
JAVA LAB MANUAL
VIVA QUESTIONS
1.Define interfaces?
objects define their interaction with the outside world through the methods that they expose.
Methods form the object's interface with the outside world; the buttons on the front of your
television set, for example, are the interface between you and the electrical wiring on the other side
of its plastic casing. You press the "power" button to turn the television on and off.
2.Define stack underflow?
Stack underflow doesn't happen in Java. Its runtime system is supposed to prevent that sort
of stuff from happening.
43
SEC
CSE/V
JAVA LAB MANUAL
TO DESIGN A VEHICLE CLASS HIERARCHY IN JAVA
EX NO: 5
DESCRIPTION ABOUT THE EXPERIMENT
To design a Vehicle class hierarchy in Java and to demonstrate polymorphism which is one
of the object oriented programming concept.
Objective
Vehicle class is created with subclasses two wheeler , three wheeler, four wheeler
subclasses to implement the vehicle class hierarchy.
How it is being achieved?
Vehicle class is defined as the super class and connected with subclasses along with its
methods and objects.
Syntax & keywords:
Subclass two wheeler is defined :
Twowheeler(String r,int m,int n)
{
super(r,m);
noofwheel=n;
}
HOW TO EXECUTE THE SOURCE CODE

Create a java program and save it using the class name as sample.java file.

Then compile sample.java using the command – javac sample.java

Run the java program to get the output using the command – java sample
44
SEC
CSE/V
JAVA LAB MANUAL
REQUIREMENTS FOR EXECUTION
S.No.
Facilities required
Quantity
1
System
1
2
O/S
Windows 98
3
Compiler
JAVA
EXPECTED OUTPUT
Create objects for the subclasses and call the appropriate methods. The subclasses define a
method named display that overrides the super class method.\
ADVANTAGES
1) Object oriented Concept - Polymorphism is implemented with inheritance concept.
2) Overriden of methods from subclass to superclass is learnt.
ALGORITHM
Step 1: Start the program.
Step 2: Define a class Vehicle with fields register no. and model.
Step 3: Define a method display which displays all the data fields.
Step 4: Define the classes namely Twowheeler, Threewheeler and Fourwheeler as subclasses of
Vehicle class.
Step 5: These subclasses defines a method named display that overrides the super class method.
Step 6: Create objects for the subclasses and call the appropriate methods.
Step 7: Stop the program.
45
SEC
CSE/V
JAVA LAB MANUAL
PROGRAM:
import java.io.*;
class Vehicle
{
String regno;
int model;
Vehicle(String r, int m)
{
regno=r;
model=m;
}
void display()
{
System.out.println("Registration no: "+regno);
System.out.println("Model no: "+model);
}
}
class Twowheeler extends Vehicle
{
int noofwheel;
Twowheeler(String r,int m,int n)
{
46
SEC
CSE/V
JAVA LAB MANUAL
super(r,m);
noofwheel=n;
}
void display()
{
System.out.println("Two wheeler tvs");
super.display();
System.out.println("No. of wheel : " +noofwheel);
}
}
class Threewheeler extends Vehicle
{
int noofleaf;
Threewheeler(String r,int m,int n)
{
super(r,m);
noofleaf=n;
}
void display()
{
System.out.println("Three wheeler auto");
super.display();
47
SEC
CSE/V
JAVA LAB MANUAL
System.out.println("No. of leaf:" +noofleaf);
}
}
class Fourwheeler extends Vehicle
{
int noofleaf;
Fourwheeler(String r,int m,int n)
{
super(r,m);
noofleaf=n;
}
void display()
{
System.out.println("Four wheeler car");
super.display();
System.out.println("No. of leaf:" +noofleaf);
}
}
public class Vehicledemo
{
public static void main(String arg[])
{
Twowheeler t1;
48
SEC
CSE/V
JAVA LAB MANUAL
Threewheeler th1;
Fourwheeler f1;
t1=new Twowheeler("TN74 12345", 1,2);
th1=new Threewheeler("TN74 54321", 4,3);
f1=new Fourwheeler("TN34 45677",5,4);
t1.display();
th1.display();
f1.display();
}
}
49
SEC
CSE/V
JAVA LAB MANUAL
OUTPUT:
RESULT:
Thus the program to design vehicle class hierarchy and to demonstrate
polymorphism was executed and the output was verified successfully.
VIVA QUESTIONS
1.Define class hierarchy?
class is a template that defines the state and behavior common to objects of a certain kind.
A class can be defined in terms of other classes. For example, a truck and a racing car are both
examples of a car.
2.Define polymorphism?
polymorphism is the characteristic of being able to assign a different meaning or usage to
something in different contexts - specifically, to allow an entity such as a variable, a function, or an
object to have more than one form
50
SEC
CSE/V
JAVA LAB MANUAL
RANDOM GENERATION OF OBJECTS
EX NO: 6
DESCRIPTION ABOUT THE EXPERIMENT
To design classes namely Currency, Rupee, and Dollar. To write a program that randomly
generates Rupee and Dollar objects .
Objective
The program randomly generates Rupee and Dollar objects and writes them into a file using
object serialization. To write another program to read that file, and to convert to Rupee if it reads a
Dollar, while leave the value as it is if it reads a Rupee.
HOW IT IS BEING ACHIEVED?
Define a class Currency as an abstract class with abstract methods. The classes Rupee and
Dollar are defined as subclasses of Currency . The dollar value is converted to equivalent rupee
value within a method of Dollar class.
Syntax & keywords
Equivalent conversion of Dollar to Rupee
if ( (decide%2)==0 )
currency = new Rupee(value);
else
currency = new Dollar(value);
out.writeObject(currency);
HOW TO EXECUTE THE SOURCE CODE

Create a java program and save it using the class name as sample.java file.

Then compile sample.java using the command – javac sample.java

Run the java program to get the output using the command – java sample
51
SEC
CSE/V
JAVA LAB MANUAL
REQUIREMENTS FOR EXECUTION
S.No.
Facilities required
Quantity
1
System
1
2
O/S
Windows 98
3
Compiler
JAVA
EXPECTED OUTPUT AND ITS FORM
The program converts the dollar value to currency or else print
the currency present in rupee value.
ADVANTAGES

Object serialization concept is learnt.

Inheritance concept is applied with super and sub classes defined.
ALGORITHM
Step 1: Start the programs.
Step 2: Define a class Currency as an abstract class with abstract methods.
Step 3: Define the classes Rupee and Dollar as subclasses of Currency.
Step 4: Define the abstract methods of the super class accordingly in each subclass.
Step 5: The dollar value is converted to equivalent rupee value within a method of Dollar class.
Step 6: Define a class StoreCurrency that randomly generates objects of Rupee and Dollar classes.
Step 7: These objects are written into a file named currency using object serialization.
Step 8: Define a class ReadCurrency that reads the objects from the file currency, and displays
them.
52
SEC
CSE/V
JAVA LAB MANUAL
Step 9: Stop the programs.
PROGRAM:
Currency.java
import java.io.Serializable;
public abstract class Currency implements Serializable
{
protected static final Double DOLLAR_RUPEE_EXCHAGERATE = 44.445D;
public Currency(Double money)
{
super();
this.money = money;
}
protected Double money;
public abstract Double getValue ();
public abstract String getPrintableValue();
}
Rupee.java
public class Rupee extends Currency
{
53
SEC
CSE/V
JAVA LAB MANUAL
public Rupee(Double amount)
{
super(amount);
}
public Double getValue()
{
return this.money;
}
public String getPrintableValue()
{
String strValue = "Object Name : Rupee \nINR : Rs " + getValue() + "\n-----------------\n";
return strValue;
}
}
Dollar.java
public class Dollar extends Currency
{
public Dollar(Double money)
{
super(money);
}
54
SEC
CSE/V
JAVA LAB MANUAL
public Double getValue()
{
return (this.money * DOLLAR_RUPEE_EXCHAGERATE);
}
public String getPrintableValue()
{
String strValue = "Object Name : Dollar \nUSD : $" + this.money + " \nINR : Rs" +
getValue() + "\n------------------\n";
return strValue;
}
}
StoreCurrency.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Random;
public class StoreCurrency
{
public static void main(String[] args) throws FileNotFoundException,IOException
{
55
SEC
CSE/V
JAVA LAB MANUAL
Currency currency = null;
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream(new File("currency.dat")));
Random random = new Random();
for (int i = 0; i < 10; i++)
{
int decide = random.nextInt();
Double value = (random.nextDouble() *10);
if ( (decide%2)==0 )
currency = new Rupee(value);
else
currency = new Dollar(value);
out.writeObject(currency);
}
out.writeObject(null);
out.close();
}
}
ReadCurrency.java
import java.io.File;
import java.io.FileInputStream;
56
SEC
CSE/V
JAVA LAB MANUAL
import java.io.IOException;
import java.io.ObjectInputStream;
public class ReadCurrency
{
public static void main(String[] args) throws IOException, ClassNotFoundException
{
Currency currency = null;
ObjectInputStream in = new ObjectInputStream(new FileInputStream(new
File("currency.dat")));
while ((currency = (Currency) in.readObject()) != null)
{
System.out.println(currency.getPrintableValue());
}
in.close();
}
}
57
SEC
CSE/V
JAVA LAB MANUAL
OUTPUT:
RESULT:
Thus the program to generate objects randomly and to write them into a file using
object serialization was executed. The file was read and the required rupee-dollar conversions were
performed and the output was verified successfully.
58
SEC
CSE/V
JAVA LAB MANUAL
VIVA QUESTIONS:
1.Define subclasses?
A subclass is a class that derives from another class. A subclass inherits state and behavior
from all of its ancestors. The term superclass refers to a class's direct ancestor as well as all of its
ascendant classes.
2.Define inheritance?
Inheritance is a mechanism wherein a new class is derived from an existing class. In Java,
classes may inherit or acquire the properties and methods of other classe
59
SEC
CSE/V
JAVA LAB MANUAL
TO IMPLEMENT CALCULATOR IN JAVA
EX NO: 7
DESCRIPTION ABOUT THE EXPERIMENT:
To design a calculator using event-driven programming paradigm of Java.
Objective
The calculator is designed with frames and buttons to have the components aligned in
the layout .
How it is being achieved?
Buttons represent the numbers addition, subtraction ,multiplication ,division, equals
operations . To display the result a textbox is provided .
Syntax & keywords:
Addition Performed using the syntax:
public void add(String n)
{
_currentTotal += convertToNumber(n);
}
HOW TO EXECUTE THE SOURCE CODE

Create a java program and save it using the class name as sample.java file.

Then compile sample.java using the command – javac sample.java

Run the java program to get the output using the command – java sample
60
SEC
CSE/V
JAVA LAB MANUAL
REQUIREMENTS FOR EXECUTION
S.No.
Facilities required
Quantity
1
System
1
2
O/S
Windows 98
3
Compiler
JAVA
EXPECTED OUTPUT AND ITS FORM
This program is used to perform the arithmetic operations like addition,
subtraction, multiplication, division using the calculator.
ALGORITHM
Step 1: Start the program.
Step 2: Create a frame for the calculator and include the swing components such as buttons and text
field as required in it.
Step 3: Layouts such as Border Layout and Grid Layout are used to align the components as per the
requirements of the calculator.
Step 4: Redefine the actionPerformed() method in the ActionListener interface to perform the
appropriate operations when the buttons are pressed.
Step 5: Provide mechanisms to handle the Number Format exceptions that may occur.
Step 6: Stop the program.
61
SEC
CSE/V
JAVA LAB MANUAL
PROGRAM:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class Calculator extends JFrame
{
private static final Font BIGGER_FONT = new Font("monspaced", Font.PLAIN, 20);
private JTextField _displayField;
private boolean _startNumber = true;
private String _previousOp ="=";
private CalcLogic _logic = new CalcLogic();
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception unused)
{
}
Calculator window = new Calculator();
62
SEC
CSE/V
JAVA LAB MANUAL
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
public Calculator()
{
_displayField = new JTextField("0", 12);
_displayField.setHorizontalAlignment(JTextField.RIGHT);
_displayField.setFont(BIGGER_FONT);
JButton clearButton = new JButton("Clear");
clearButton.setFont(BIGGER_FONT);
clearButton.addActionListener(new ClearListener());
ActionListener numListener = new NumListener();
String buttonOrder = "789456123 0 ";
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(5, 3, 2, 2));
for (int i = 0; i < buttonOrder.length(); i++)
{
String keyTop = buttonOrder.substring(i, i+1);
JButton b = new JButton(keyTop);
if (keyTop.equals(" "))
{
b.setEnabled(false);
63
SEC
CSE/V
}
JAVA LAB MANUAL
else
{
b.addActionListener(numListener);
b.setFont(BIGGER_FONT);
}
buttonPanel.add(b);
}
ActionListener opListener = new OpListener();
JPanel opPanel = new JPanel();
opPanel.setLayout(new GridLayout(5, 1, 2, 2));
String[] opOrder = {"+", "-", "*", "/", "="};
for (int i = 0; i < opOrder.length; i++)
{
JButton b = new JButton(opOrder[i]);
b.addActionListener(opListener);
b.setFont(BIGGER_FONT);
opPanel.add(b);
}
JPanel clearPanel = new JPanel();
clearPanel.setLayout(new FlowLayout());
clearPanel.add(clearButton);
JPanel content = new JPanel();
content.setLayout(new BorderLayout(5, 5));
64
SEC
CSE/V
JAVA LAB MANUAL
content.add(_displayField,BorderLayout.NORTH );
content.add(buttonPanel ,BorderLayout.CENTER);
content.add(opPanel ,BorderLayout.EAST );
content.add(clearPanel ,BorderLayout.SOUTH );
content.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
this.setContentPane(content);
this.pack();
this.setTitle("Calculator");
this.setResizable(false);
}
private void actionClear()
{
_startNumber = true;
_displayField.setText("0");
_previousOp = "=";
_logic.setTotal("0");
}
class OpListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
65
SEC
CSE/V
JAVA LAB MANUAL
if (_startNumber)
{
actionClear();
_displayField.setText("ERROR - No operator");
}
else
{
_startNumber = true;
try
{
String displayText = _displayField.getText();
if (_previousOp.equals("="))
_logic.setTotal(displayText);
else if (_previousOp.equals("+"))
_logic.add(displayText);
else if (_previousOp.equals("-"))
_logic.subtract(displayText);
else if (_previousOp.equals("*"))
_logic.multiply(displayText);
else if (_previousOp.equals("/"))
_logic.divide(displayText);
_displayField.setText("" + _logic.getTotalString());
}
66
SEC
CSE/V
JAVA LAB MANUAL
catch (NumberFormatException ex)
{
actionClear();
_displayField.setText("Error");
}
_previousOp = e.getActionCommand();
}
}
}
class NumListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String digit = e.getActionCommand();
if (_startNumber)
{
_displayField.setText(digit);
_startNumber = false;
}
67
SEC
CSE/V
JAVA LAB MANUAL
else
{
_displayField.setText(_displayField.getText() + digit);
}
}
}
class ClearListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
actionClear();
}
}
}
class CalcLogic
{
private int _currentTotal;
public CalcLogic()
{
_currentTotal = 0;
}
68
SEC
CSE/V
JAVA LAB MANUAL
public String getTotalString()
{
return "" + _currentTotal;
}
public void setTotal(String n)
{
_currentTotal = convertToNumber(n);
}
public void add(String n)
{
_currentTotal += convertToNumber(n);
}
public void subtract(String n)
{
_currentTotal -= convertToNumber(n);
}
public void multiply(String n)
{
_currentTotal *= convertToNumber(n);
}
69
SEC
CSE/V
JAVA LAB MANUAL
public void divide(String n)
{
_currentTotal /= convertToNumber(n);
}
private int convertToNumber(String n)
{
return Integer.parseInt(n);
}
}
OUTPUT:
70
SEC
CSE/V
JAVA LAB MANUAL
RESULT:
Thus the program to design a calculator was executed and the output was verified
successfully.
VIVA QUESTION:
1. What is swing?
Swing provides set of GUI components . Provides native application with look and feel
layout . Powerful and flexible than AWT components.
2. Define border layout?
A layout manager which divides the area into center, north, south, east, and
west regions.
71
SEC
CSE/V
JAVA LAB MANUAL
TO IMPLEMENT MULTITHREADING IN JAVA
EX NO: 8
DESCRIPTION ABOUT THE EXPERIMENT:
To write a program in Java that prints all the prime numbers in the Fibonacci series below
10000 using multithreading.
Objective:
The main Objective is to create multiple threads and manage it . Two threads are created
and integrated with main thread.
How it is being achieved?
Create a thread called Prime Thread to stores all the prime numbers below 10000. Create
another thread called Fibonacci to stores the elements of the Fibonacci series below 10000. The
main thread reads the values stored by both the threads, checks for the common elements and print.
Syntax & keywords
Prime numbers in fibonacci series
for(int i=0;p.num[i]!=-1;i++)
{
for(int j=0;f.num[j]!=-1;j++)
{
if(p.num[i]==f.num[j])
{
System.out.println(p.num[i]);
break;
72
SEC
CSE/V
JAVA LAB MANUAL
HOW TO EXECUTE THE SOURCE CODE

Create a java program and save it using the class name as sample.java file.

Then compile sample.java using the command – javac sample.java

Run the java program to get the output using the command – java sample
REQUIREMENTS FOR EXECUTION :
S.No.
Facilities required
Quantity
1
System
1
2
O/S
Windows 98
3
Compiler
JAVA
EXPECTED OUTPUT AND ITS FORM :
The program is used to print the prime numbers present in fibonacci series with the
functions of multithreading.
ALGORITHM:
Step 1: Start the program.
Step 2: Create a thread called Prime Thread that stores all the prime numbers below 10000.
Step 3: Create another thread called Fibonacci Thread that stores the elements of the Fibonacci
series below 10000.
Step 4: Prime Thread and Fibonacci Thread are assigned a higher priority than the main thread of
the program.
Step 5: The main thread reads the values stored by both the threads, checks for the common
elements and prints them.
Step 6: Stop the program.
73
SEC
CSE/V
JAVA LAB MANUAL
PROGRAM:
interface maxlimit
{
public static final int MAX_LIMIT=10000;
}
class prime extends Thread implements maxlimit
{
int num[]=new int[MAX_LIMIT];
prime(String n)
{
super(n);
for(int i=0;i<MAX_LIMIT;i++)
num[i]=-1;
}
public void run()
{
int k=0,flag;
for(int i=2;i<=MAX_LIMIT;i++)
{
flag=0;
for(int j=2;j<i;j++)
{
74
SEC
CSE/V
JAVA LAB MANUAL
if(i%j==0)
{
flag=1;
break;
}
}
if(flag==0)
{
num[k]=i;
k++;
}
}
}
}
class fibonacci extends Thread implements maxlimit
{
int num[]=new int[MAX_LIMIT];
fibonacci(String n)
{
super(n);
75
SEC
CSE/V
JAVA LAB MANUAL
for(int i=0;i<MAX_LIMIT;i++)
num[i]=-1;
}
public void run()
{
int f1=-1,f2=1,f3=0,k=0;
while(f3<=MAX_LIMIT)
{
f3=f1+f2;
num[k]=f3;
k++;
f1=f2;
f2=f3;
}
}
}
class primefibi
{
public static void main(String arg[])
{
76
SEC
CSE/V
JAVA LAB MANUAL
prime p=new prime("Prime Thread");
fibonacci f=new fibonacci("Fibonacci Thread");
p.setPriority(9);
f.setPriority(9);
p.start();
f.start();
System.out.println("Prime numbers in fibonacci series");
for(int i=0;p.num[i]!=-1;i++)
{
for(int j=0;f.num[j]!=-1;j++)
{
if(p.num[i]==f.num[j])
{
System.out.println(p.num[i]);
break;
}
}
}
}
}
77
SEC
CSE/V
JAVA LAB MANUAL
OUTPUT:
RESULT:
Thus the program to print the prime numbers in the Fibonacci series using multithreading
was executed and the output was verified successfully.
VIVA QUESTIONS:
1.Define Multithreading?
Multithreading is a type of execution model that allows multiple threads to exist within
the context of a process such that they execute independently but share their process resources.
2.Define Fibonacci series?
Sequence of numbers in which 1 appears twice as the first two numbers, and every
subsequent number is the sum of two preceding numbers: 1, 1, 2, 3, 5, 8, 13 ... and so on.
78
SEC
CSE/V
EX NO:9
JAVA LAB MANUAL
SIMPLE OPAC SYSTEM FOR LIBRARY
DESCRIPTION ABOUT THE EXPERIMENT:
To develop a simple OPAC system for library using event-driven and concurrent
programming paradigms of Java. JDBC is used to connect to a back-end database.
Objective:
The main Objective is to develop OPAC (online public access catalog) system
for library management . We use database connectivity to access the data objects.
How it is being achieved?
The front end form is created to get the data and the back end database is used to store the
data and displayed. Database is connected using JDBC(java database connectivity). JDBC is Java
application programming interface that allows the Java programmers to access database
management system from Java code. It was developed by JavaSoft, a subsidiary of Sun
Microsystems.
Syntax & keywords
JDBC connection syntax:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:custo");
stat = conn.createStatement();
res = stat.executeQuery("Select * from stu");
res.next();
79
SEC
CSE/V
JAVA LAB MANUAL
HOW TO EXECUTE THE SOURCE CODE

Create a java program and save it using the class name as sample.java file.

Then compile sample.java using the command – javac sample.java

Run the java program to get the output using the command – java sample
REQUIREMENTS FOR EXECUTION :
S.No.
Facilities required
Quantity
1
System
1
2
O/S
Windows 98
3
Compiler
JAVA
EXPECTED OUTPUT AND ITS FORM :
This program converts the manual entry and usage of library system .OPAC helps us to access
the library assets dynamically similar to digital library.
APPLICATIONS:
Library management system.
ALGORITHM
Step 1: Start the program.
Step 2: Design the front end for the library system.
Step 3: Connect the front end with the database at the backend using JDBC.
Step 4: Design the front end such that it accepts the inputs from the user and inserts the records into
the database.
80
SEC
CSE/V
JAVA LAB MANUAL
Step 5: Display the contents of the database at the front end.
Step 6: Suspend the established connections.
Step 7: Stop the program.
PROGRAM: Datas.java
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Datas extends JFrame implements ActionListener
{
JTextField id;
JTextField name;
JButton next;
JButton addnew;
JPanel p;
static ResultSet res;
static Connection conn;
static Statement stat;
public Datas()
{
super("Our Application");
81
SEC
CSE/V
JAVA LAB MANUAL
Container c = getContentPane();
c.setLayout(new GridLayout(5,1));
id = new JTextField(20);
name = new JTextField(20);
next = new JButton("Next BOOK");
p = new JPanel();
c.add(new JLabel("ISBN",JLabel.CENTER));
c.add(id);
c.add(new JLabel("Book Name",JLabel.CENTER));
c.add(name);
c.add(p);
p.add(next);
next.addActionListener(this);
pack();
setVisible(true);
addWindowListener(new WIN());
}
public static void main(String args[])
{
Datas d = new Datas();
try
{
82
SEC
CSE/V
JAVA LAB MANUAL
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:custo");
stat = conn.createStatement();
res = stat.executeQuery("Select * from stu");
res.next();
}
catch(Exception e)
{
System.out.println("Error" +e);
}
d.showRecord(res);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == next)
{
try
{
res.next();
}
catch(Exception ee)
{
}
83
SEC
CSE/V
JAVA LAB MANUAL
showRecord(res);
}
}
public void showRecord(ResultSet res)
{
try
{
id.setText(res.getString(2));
name.setText(res.getString(3));
}
catch(Exception e)
{
}
}
class WIN extends WindowAdapter
{
public void windowClosing(WindowEvent w)
{
JOptionPane jop = new JOptionPane();
jop.showMessageDialog(null,"Database","Thanks",JOptionPane.QUESTION_MESSAGE);
}
}}
84
SEC
CSE/V
JAVA LAB MANUAL
Prog1.java
import java.sql.*;
import java.sql.DriverManager.*;
class Ja
{
String bookid,bookname;
int booksno;
Connection con;
Statement stmt;
ResultSet rs;
Ja()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:co");
}
catch(Exception e)
{
System.out.println("connection error");
}
}
85
SEC
CSE/V
JAVA LAB MANUAL
void myput()
{
try
{
stmt=con.createStatement();
rs=stmt.executeQuery("SELECT * FROM opac");
while(rs.next())
{
booksno=rs.getInt(1);
bookid=rs.getString(2);
bookname=rs.getString(3);
System.out.println("\n"+ booksno+"\t"+bookid+"\t"+bookname);
}
rs.close();
stmt.close();
con.close();
}
catch(SQLException e)
{
System.out.println("sql error");
}
}
}
86
SEC
CSE/V
JAVA LAB MANUAL
class prog1
{
public static void main(String arg[])
{
Ja j=new Ja();
j.myput();
}
}
OUTPUT:
87
SEC
CSE/V
JAVA LAB MANUAL
RESULT:
Thus the program to design a simple OPAC system for library was executed and the output
was verified successfully.
88
SEC
CSE/V
JAVA LAB MANUAL
VIVA QUESTIONS:
1.Define OPAC?
An OPAC (Online Public Access Catalog) is an online bibliography of a library collection that
is available to the public.
2.Define JDBC?
(Java DataBase Connectivity) A programming interface that lets Java applications access a
database via the SQL language. Since Java interpreters (Java Virtual Machines) are available for all
major client platforms, this allows a platform-independent database application to be written
89
SEC
CSE/V
EX NO: 10
JAVA LAB MANUAL
TO IMPLEMENT MULTITHREADED ECHO SERVER & CLIENT
DESCRIPTION ABOUT THE EXPERIMENT:
To develop a multithreaded echo server and a corresponding client. It is achieved using multiple
threads created with multiple clients connected to a single server thread.
Objective:
The main Objective is to echo that is to display the message sent from client to
server.Single server manages multiple clients and display corresponding messages
received.
How it is being achieved?
Multiple threads created are linked with a single main thread . In coordination
multithreaded concept is handled along with exception handling mechanisms.
Syntax and keywords:
To echo the message :
OutputStreamWriter(s.getOutputStream()));
out.println("Hello");
out.flush();
HOW TO EXECUTE THE SOURCE CODE

Create a java program and save it using the class name as sample.java file.

Then compile sample.java using the command – javac sample.java

Run the java program to get the output using the command – java sample
90
SEC
CSE/V
JAVA LAB MANUAL
REQUIREMENTS FOR EXECUTION :
S.No.
Facilities required
Quantity
1
System
1
2
O/S
Windows 98
3
Compiler
JAVA
EXPECTED OUTPUT AND ITS FORM :
This program displays the string using multithreaded concept executed between client and server
communication.
ALGORITHM
Step 1: Start the program.
Step 2: Create a Socket at the Server side.
Step 3: Design the server such that it responds to each client using a separate thread.
Step 4: The server receives the data sent by the client and echoes those data.
Step 5: Provide the necessary exception handling mechanisms at the server.
Step 6: Create a Socket at the client side.
Step 7: Get the host name from the user.
Step 8: Establish a connection between the server and the client.
Step 9: Transmit the data from the client side to the server.
Step 10: Provide the necessary exception handling mechanisms at the client.
91
SEC
CSE/V
JAVA LAB MANUAL
Step 11: Stop the program.
PROGRAM:
EchoServer.java
import java.net.*;
import java.io.*;
public class EchoServer
{
ServerSocket m_ServerSocket;
public EchoServer()
{
try
{
m_ServerSocket = new ServerSocket(12111);
}
catch(IOException ioe)
{
System.out.println("Could not create server socket at 12111. Quitting.");
System.exit(-1);
}
System.out.println("Listening for clients.....");
int id = 0;
while(true)
{
92
SEC
CSE/V
JAVA LAB MANUAL
try
{
Socket clientSocket = m_ServerSocket.accept();
ClientServiceThread cliThread
= new ClientServiceThread(clientSocket, id++);
cliThread.start();
}
catch(IOException ioe)
{
System.out.println("Exception encountered
on accept. Ignoring. Stack Trace :");
ioe.printStackTrace();
}
}
}
public static void main (String[] args)
{
new EchoServer();
}
class ClientServiceThread extends Thread
{
Socket m_clientSocket;
93
SEC
CSE/V
JAVA LAB MANUAL
int m_clientID = -1;
boolean m_bRunThread = true;
ClientServiceThread(Socket s, int clientID)
{
m_clientSocket = s;
m_clientID = clientID;
}
public void run()
{
BufferedReader in = null;
PrintWriter out = null;
System.out.println("Accepted Client : ID - " + m_clientID + " :
Address - " + m_clientSocket.getInetAddress().getHostName());
try
{
in = new BufferedReader(
new InputStreamReader(m_clientSocket.getInputStream()));
out = new PrintWriter(
new OutputStreamWriter(m_clientSocket.getOutputStream()));
while(m_bRunThread)
{
String clientCommand = in.readLine();
System.out.println("Client Says :" + clientCommand);
94
SEC
CSE/V
JAVA LAB MANUAL
if(clientCommand.equalsIgnoreCase("quit"))
{
m_bRunThread = false;
System.out.print("Stopping client thread
for client : " + m_clientID);
}
else
{
out.println(clientCommand);
out.flush();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
95
SEC
CSE/V
JAVA LAB MANUAL
in.close();
out.close();
m_clientSocket.close();
System.out.println("...Stopped");
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
}
EchoClient.java
import java.net.*;
import java.io.*;
public class EchoClient
{
public static void main(String[] args)
{
if(args.length == 0)
{
96
SEC
CSE/V
JAVA LAB MANUAL
System.out.println("Usage : EchoClient <serverName>");
return;
}
Socket s = null;
try
{
s = new Socket(args[0], 12111);
}
catch(UnknownHostException uhe)
{
System.out.println("Unknown Host :" + args[0]);
s = null;
}
catch(IOException ioe)
{
System.out.println("Cant connect to server at 12111. Make sure it is
running.");
s = null;
}
if(s == null)
System.exit(-1);
97
SEC
CSE/V
JAVA LAB MANUAL
BufferedReader in = null;
PrintWriter out = null;
try
{
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
out.println("Hello");
out.flush();
System.out.println("Server Says : " + in.readLine());
out.println("This");
out.flush();
System.out.println("Server Says : " + in.readLine());
out.println("is");
out.flush();
System.out.println("Server Says : " + in.readLine());
out.println("a");
out.flush();
System.out.println("Server Says : " + in.readLine());
out.println("Test");
out.flush();
System.out.println("Server Says : " + in.readLine());
out.println("Quit");
out.flush();
98
SEC
CSE/V
JAVA LAB MANUAL
}
catch(IOException ioe)
{
System.out.println("Exception during communication.
Server probably closed connection.");
}
finally
{
try
{
out.close();
in.close();
s.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
99
SEC
CSE/V
JAVA LAB MANUAL
OUTPUT:
100
SEC
CSE/V
JAVA LAB MANUAL
RESULT:
Thus the program to develop a multithreaded echo server and client was executed and the
output was verified successfully.
VIVA QUESTIONS:
1. Define server?
A server is a a software program, or the computer on which that program runs, that
provides a specific kind of service to client software running on the same computer or other
computers on a network.
2. Define Client?
A client is a piece of computer hardware or software that accesses a service made
available by a server.
101
SEC
CSE/V
JAVA LAB MANUAL
CHAPTER VI
EXPERIMENTS BEYOND THE SYLLABUS
EX NO :1
DEVELOPING A SIMPLE PAINT LIKE PROGRAM USING APPLET
AIM:
To develop a simple paint like program using applet in java.
ALGORITHM:
1. Import the required class and packages.
2. Create a class Drawtest for creating an applet.
3. Initialize panles and controls in the init() method.
4. Define the destroy() method to destroy the same.
5. Create an instance for draw test class and call the init(0 and start() methods in the main
method.
6. Add a new frame to the applet window and resize it to 300x300.
7. Declare a method get applet infor to display the applet information.
8. Declare two constants LINES,POINTS which are going to be the modes.
9. Define the paint method and perfoem the required operations.
10. Display the result according to the mode selected.
102
SEC
CSE/V
JAVA LAB MANUAL
DEVELOPING A SIMPLE PAINT LIKE PROGRAM USING APPLET
import java.awt.event.*;
import java.awt.*;
import java.applet.*;
import java.util.Vector;
public class DrawTest extends Applet{
DrawPanel panel;
DrawControls controls;
public void init() {
setLayout(new BorderLayout());
panel = new DrawPanel();
controls = new DrawControls(panel);
add("Center", panel);
add("South",controls);
}
public void destroy() {
remove(panel);
remove(controls);
}
103
SEC
CSE/V
JAVA LAB MANUAL
public static void main(String args[]) {
Frame f = new Frame("DrawTest");
DrawTest drawTest = new DrawTest();
drawTest.init();
drawTest.start();
f.add("Center", drawTest);
f.setSize(300, 300);
f.show();
}
public String getAppletInfo() {
return "A simple drawing program.";
}
}
class DrawPanel extends Panel implements MouseListener, MouseMotionListener {
public static final int LINES = 0;
public static final int POINTS = 1;
int
mode = LINES;
Vector lines = new Vector();
Vector colors = new Vector();
int x1,y1;
int x2,y2;
104
SEC
CSE/V
JAVA LAB MANUAL
public DrawPanel() {
setBackground(Color.white);
addMouseMotionListener(this);
addMouseListener(this);
}
public void setDrawMode(int mode) {
switch (mode) {
case LINES:
case POINTS:
this.mode = mode;
break;
default:
throw new IllegalArgumentException();
}
}
public void mouseDragged(MouseEvent e) {
e.consume();
switch (mode) {
case LINES:
x2 = e.getX();
y2 = e.getY();
break;
105
SEC
CSE/V
JAVA LAB MANUAL
case POINTS:
default:
colors.addElement(getForeground());
lines.addElement(new Rectangle(x1, y1, e.getX(), e.getY()));
x1 = e.getX();
y1 = e.getY();
break;
}
repaint();
}
public void mouseMoved(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
e.consume();
switch (mode) {
case LINES:
x1 = e.getX();
y1 = e.getY();
x2 = -1;
break;
case POINTS:
default:
106
SEC
CSE/V
JAVA LAB MANUAL
colors.addElement(getForeground());
lines.addElement(new Rectangle(e.getX(), e.getY(), -1, -1));
x1 = e.getX();
y1 = e.getY();
repaint();
break;
}
}
public void mouseReleased(MouseEvent e) {
e.consume();
switch (mode) {
case LINES:
colors.addElement(getForeground());
lines.addElement(new Rectangle(x1, y1, e.getX(), e.getY()));
x2 = -1;
break;
case POINTS:
default:
break;
}
repaint();
}
107
SEC
CSE/V
JAVA LAB MANUAL
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void paint(Graphics g) {
int np = lines.size();
/* draw the current lines */
g.setColor(getForeground());
for (int i=0; i < np; i++) {
Rectangle p = (Rectangle)lines.elementAt(i);
g.setColor((Color)colors.elementAt(i));
if (p.width != -1) {
g.drawLine(p.x, p.y, p.width, p.height);
} else {
g.drawLine(p.x, p.y, p.x, p.y);
}
108
SEC
CSE/V
JAVA LAB MANUAL
}
if (mode == LINES) {
g.setColor(getForeground());
if (x2 != -1) {
g.drawLine(x1, y1, x2, y2);
}
}
}
}
class DrawControls extends Panel implements ItemListener {
DrawPanel target;
public DrawControls(DrawPanel target) {
this.target = target;
setLayout(new FlowLayout());
setBackground(Color.lightGray);
target.setForeground(Color.red);
CheckboxGroup group = new CheckboxGroup();
Checkbox b;
add(b = new Checkbox(null, group, false));
b.addItemListener(this);
b.setForeground(Color.red);
add(b = new Checkbox(null, group, false));
109
SEC
CSE/V
JAVA LAB MANUAL
b.addItemListener(this);
b.setForeground(Color.green);
add(b = new Checkbox(null, group, false));
b.addItemListener(this);
b.setForeground(Color.blue);
add(b = new Checkbox(null, group, false));
b.addItemListener(this);
b.setForeground(Color.pink);
add(b = new Checkbox(null, group, false));
b.addItemListener(this);
b.setForeground(Color.orange);
add(b = new Checkbox(null, group, true));
b.addItemListener(this);
b.setForeground(Color.black);
target.setForeground(b.getForeground());
Choice shapes = new Choice();
shapes.addItemListener(this);
shapes.addItem("Lines");
shapes.addItem("Points");
shapes.setBackground(Color.lightGray);
add(shapes);
}
110
SEC
CSE/V
JAVA LAB MANUAL
public void paint(Graphics g) {
Rectangle r = getBounds();
g.setColor(Color.lightGray);
g.draw3DRect(0, 0, r.width, r.height, false);
int n = getComponentCount();
for(int i=0; i<n; i++) {
Component comp = getComponent(i);
if (comp instanceof Checkbox) {
Point loc = comp.getLocation();
Dimension d = comp.getSize();
g.setColor(comp.getForeground());
g.drawRect(loc.x-1, loc.y-1, d.width+1, d.height+1);
}
}
}
public void itemStateChanged(ItemEvent e) {
if (e.getSource() instanceof Checkbox) {
target.setForeground(((Component)e.getSource()).getForeground());
} else if (e.getSource() instanceof Choice) {
String choice = (String) e.getItem();
if (choice.equals("Lines")) {
111
SEC
CSE/V
JAVA LAB MANUAL
target.setDrawMode(DrawPanel.LINES);
} else if (choice.equals("Points")) {
target.setDrawMode(DrawPanel.POINTS);
}
}
}
}
112
SEC
CSE/V
JAVA LAB MANUAL
OUTPUT:
Result:
Thus the Applet-Paint program was compiled and executed successfully
113
SEC
CSE/V
EX NO 2
JAVA LAB MANUAL
IMPLEMENTING DYNAMIC POLYMORPHISM IN JAVA
AIM:
To write a java program for abstract class to find areas of different shapes.
ALGORITHM:
1. Start the program.
2. Create an abstract class with class name Shape.
3. Create a constructor with arguments and declare variables dim1, dim2 and PI.
4. Declare an abstract method area() inside the class.
5. Create the classes Rectangle, Triangle, Circle, and Ellipse to find the area.
6. Define abstract method area() inside the subclasses and call the constructor of class Shape
using super keyword.
7. In main(), create the objects for all classes and pass values to fields of constructors.
8. Create a reference variable figuref for abstract class.
9. Using reference variable of class Shape, call the method area() of all subclasses
10. Print the areas for all shapes.
11. Stop the program.
114
SEC
CSE/V
JAVA LAB MANUAL
IMPLEMENTING DYNAMIC POLYMORPHISM IN JAVA
abstract class Shape
{
double dim1;
double dim2;
double PI=3.14;
Shape(double a, double b)
{
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}
class Rectangle extends Shape
{
Rectangle(double a, double b)
{
super(a, b);
}
// override area for rectangle
115
SEC
CSE/V
JAVA LAB MANUAL
double area()
{
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Shape
{
Triangle(double a, double b)
{
super(a, b);
}
// override area for right triangle
double area()
{
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class Circle extends Shape
{
Circle(double a, double b)
{
116
SEC
CSE/V
JAVA LAB MANUAL
super(a, b);
}
double area()
{
System.out.println("Inside Area for Circle.");
return PI * dim1 * dim1;
}
}
class Ellipse extends Shape
{
Ellipse(double a, double b)
{
super(a, b);
}
double area() {
System.out.println("Inside Area for Ellipse.");
return PI * dim1 * dim2;
}
}
class Square extends Shape
{
Square(double a, double b)
{
117
SEC
CSE/V
JAVA LAB MANUAL
super(a, b);
}
double area() {
System.out.println("Inside Area for Square.");
return dim1 * dim1;
}
}
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Circle c=new Circle(5,5);
Ellipse e=new Ellipse(7,7);
Square s=new Square(6,6);
Shape figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
figref = c;
System.out.println("Area is " + figref.area());
figref = e;
118
SEC
CSE/V
JAVA LAB MANUAL
System.out.println("Area is " + figref.area());
figref = s;
System.out.println("Area is " + figref.area());
}
}
OUTPUT:
E:\SQ>java AbstractAreas
Inside Area for Rectangle.
Area is 45.0
Inside Area for Triangle.
Area is 40.0
Inside Area for Circle.
Area is 78.5
Inside Area for Ellipse.
Area is 153.86
Inside Area for Square.
Area is 36.0
Result:
Thus the Dynamic polymorphism was compiled and executed successfully
119
SEC
CSE/V
EX NO : 3
JAVA LAB MANUAL
DEVELOPING A TEMPLATE FOR LINKED LIST
Aim:
To develop a template for linked list in java.
Algorithm:
1. Import the necessary packages.
2. Declare the main function within the class Linked list demo.
3. Insert items in to the list using add() method use addLast() to isert at the end.
4. Display the contents of the lists.
5. Use remove() method to declare a specific element.
6. Use remove() first(0,removeLast() to delete the element at the first and at the last.
7. Display the lsit and hadle the exceptions .
120
SEC
CSE/V
JAVA LAB MANUAL
DEVELOPING A TEMPLATE FOR LINKED LIST
import java.util.*;
class LinkedListDemo
{
public static void main(String args[])
{
LinkedList<String> l1=new LinkedList<String>();
l1.add("F");
l1.add("B");
l1.add("D");
l1.add("E");
l1.add("C");
l1.addLast("Z");
l1.addLast("A");
l1.add(1,"A2");
System.out.println("Original contents of l1:" + l1);
l1.remove("F");
l1.remove(2);
System.out.println("Contents of l1 after deflection: " + l1);
l1.removeFirst();
l1.removeLast();
System.out.println("l1 after deleting first and last: " + l1);
String val=l1.get(2);
121
SEC
CSE/V
JAVA LAB MANUAL
l1.set(2, val + "Changed");
System.out.println("l1 after change: " + l1); } }
OUTPUT:
E:\SQ>java LinkedListDemo
Original contents of l1:[F, A2, B, D, E, C, Z, A]
Contents of l1 after deflection: [A2, B, E, C, Z, A]
l1 after deleting first and last: [B, E, C, Z]
l1 after change: [B, E, CChanged, Z]
Result:
Thus the Linked list program was compiled and executed successfuly.
122