SlideShare a Scribd company logo
MADHA ENGINEERING COLLEGE
DEPARTMENT OF CSE
REGULATION-2008
CS2306 – JAVA LAB
LAB MANUAL
1
SYLLABUS
1. Develop Rational number class in Java. Use Java Doc comments for
documentation. Your implementation should use efficient representation
for a rational number, i.e. (500 / 1000) should be represented as (½).
2. Develop Date class in Java similar to the one available in java.util
package. Use Java Doc comments.
3. Implement Lisp-like list in Java. Write basic operations such as 'car',
'cdr', and 'cons'. If L is a list [3, 0, 2, 5], L.car () returns 3, while L.cdr()
returns [0,2,5].
4. Design a Java interface for ADT Stack. Develop two different classes
that implement this interface, one using array and the other using linked-
list. Provide necessary exception handling in both the implementations.
5. Design a Vehicle class hierarchy in Java. Write a test program to
demonstrate polymorphism.
6. Design classes for Currency, Rupee, and Dollar. Write a program that
randomly generates Rupee and Dollar objects and write them into a file
using object serialization. Write another program to read that file, convert
to Rupee if it reads a Dollar, and while leave the value as it is if it reads a
Rupee.
7. Design a scientific calculator using event-driven programming paradigm
of Java.
8. Write a multi-threaded Java program to print all numbers below 100,000
that are both prime and Fibonacci number (some examples are 2, 3, 5,
13, etc.). Design a thread that generates prime numbers below 100,000
and writes them into a pipe. Design another thread that generates
Fibonacci numbers and writes them to another pipe. The main thread
should read both the pipes to identify numbers common to both.
9. Develop a simple OPAC system for library using even-driven and
concurrent programming paradigms of Java. Use JDBC to connect to a
back-end database.
10.Develop multi-threaded echo server and a corresponding GUI client in
Java.
11.[Mini-Project] Develop a programmer's editor in Java that supports
syntax-highlighting, compilation support, debugging support, etc.
2
1. IMPLEMENTATION OF RATIONAL NUMBER
Develop Rational number class in Java. Use JavaDoc comments for
documentation. Your implementation should use efficient representation
for a rational number, i.e. (500 / 1000) should be represented as (½).
ALGORITHM:
STEP 1: Get two inputs from the user through command line arguments.
STEP 2: Store the numerator to variable a and denominator to variable b.
STEP 3: If both a and b are either positive or negative, set the flag as 0.
STEP 4: If either a or b is negative, set flag as 1.
STEP 5: Compare the values of a and b and assign the lowest value to c.
STEP 6: Set the for loop for i=2.
STEP 7: If both a and b values are divisible by i, then perform
(i) a=a/i;
(ii) b=b/i;
(ii) i=1;
STEP 8: Repeat the loop if the value of i is less than c. Break the loop if the
condition fails.
STEP 9: If flag is 1, display the result as negative number; else display it as
positive number.
RationalClass.java
import java.util.*;
/**
*@author Sreekandan.K
*/
public class RationalClass
{
/**
The Numerator part of Rational
*/
private int numerator;
3
/**
The Denominator part of Rational
*/
private int denominator;
/**
create and initialize a new Rational object
*/
public RationalClass(int numerator,int denominator)
{
if(denominator==0)
{
throw new RuntimeException("Denominator is zero");
}
int g=gcd(numerator,denominator);
if(g==1)
{
System.out.println("No Common Divisor for Numerator and Denominator");
this.numerator=numerator;
this.denominator=denominator;
}
else
{
this.numerator=numerator/g;
this.denominator=denominator/g;
}
}
/**
return string representation
*/
public String display()
{
return numerator+"/"+denominator;
}
/**
@param m
@param n
@return Greatest common divisor for m and n
*/
private static int gcd(int n,int d)
{
4
if(d==0)
return n;
else
return gcd(d,n%d);
}
2. IMPLEMENTATION OF DATE SERVER
Develop Date class in Java similar to the one available in java.util package.
Use Java Doc comments.
ALGORITHM:
STEP 1: Create a package which consists of constructors with the following
arguments:
i) Default
ii)Taking 3 arguments year, day and month
iii)Taking 5 arguments year, day, month, hours and minutes
iv)Taking 6 arguments year, day, month, hour, minutes and seconds
STEP 2: Get the year, month, date, hours, minutes, seconds using the
getYear(), getMonth(), getDate(), getHours(), getMinutes(), getSeconds()
methods.
STEP 3: Set all these details using set methods.
STEP 4: After()-the after() method returns true if the current date comes after
the specified date else it returns false
STEP 5: Before()-the before()method returns true if the current date comes
before the specified date else it returns false
STEP 6: Compare()-the compare() method compares the current date with the
specified date and returns 0 if it is equal,if after it returns 1 and if before it
returns -1.
DateFormatDemo.java
import java.text.*;
import java.util.*;
/**
*Class DateFormatDemo formats the date and time by using java.text package
*
*/
public class DateFormatDemo
{
public static void main(String args[])
{
/**
5
* @see java.util package
*/
Date date=new Date();
/**
* @see java.text package
*/
DateFormat df;
System.out.println("Current Date and Time - Available in java.util Package:");
System.out.println("-------------------------------------------------------");
System.out.println(date);
System.out.println();
System.out.println("Formatted Date - Using DateFormat Class from java.text
Package:");
System.out.println("---------------------------------------------------------------");
df=DateFormat.getDateInstance(DateFormat.DEFAULT);
System.out.println("Default Date Format:"+df.format(date));
df=DateFormat.getDateInstance(DateFormat.SHORT);
System.out.println("Date In Short Format:"+df.format(date));
df=DateFormat.getDateInstance(DateFormat.MEDIUM);
System.out.println("Date In Medium Format:"+df.format(date));
df=DateFormat.getDateInstance(DateFormat.LONG);
System.out.println("Date In Long Format:"+df.format(date));
df=DateFormat.getDateInstance(DateFormat.FULL);
System.out.println("Date In Full Format:"+df.format(date));
System.out.println();
System.out.println("Formatted Time - Using DateFormat Class from java.text
Package:");
System.out.println("---------------------------------------------------------------");
df=DateFormat.getTimeInstance(DateFormat.DEFAULT);
System.out.println("Default Time Format:"+df.format(date));
df=DateFormat.getTimeInstance(DateFormat.SHORT);
System.out.println("Time In Short Format:"+df.format(date));
df=DateFormat.getTimeInstance(DateFormat.MEDIUM);
System.out.println("Time In Medium Format:"+df.format(date));
df=DateFormat.getTimeInstance(DateFormat.LONG);
System.out.println("Time In Long Format:"+df.format(date));
df=DateFormat.getTimeInstance(DateFormat.FULL);
System.out.println("Time In Full Format:"+df.format(date));
System.out.println();
System.out.println("Formatted Date and Time - Using SimpleDateFormat Class
from java.text Package:");
System.out.println("------------------------------------------------------------------------------"
);
/**
* @see java.text package
*/
SimpleDateFormat sdf;
sdf=new SimpleDateFormat("dd MMM yyyy hh:mm:sss:S E w D zzz");
6
System.out.println(sdf.format(date));
}
}
7
3. IMPLEMENTATION OF LISP-LIKE LIST
Implement Lisp-like list in Java. Write basic operations such as 'car', 'cdr',
and 'cons'. If L is a list [3, 0, 2, 5], L.car() returns 3, while L.cdr() returns
[0,2,5].
ALGORITHM
STEP 1: Create a node of a list having data part and link part.
STEP 2: Create a menu having the following choices : insert, car, cdr, adjoin
and display.
STEP 3: Read the choice from the user and call the respective m ethods.
STEP 4: Create another class which implements the same interface to
implement the concept of stack through linked list.
INSERT
STEP 1: Create an object of node and append to the list.
CAR
STEP 1: Return the first node data.
CDR
STEP 1: Return all the node (data part) in the list except the first node.
ADJOIN
STEP 1: Check if the node to be inserted is already present in the list, if not
present append to the list.
LispOperation.java
import java.util.*;
/**
*
*/
class Lisp
{
public Vector car(Vector v)
{
Vector elt=new Vector();
elt.addElement(v.elementAt(0));
return elt;
}
public Vector cdr(Vector v)
{
Vector elt=new Vector();
for(int i=1;i<v.size();i++)
elt.addElement(v.elementAt(i));
return elt;
}
public Vector cons(int x, Vector v)
{
v.insertElementAt(x,0);
return v;
}
}
8
4. IMPLEMENTATION OF STACK
Design a Java interface for ADT Stack. Develop two different classes that
implement this interface, one using array and the other using linked-list.
Provide necessary exception handling in both the implementations.
ALGORITHM
STEP 1: Create an interface which consists of three methods namely PUSH,
POP and DISPLAY
STEP 2: Create a class which implements the above interface to implement the
concept of stack through Array
STEP 3: Define all the methods of the interface to push any element, to pop the
top element and to display the elements present in the stack.
STEP 4: Create another class which implements the same interface to
implement the concept of stack through linked list.
STEP 5: Repeat STEP 4 for the above said class also.
STEP 6: In the main class, get the choice from the user to choose whether array
implementation or linked list implementation of the stack.
STEP 7: Call the methods appropriately according to the choices made by the
user in the previous step.
STEP 8: Repeat step 6 and step 7 until the user stops his/her execution
StackADT.java
import java.io.*;
import java.util.*;
interface stackInterface
{
int n=50;
public void pop();
public void push();
public void display();
}
class stack implements stackInterface
{
int arr[]=new int[n];
int top=-1;
Scanner in=new Scanner(System.in);
public void push()
{
try
{
System.out.println("Enter The Element of Stack");
int elt=in.nextInt();
arr[++top]=elt;
}
catch (Exception e)
{
9
System.out.println("e");
}
}
public void pop()
{
int pop=arr[top];
top--;
System.out.println("Popped Element Is:"+pop);
}
public void display()
{
if(top<0)
{
System.out.println("Stack Is Empty");
return;
}
else
{
String str=" ";
for(int i=0;i<=top;i++)
str=str+" "+arr[i];
System.out.println("Stack Elements Are:"+str);
}
}
}
/**
*
*/
10
5. IMPLEMENTATION OF VEHICLE CLASS USING POLYMORPHISM
Design a Vehicle class hierarchy in Java. Write a test program to
demonstrate Polymorphism.
ALGORITHM
STEP 1: Create an abstract class named vehicle with abstract method Display
and a concrete method Input.
STEP 2: Define the input method by prompting the user to enter the values for
name, owner, type, number, engine capacity, seating capacity for the vehicle; all
the inputs taken in the form string.
STEP 3: Extend three classes namely Air, Water and Land from the base class.
STEP 4: Define the method display under the class Air by displaying all the
entered values.
STEP 5: Repeat step 4 for the class Water.
STEP 6: Extend the input method for the class Land by taking in the value of
wheeling capacity for the vehicle in the form of string.
STEP 7: In the main method create a reference for the abstract class and create
a switch case to perform operations on the opted class.
STEP 8: Under each class create a switch case to either enter the data or to
display the transport report.
STEP 9: Repeat the main menu on the user's choice.
STEP 10: Create array of objects under each class and call the methods by
assigning the values of the created objects to the reference object, to show
polymorphism.
VehicleDemo.java
import java.io.*;
class Vehicle
{
String regno;
int model;
Vehicle(String r, int m)
{
regno=r;
model=m;
}
void display()
{
System.out.println("Registration Number:"+regno);
System.out.println("Model Number:"+model);
}
}
class Twowheeler extends Vehicle
{
11
int wheel;
Twowheeler(String r,int m,int n)
{
super(r,m);
wheel=n;
}
void display()
{
System.out.println("Vehicle : Two Wheeler");
System.out.println("=====================");
super.display();
System.out.println("Number of Wheels:"+wheel+"n");
}
}
class Threewheeler extends Vehicle
{
int leaf;
Threewheeler(String r,int m,int n)
{
super(r,m);
leaf=n;
}
void display()
{
System.out.println("Vehicle : Three Wheeler");
System.out.println("=======================");
super.display();
System.out.println("Number of Leaf:"+leaf+"n");
}
}
class Fourwheeler extends Vehicle
{
int leaf;
Fourwheeler(String r,int m,int n)
{
super(r,m);
leaf=n;
}
void display()
{
System.out.println("Vehicle : Four Wheeler");
System.out.println("======================");
super.display();
System.out.println("Number of Leaf:"+leaf);
}
}
/**
**/
12
6. IMPLEMENTATION OF CURRENCY CONVERTER
Design classes for Currency, Rupee, and Dollar. Write a program that
randomly generates Rupee and Dollar objects and write them into a file
using object serialization. Write another program to read that file, convert
to Rupee if it reads a Dollar, while leave the value as it is if it reads a
Rupee.
ALGORITHM FOR PROGRAM 1:
STEP 1: Create a class named currency that implements the serializable
interface and also it is the base class for rupee and dollar classes.
STEP 2: Create an object for ObjectOutputStream to open a file in write mode
using FileOutputStream.
STEP 3: Read the user choice to enter rupee or dollar amount.
STEP 4: Generate random numbers as the value of rupee or dollar.
STEP 5: If choice is rupee then, append "Rs" to the value generated, else if
choice is dollar append "$" to the value generated.
STEP 6: Display the appended String and also write it into the file opened using
the writeObject() method.
STEP 7: Close the file.
ALGORITHM FOR PROGRAM 2:
STEP 1: Create a class named currency that implements the serializable
interface and also it is the base class for rupee and dollar classes.
STEP 2: Create an object for ObjectInputStream to open the file created in
program1 in read mode using FileInputStream.
STEP 3: If the file does not exist or if it is empty show exceptions.
STEP 4: While the End of file is not reached, do the following...
(i) If the value read is a dollar convert into rupee and print to the user
otherwise
print the rupee as such.
STEP 5: End the program.
writeObj.java
import java.io.*;
import java.util.*;
abstract class Currency implements Serializable
{
protected double money;
public abstract double getValue();
public abstract String printObj();
public Currency(double money)
{
this.money=money;
}
}
class Dollar extends Currency
13
{
public Dollar(int money)
{
super(money);
}
public double getValue()
{
return this.money*51;
}
public String printObj()
{
String object="Object Name : DollarnUSD : $"+this.money+"nINR :
Rs"+getValue()+"n";
return object;
}
}
class Rupee extends Currency
{
public Rupee(int amount)
{
super(amount);
}
public double getValue()
{
return this.money;
}
public String printObj()
{
String object="Object Name : Rupee nINR : Rs "+getValue()+"n";
return object;
}
}
/**
*
*/
14
7. IMPLEMENTATION OF CALCULATOR
Develop a scientific calculator using even-driven programming paradigm
of Java.
ALGORITHM:
STEP 1: Create a panel consisting of Buttons for various scientific operations.
STEP 2: Create Button actions.
STEP 3: Place the panel onto a frame.
STEP 4: Associate each Button click with the corresponding actionlistener.
SimpleCalculator.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
/**
*
*/
public class SimpleCalculator
{
public static void main(String[] args)
{
CalcFrame cf=new CalcFrame();
cf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cf.setVisible(true);
}
}
class CalcFrame extends JFrame
{
public CalcFrame()
{
setTitle("CALCULATOR");
CalcPanel panel=new CalcPanel();
add(panel);
pack();
}
}
class CalcPanel extends JPanel
{
JButton display;
JPanel panel;
double result;
String lastcmd;
boolean start;
public CalcPanel()
{
15
setLayout(new BorderLayout());
result=0;
lastcmd="=";
start=true;
display=new JButton("0");
display.setEnabled(false);
add(display,BorderLayout.NORTH);
ActionListener insert=new InsertAction();
ActionListener cmd=new CommandAction();
panel=new JPanel();
panel.setLayout(new GridLayout(5,4));
addButton("1",insert);
addButton("2",insert);
addButton("3",insert);
addButton("/",cmd);
addButton("4",insert);
addButton("5",insert);
addButton("6",insert);
addButton("*",cmd);
addButton("7",insert);
addButton("8",insert);
addButton("9",insert);
addButton("-",cmd);
addButton("0",insert);
addButton(".",insert);
addButton("pow",cmd);
addButton("+",cmd);
addButton("sin",insert);
addButton("cos",insert);
addButton("tan",insert);
addButton("=",cmd);
add(panel, BorderLayout.CENTER);
}
private void addButton(String label,ActionListener listener)
{
JButton button=new JButton(label);
button.addActionListener(listener);
panel.add(button);
}
private class InsertAction implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
String input=ae.getActionCommand();
if(start==true)
{
display.setText("");
start=false;
16
}
if(input.equals("sin"))
{
Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0;
display.setText(""+Math.sin(angle));
}
else if(input.equals("cos"))
{
Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0;
display.setText(""+Math.cos(angle));
}
else if(input.equals("tan"))
{
Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0;
display.setText(""+Math.tan(angle));
}
else
display.setText(display.getText()+input);
}
}
private class CommandAction implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
String command=ae.getActionCommand();
if(start==true)
{
if(command.equals("-"))
{
display.setText(command);
start=false;
}
else
lastcmd=command;
}
else
{
calc(Double.parseDouble(display.getText()));
lastcmd=command;
start=true;
}
}
}
public void calc(double x)
{
if(lastcmd.equals("+"))
result=result+x;
else if(lastcmd.equals("-"))
17
result=result-x;
else if(lastcmd.equals("*"))
result=result*x;
else if(lastcmd.equals("/"))
result=result/x;
else if(lastcmd.equals("="))
result=x;
else if(lastcmd.equals("pow"))
{
double powval=1.0;
for(double i=0.0;i<x;i++)
powval=powval*result;
result=powval;
}
display.setText(""+ result);
}
}
18
8. IMPLEMENTATION OF FIBONACCI SERIES USING FRAMES
Write a multi-threaded Java program to print all numbers below 100,000
that are both prime and fibonacci number (some examples are 2, 3, 5, 13,
etc.). Design a thread that generates prime numbers below 100,000 and
writes them into a pipe. Design another thread that generates fibonacci
numbers and writes them to another pipe. The main thread should read
both the pipes to identify numbers common to both.
ALGORITHM:
STEP 1: CreateThread1 which generates prime numbers below 100,000 and
store in pipe1.
STEP 2: Create Thread2 which generates Fibonacci numbers below 100,000
and store in pipe 2.
STEP 3: Write a main program which does the following:
(i) Call the two threads created in step1 and step2.
(ii) Read the data from pipe1 and pipe 2 and print the numbers
common to both.
MultiThreadDemo.java
import java.util.*;
import java.io.*;
class Fibonacci extends Thread
{
private PipedWriter out=new PipedWriter();
public PipedWriter getPipedWriter()
{
return out;
}
public void run()
{
Thread t=Thread.currentThread();
t.setName("Fibonacci");
System.out.println(t.getName()+" Thread started...");
int fibo=0,fibo1=0,fibo2=1;
while(true)
{
try
{
fibo=fibo1+fibo2;
if(fibo>100000)
{
out.close();
break;
}
out.write(fibo);
sleep(1000);
19
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
fibo1=fibo2;
fibo2=fibo;
}
System.out.println(t.getName()+" Thread exiting...");
}
}
class Prime extends Thread
{
private PipedWriter out1=new PipedWriter();
public PipedWriter getPipedWriter()
{
return out1;
}
public void run()
{
Thread t=Thread.currentThread();
t.setName("Prime");
System.out.println(t.getName() +" Thread Started...");
int prime=1;
while(true)
{
try
{
if(prime>100000)
{
out1.close();
break;
}
if(isPrime(prime))
out1.write(prime);
prime++;
sleep(0);
}
catch(Exception e)
{
System.out.println(t.getName()+" Thread exiting...");
System.exit(0);
}
}
}
public boolean isPrime(int n)
{
int m=(int)Math.round(Math.sqrt(n));
20
if(n==1||n==2)
return true;
for(int i=2;i<=m;i++)
if(n%i==0)
return false;
return true;
}
}
/**
*
*/
21
8. IMPLEMENTATION OF FIBONACCI SERIES USING FRAMES
Develop a simple OPAC system for library using event-driven and
concurrent programming paradigms of Java. Use JDBC to connect to a
back-end database.
ALGORITHM:
STEP 1: Create a Master Database1(Book Details) having the following fields:
BookNo.Book Name, Author, No. of pages, Name of Publisher, Cost.
STEP 2: Create a Master Database2(User Details) having the following fields :
UserID, Department
STEP 3: Create a Transaction Database having the following fields: UserID,
Book No., Date of Renewal / Date of Return, Fine
STEP 4: Create a panel consisting of buttons ADD, UPDATE, DELETE.
Associate these button actions with listeners(with Master Database 1)
STEP 5: Create a panel consisting of buttons ADD, UPDATE, DELETE.
Associate these button actions with listeners(with Master Database 2)
STEP 6: Create another panel consisting of buttons UserID, BookID,
Return/Renewal,Fine.
STEP 7: Associate these buttons with listeners(with Transaction Database).
OpacSystem.java
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
/**
*
*/
public class OpacSystem implements ActionListener
{
JRadioButton author=new JRadioButton("Search By Author");
JRadioButton book=new JRadioButton("Search by Book");
JTextField txt=new JTextField(30);
JLabel label=new JLabel("Enter Search Key");
JButton search=new JButton("SEARCH");
JFrame frame=new JFrame();
JTable table;
DefaultTableModel model;
String query="select*from opacTab";
public OpacSystem()
{
frame.setTitle("OPAC SYSTEM");
frame.setSize(800,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
22
JPanel p1=new JPanel();
p1.setLayout(new FlowLayout());
p1.add(label);
p1.add(txt);
ButtonGroup bg=new ButtonGroup();
bg.add(author);
bg.add(book);
JPanel p2=new JPanel();
p2.setLayout(new FlowLayout());
p2.add(author);
p2.add(book);
p2.add(search);
search.addActionListener(this);
JPanel p3=new JPanel();
p3.setLayout(new BorderLayout());
p3.add(p1,BorderLayout.NORTH);
p3.add(p2,BorderLayout.CENTER);
frame.add(p3,BorderLayout.NORTH);
addTable(query);
frame.setVisible(true);
}
public void addTable(String str)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:opacDS");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(str);
ResultSetMetaData rsmd=rs.getMetaData();
int cols=rsmd.getColumnCount();
model=new DefaultTableModel(1,cols);
table=new JTable(model);
String[] tabledata=new String[cols];
int i=0;
while(i<cols)
{
tabledata[i]=rsmd.getColumnName(i+1);
i++;
}
model.addRow(tabledata);
while(rs.next())
{
for(i=0;i<cols;i++)
tabledata[i]=rs.getObject(i+1).toString();
model.addRow(tabledata);
}
frame.add(table,BorderLayout.CENTER);
23
con.close();
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
public void actionPerformed(ActionEvent ae)
{
if(author.isSelected())
query="select*from opacTab where AUTHOR like '"+txt.getText()+"%'";
if(book.isSelected())
query="select*from opacTab where BOOK like '"+txt.getText()+"%'";
while(model.getRowCount()>0)
model.removeRow(0);
frame.remove(table);
addTable(query);
}
24
10. IMPLEMENTATION OF MULTITHREADED
ECHO SERVER & ECHO CLIENT
Develop multi-threaded echo server and a corresponding GUI client in
Java.
ALGORITHM FOR SERVER:
STEP 1: Establish the connection of socket.
STEP 2: Assign the local Protocol address to the socket.
STEP 3: Move the socket from closed to listener state and provide maximum no.
of Connections.
STEP 4: Create a new socket connection using client address.
STEP 5: Read the data from the socket.
STEP 6: Write the data into socket.
STEP 7: Close the socket.
EchoServer.java
import java.io.*;
import java.net.*;
/**
*
*/
public class EchoServer
{
public static void main(String [] args)
{
System.out.println("Server Started....");
try
{
ServerSocket ss=new ServerSocket(300);
while(true)
{
Socket s= ss.accept();
Thread t = new ThreadedServer(s);
t.start();
}
}
catch(Exception e)
{
System.out.println("Error: " + e);
}
}
}
class ThreadedServer extends Thread
{
Socket soc;
public ThreadedServer(Socket soc)
25
{
this.soc=soc;
}
public void run()
{
try
{
BufferedReader in=new BufferedReader(new
InputStreamReader(soc.getInputStream()));
PrintWriter out=new PrintWriter(soc.getOutputStream());
String str=in.readLine();
System.out.println("Message From Client:"+str);
out.flush();
out.println("Message To Client:"+str);
out.flush();
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
}
ALGORITHM FOR CLIENT:
STEP 1: Open the socket.
STEP 2: Get the host name and port number from client.
STEP 3: Write a request to the buffer that contain the request number as a byte
to the
output stream.
STEP 4: Get the message from the user.
STEP 5: Write to the socket.
STEP 6: Set the write operation for success.
STEP 7: Read the contents from the socket / Buffer.
STEP 8: Close the socket.
EchoClient.java
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
*
*/
class EchoClient extends JFrame
{
26
JTextArea ta;
JTextField msg;
JPanel panel;
JScrollPane scroll;
JButton b1=new JButton("Close");
JButton b2=new JButton("Send");
JLabel l1=new JLabel("Echo Client GUI");
Container c;
EchoClient()
{
c=getContentPane();
setSize(300,470);
setTitle("GUI Client");
panel=new JPanel();
msg=new JTextField(20);
panel.setLayout(new FlowLayout(FlowLayout.CENTER));
ta=new JTextArea(20,20);
scroll=new JScrollPane(ta);
panel.add(l1);
panel.add(ta);
panel.add(msg);
panel.add(b2);
panel.add(b1);
c.add(panel);
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
try
{
Socket s=new Socket("localhost",300);
BufferedReader in=new BufferedReader(new
InputStreamReader(s.getInputStream()));
PrintWriter out=new PrintWriter(new
OutputStreamWriter(s.getOutputStream()));
out.println(msg.getText());
out.flush();
String temp =ta.getText();
if(temp.equalsIgnoreCase("quit"))
{
System.exit(0);
}
msg.setText("");
ta.append("n"+in.readLine());
}
catch (IOException e)
{
ta.setText("Exception:"+e);
27
}
}
});
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
public static void main(String args[])
{
EchoClient frame=new EchoClient();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
28
11. MINI PROJECT
Develop a programmer's editor in Java that supports syntax high lighting,
compilation support, debugging support, etc.
ALGORITHM:
STEP 1: Create a panel consisting of menu bar containing File, Edit, Compile
and Debug.
STEP 2: Add submenus for each of the menu.
File – New, Open, Save, Quit.
Edit – Cut, Copy, Paste.
Compile – Compile, Link
Debug – Inspect, Call Stack, Watches, BreakPoints.
STEP 3: Associate these event sources with Listeners.
29
Ad

More Related Content

What's hot (20)

Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
AravindSankaran
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
Mumbai Academisc
 
Java codes
Java codesJava codes
Java codes
Hussain Sherwani
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
Upender Upr
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya Behera
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
Iram Ramrajkar
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - Praticals
Fahad Shaikh
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUAL
Prabhu D
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
Iram Ramrajkar
 
Class method
Class methodClass method
Class method
kamal kotecha
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Mario Fusco
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
Nishan Barot
 
Java practical
Java practicalJava practical
Java practical
shweta-sharma99
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
Shalabh Chaudhary
 
Java programs
Java programsJava programs
Java programs
Mukund Gandrakota
 
Java Programs
Java ProgramsJava Programs
Java Programs
vvpadhu
 
Java ppt
Java pptJava ppt
Java ppt
Rohan Gajre
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
Mario Fusco
 
Java programs
Java programsJava programs
Java programs
Dr.M.Karthika parthasarathy
 
Kotlin
KotlinKotlin
Kotlin
YeldosTanikin
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
Upender Upr
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya Behera
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - Praticals
Fahad Shaikh
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUAL
Prabhu D
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
Iram Ramrajkar
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Mario Fusco
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
Nishan Barot
 
Java Programs
Java ProgramsJava Programs
Java Programs
vvpadhu
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
Mario Fusco
 

Viewers also liked (17)

20 C programs
20 C programs20 C programs
20 C programs
navjoth
 
Simple Java
Simple JavaSimple Java
Simple Java
Reduan Samad
 
Programming with \'C\'
Programming with \'C\'Programming with \'C\'
Programming with \'C\'
bdmsts
 
Connect all your customers on one multichannel platform!
Connect all your customers on one multichannel platform!Connect all your customers on one multichannel platform!
Connect all your customers on one multichannel platform!
Slawomir Kluczewski
 
Computer Logic
Computer LogicComputer Logic
Computer Logic
primeteacher32
 
Python in raspberry pi
Python in raspberry piPython in raspberry pi
Python in raspberry pi
Sudar Muthu
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
javaTpoint s
 
Conditional Loops Python
Conditional Loops PythonConditional Loops Python
Conditional Loops Python
primeteacher32
 
Loops in c
Loops in cLoops in c
Loops in c
baabtra.com - No. 1 supplier of quality freshers
 
Cloud Computing to Internet of Things
Cloud Computing to Internet of ThingsCloud Computing to Internet of Things
Cloud Computing to Internet of Things
HermesDDS
 
Socket Programming In Python
Socket Programming In PythonSocket Programming In Python
Socket Programming In Python
didip
 
Got Python I/O: IoT Develoment in Python via GPIO
Got Python I/O: IoT Develoment in Python via GPIOGot Python I/O: IoT Develoment in Python via GPIO
Got Python I/O: IoT Develoment in Python via GPIO
Adam Englander
 
Internet of Things for Libraries
Internet of Things for LibrariesInternet of Things for Libraries
Internet of Things for Libraries
Nicole Baratta
 
C programs
C programsC programs
C programs
Minu S
 
Multidimensional array in C
Multidimensional array in CMultidimensional array in C
Multidimensional array in C
Smit Parikh
 
Mastering Python lesson3b_for_loops
Mastering Python lesson3b_for_loopsMastering Python lesson3b_for_loops
Mastering Python lesson3b_for_loops
Ruth Marvin
 
Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1
javatrainingonline
 
20 C programs
20 C programs20 C programs
20 C programs
navjoth
 
Programming with \'C\'
Programming with \'C\'Programming with \'C\'
Programming with \'C\'
bdmsts
 
Connect all your customers on one multichannel platform!
Connect all your customers on one multichannel platform!Connect all your customers on one multichannel platform!
Connect all your customers on one multichannel platform!
Slawomir Kluczewski
 
Python in raspberry pi
Python in raspberry piPython in raspberry pi
Python in raspberry pi
Sudar Muthu
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
javaTpoint s
 
Conditional Loops Python
Conditional Loops PythonConditional Loops Python
Conditional Loops Python
primeteacher32
 
Cloud Computing to Internet of Things
Cloud Computing to Internet of ThingsCloud Computing to Internet of Things
Cloud Computing to Internet of Things
HermesDDS
 
Socket Programming In Python
Socket Programming In PythonSocket Programming In Python
Socket Programming In Python
didip
 
Got Python I/O: IoT Develoment in Python via GPIO
Got Python I/O: IoT Develoment in Python via GPIOGot Python I/O: IoT Develoment in Python via GPIO
Got Python I/O: IoT Develoment in Python via GPIO
Adam Englander
 
Internet of Things for Libraries
Internet of Things for LibrariesInternet of Things for Libraries
Internet of Things for Libraries
Nicole Baratta
 
C programs
C programsC programs
C programs
Minu S
 
Multidimensional array in C
Multidimensional array in CMultidimensional array in C
Multidimensional array in C
Smit Parikh
 
Mastering Python lesson3b_for_loops
Mastering Python lesson3b_for_loopsMastering Python lesson3b_for_loops
Mastering Python lesson3b_for_loops
Ruth Marvin
 
Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1
javatrainingonline
 
Ad

Similar to CS2309 JAVA LAB MANUAL (20)

Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
Shivam Singhal
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf
amitbhachne
 
Java programming concept
Java programming conceptJava programming concept
Java programming concept
Sanjay Gunjal
 
Effective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's bookEffective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's book
Roman Tsypuk
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
kamal kotecha
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
mwillmer
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
JAXLondon_Conference
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
Prof. Erwin Globio
 
Lewis jssap3 e_labman02
Lewis jssap3 e_labman02Lewis jssap3 e_labman02
Lewis jssap3 e_labman02
auswhit
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
Arjun Shanka
 
Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for Designers
R. Sosa
 
Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
Mohammad Faizan
 
project2.classpathproject2.project project2 .docx
project2.classpathproject2.project  project2 .docxproject2.classpathproject2.project  project2 .docx
project2.classpathproject2.project project2 .docx
briancrawford30935
 
interface in java explained in detailed form
interface in java explained in detailed forminterface in java explained in detailed form
interface in java explained in detailed form
PriyadharshiniG41
 
JAVA_BASICS_Data_abstraction_encapsulation.ppt
JAVA_BASICS_Data_abstraction_encapsulation.pptJAVA_BASICS_Data_abstraction_encapsulation.ppt
JAVA_BASICS_Data_abstraction_encapsulation.ppt
VGaneshKarthikeyan
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
Martin Toshev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
Shivam Singhal
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf
amitbhachne
 
Java programming concept
Java programming conceptJava programming concept
Java programming concept
Sanjay Gunjal
 
Effective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's bookEffective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's book
Roman Tsypuk
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
kamal kotecha
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
mwillmer
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
Lewis jssap3 e_labman02
Lewis jssap3 e_labman02Lewis jssap3 e_labman02
Lewis jssap3 e_labman02
auswhit
 
Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for Designers
R. Sosa
 
project2.classpathproject2.project project2 .docx
project2.classpathproject2.project  project2 .docxproject2.classpathproject2.project  project2 .docx
project2.classpathproject2.project project2 .docx
briancrawford30935
 
interface in java explained in detailed form
interface in java explained in detailed forminterface in java explained in detailed form
interface in java explained in detailed form
PriyadharshiniG41
 
JAVA_BASICS_Data_abstraction_encapsulation.ppt
JAVA_BASICS_Data_abstraction_encapsulation.pptJAVA_BASICS_Data_abstraction_encapsulation.ppt
JAVA_BASICS_Data_abstraction_encapsulation.ppt
VGaneshKarthikeyan
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
Martin Toshev
 
Ad

Recently uploaded (20)

What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
The History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptxThe History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
Arshad Shaikh
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast BrooklynBridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
i4jd41bk
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
*"The Segmented Blueprint: Unlocking Insect Body Architecture"*.pptx
Arshad Shaikh
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast BrooklynBridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
i4jd41bk
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 

CS2309 JAVA LAB MANUAL

  • 1. MADHA ENGINEERING COLLEGE DEPARTMENT OF CSE REGULATION-2008 CS2306 – JAVA LAB LAB MANUAL 1
  • 2. SYLLABUS 1. Develop Rational number class in Java. Use Java Doc comments for documentation. Your implementation should use efficient representation for a rational number, i.e. (500 / 1000) should be represented as (½). 2. Develop Date class in Java similar to the one available in java.util package. Use Java Doc comments. 3. Implement Lisp-like list in Java. Write basic operations such as 'car', 'cdr', and 'cons'. If L is a list [3, 0, 2, 5], L.car () returns 3, while L.cdr() returns [0,2,5]. 4. Design a Java interface for ADT Stack. Develop two different classes that implement this interface, one using array and the other using linked- list. Provide necessary exception handling in both the implementations. 5. Design a Vehicle class hierarchy in Java. Write a test program to demonstrate polymorphism. 6. Design classes for Currency, Rupee, and Dollar. Write a program that randomly generates Rupee and Dollar objects and write them into a file using object serialization. Write another program to read that file, convert to Rupee if it reads a Dollar, and while leave the value as it is if it reads a Rupee. 7. Design a scientific calculator using event-driven programming paradigm of Java. 8. Write a multi-threaded Java program to print all numbers below 100,000 that are both prime and Fibonacci number (some examples are 2, 3, 5, 13, etc.). Design a thread that generates prime numbers below 100,000 and writes them into a pipe. Design another thread that generates Fibonacci numbers and writes them to another pipe. The main thread should read both the pipes to identify numbers common to both. 9. Develop a simple OPAC system for library using even-driven and concurrent programming paradigms of Java. Use JDBC to connect to a back-end database. 10.Develop multi-threaded echo server and a corresponding GUI client in Java. 11.[Mini-Project] Develop a programmer's editor in Java that supports syntax-highlighting, compilation support, debugging support, etc. 2
  • 3. 1. IMPLEMENTATION OF RATIONAL NUMBER Develop Rational number class in Java. Use JavaDoc comments for documentation. Your implementation should use efficient representation for a rational number, i.e. (500 / 1000) should be represented as (½). ALGORITHM: STEP 1: Get two inputs from the user through command line arguments. STEP 2: Store the numerator to variable a and denominator to variable b. STEP 3: If both a and b are either positive or negative, set the flag as 0. STEP 4: If either a or b is negative, set flag as 1. STEP 5: Compare the values of a and b and assign the lowest value to c. STEP 6: Set the for loop for i=2. STEP 7: If both a and b values are divisible by i, then perform (i) a=a/i; (ii) b=b/i; (ii) i=1; STEP 8: Repeat the loop if the value of i is less than c. Break the loop if the condition fails. STEP 9: If flag is 1, display the result as negative number; else display it as positive number. RationalClass.java import java.util.*; /** *@author Sreekandan.K */ public class RationalClass { /** The Numerator part of Rational */ private int numerator; 3
  • 4. /** The Denominator part of Rational */ private int denominator; /** create and initialize a new Rational object */ public RationalClass(int numerator,int denominator) { if(denominator==0) { throw new RuntimeException("Denominator is zero"); } int g=gcd(numerator,denominator); if(g==1) { System.out.println("No Common Divisor for Numerator and Denominator"); this.numerator=numerator; this.denominator=denominator; } else { this.numerator=numerator/g; this.denominator=denominator/g; } } /** return string representation */ public String display() { return numerator+"/"+denominator; } /** @param m @param n @return Greatest common divisor for m and n */ private static int gcd(int n,int d) { 4
  • 5. if(d==0) return n; else return gcd(d,n%d); } 2. IMPLEMENTATION OF DATE SERVER Develop Date class in Java similar to the one available in java.util package. Use Java Doc comments. ALGORITHM: STEP 1: Create a package which consists of constructors with the following arguments: i) Default ii)Taking 3 arguments year, day and month iii)Taking 5 arguments year, day, month, hours and minutes iv)Taking 6 arguments year, day, month, hour, minutes and seconds STEP 2: Get the year, month, date, hours, minutes, seconds using the getYear(), getMonth(), getDate(), getHours(), getMinutes(), getSeconds() methods. STEP 3: Set all these details using set methods. STEP 4: After()-the after() method returns true if the current date comes after the specified date else it returns false STEP 5: Before()-the before()method returns true if the current date comes before the specified date else it returns false STEP 6: Compare()-the compare() method compares the current date with the specified date and returns 0 if it is equal,if after it returns 1 and if before it returns -1. DateFormatDemo.java import java.text.*; import java.util.*; /** *Class DateFormatDemo formats the date and time by using java.text package * */ public class DateFormatDemo { public static void main(String args[]) { /** 5
  • 6. * @see java.util package */ Date date=new Date(); /** * @see java.text package */ DateFormat df; System.out.println("Current Date and Time - Available in java.util Package:"); System.out.println("-------------------------------------------------------"); System.out.println(date); System.out.println(); System.out.println("Formatted Date - Using DateFormat Class from java.text Package:"); System.out.println("---------------------------------------------------------------"); df=DateFormat.getDateInstance(DateFormat.DEFAULT); System.out.println("Default Date Format:"+df.format(date)); df=DateFormat.getDateInstance(DateFormat.SHORT); System.out.println("Date In Short Format:"+df.format(date)); df=DateFormat.getDateInstance(DateFormat.MEDIUM); System.out.println("Date In Medium Format:"+df.format(date)); df=DateFormat.getDateInstance(DateFormat.LONG); System.out.println("Date In Long Format:"+df.format(date)); df=DateFormat.getDateInstance(DateFormat.FULL); System.out.println("Date In Full Format:"+df.format(date)); System.out.println(); System.out.println("Formatted Time - Using DateFormat Class from java.text Package:"); System.out.println("---------------------------------------------------------------"); df=DateFormat.getTimeInstance(DateFormat.DEFAULT); System.out.println("Default Time Format:"+df.format(date)); df=DateFormat.getTimeInstance(DateFormat.SHORT); System.out.println("Time In Short Format:"+df.format(date)); df=DateFormat.getTimeInstance(DateFormat.MEDIUM); System.out.println("Time In Medium Format:"+df.format(date)); df=DateFormat.getTimeInstance(DateFormat.LONG); System.out.println("Time In Long Format:"+df.format(date)); df=DateFormat.getTimeInstance(DateFormat.FULL); System.out.println("Time In Full Format:"+df.format(date)); System.out.println(); System.out.println("Formatted Date and Time - Using SimpleDateFormat Class from java.text Package:"); System.out.println("------------------------------------------------------------------------------" ); /** * @see java.text package */ SimpleDateFormat sdf; sdf=new SimpleDateFormat("dd MMM yyyy hh:mm:sss:S E w D zzz"); 6
  • 8. 3. IMPLEMENTATION OF LISP-LIKE LIST Implement Lisp-like list in Java. Write basic operations such as 'car', 'cdr', and 'cons'. If L is a list [3, 0, 2, 5], L.car() returns 3, while L.cdr() returns [0,2,5]. ALGORITHM STEP 1: Create a node of a list having data part and link part. STEP 2: Create a menu having the following choices : insert, car, cdr, adjoin and display. STEP 3: Read the choice from the user and call the respective m ethods. STEP 4: Create another class which implements the same interface to implement the concept of stack through linked list. INSERT STEP 1: Create an object of node and append to the list. CAR STEP 1: Return the first node data. CDR STEP 1: Return all the node (data part) in the list except the first node. ADJOIN STEP 1: Check if the node to be inserted is already present in the list, if not present append to the list. LispOperation.java import java.util.*; /** * */ class Lisp { public Vector car(Vector v) { Vector elt=new Vector(); elt.addElement(v.elementAt(0)); return elt; } public Vector cdr(Vector v) { Vector elt=new Vector(); for(int i=1;i<v.size();i++) elt.addElement(v.elementAt(i)); return elt; } public Vector cons(int x, Vector v) { v.insertElementAt(x,0); return v; } } 8
  • 9. 4. IMPLEMENTATION OF STACK Design a Java interface for ADT Stack. Develop two different classes that implement this interface, one using array and the other using linked-list. Provide necessary exception handling in both the implementations. ALGORITHM STEP 1: Create an interface which consists of three methods namely PUSH, POP and DISPLAY STEP 2: Create a class which implements the above interface to implement the concept of stack through Array STEP 3: Define all the methods of the interface to push any element, to pop the top element and to display the elements present in the stack. STEP 4: Create another class which implements the same interface to implement the concept of stack through linked list. STEP 5: Repeat STEP 4 for the above said class also. STEP 6: In the main class, get the choice from the user to choose whether array implementation or linked list implementation of the stack. STEP 7: Call the methods appropriately according to the choices made by the user in the previous step. STEP 8: Repeat step 6 and step 7 until the user stops his/her execution StackADT.java import java.io.*; import java.util.*; interface stackInterface { int n=50; public void pop(); public void push(); public void display(); } class stack implements stackInterface { int arr[]=new int[n]; int top=-1; Scanner in=new Scanner(System.in); public void push() { try { System.out.println("Enter The Element of Stack"); int elt=in.nextInt(); arr[++top]=elt; } catch (Exception e) { 9
  • 10. System.out.println("e"); } } public void pop() { int pop=arr[top]; top--; System.out.println("Popped Element Is:"+pop); } public void display() { if(top<0) { System.out.println("Stack Is Empty"); return; } else { String str=" "; for(int i=0;i<=top;i++) str=str+" "+arr[i]; System.out.println("Stack Elements Are:"+str); } } } /** * */ 10
  • 11. 5. IMPLEMENTATION OF VEHICLE CLASS USING POLYMORPHISM Design a Vehicle class hierarchy in Java. Write a test program to demonstrate Polymorphism. ALGORITHM STEP 1: Create an abstract class named vehicle with abstract method Display and a concrete method Input. STEP 2: Define the input method by prompting the user to enter the values for name, owner, type, number, engine capacity, seating capacity for the vehicle; all the inputs taken in the form string. STEP 3: Extend three classes namely Air, Water and Land from the base class. STEP 4: Define the method display under the class Air by displaying all the entered values. STEP 5: Repeat step 4 for the class Water. STEP 6: Extend the input method for the class Land by taking in the value of wheeling capacity for the vehicle in the form of string. STEP 7: In the main method create a reference for the abstract class and create a switch case to perform operations on the opted class. STEP 8: Under each class create a switch case to either enter the data or to display the transport report. STEP 9: Repeat the main menu on the user's choice. STEP 10: Create array of objects under each class and call the methods by assigning the values of the created objects to the reference object, to show polymorphism. VehicleDemo.java import java.io.*; class Vehicle { String regno; int model; Vehicle(String r, int m) { regno=r; model=m; } void display() { System.out.println("Registration Number:"+regno); System.out.println("Model Number:"+model); } } class Twowheeler extends Vehicle { 11
  • 12. int wheel; Twowheeler(String r,int m,int n) { super(r,m); wheel=n; } void display() { System.out.println("Vehicle : Two Wheeler"); System.out.println("====================="); super.display(); System.out.println("Number of Wheels:"+wheel+"n"); } } class Threewheeler extends Vehicle { int leaf; Threewheeler(String r,int m,int n) { super(r,m); leaf=n; } void display() { System.out.println("Vehicle : Three Wheeler"); System.out.println("======================="); super.display(); System.out.println("Number of Leaf:"+leaf+"n"); } } class Fourwheeler extends Vehicle { int leaf; Fourwheeler(String r,int m,int n) { super(r,m); leaf=n; } void display() { System.out.println("Vehicle : Four Wheeler"); System.out.println("======================"); super.display(); System.out.println("Number of Leaf:"+leaf); } } /** **/ 12
  • 13. 6. IMPLEMENTATION OF CURRENCY CONVERTER Design classes for Currency, Rupee, and Dollar. Write a program that randomly generates Rupee and Dollar objects and write them into a file using object serialization. Write another program to read that file, convert to Rupee if it reads a Dollar, while leave the value as it is if it reads a Rupee. ALGORITHM FOR PROGRAM 1: STEP 1: Create a class named currency that implements the serializable interface and also it is the base class for rupee and dollar classes. STEP 2: Create an object for ObjectOutputStream to open a file in write mode using FileOutputStream. STEP 3: Read the user choice to enter rupee or dollar amount. STEP 4: Generate random numbers as the value of rupee or dollar. STEP 5: If choice is rupee then, append "Rs" to the value generated, else if choice is dollar append "$" to the value generated. STEP 6: Display the appended String and also write it into the file opened using the writeObject() method. STEP 7: Close the file. ALGORITHM FOR PROGRAM 2: STEP 1: Create a class named currency that implements the serializable interface and also it is the base class for rupee and dollar classes. STEP 2: Create an object for ObjectInputStream to open the file created in program1 in read mode using FileInputStream. STEP 3: If the file does not exist or if it is empty show exceptions. STEP 4: While the End of file is not reached, do the following... (i) If the value read is a dollar convert into rupee and print to the user otherwise print the rupee as such. STEP 5: End the program. writeObj.java import java.io.*; import java.util.*; abstract class Currency implements Serializable { protected double money; public abstract double getValue(); public abstract String printObj(); public Currency(double money) { this.money=money; } } class Dollar extends Currency 13
  • 14. { public Dollar(int money) { super(money); } public double getValue() { return this.money*51; } public String printObj() { String object="Object Name : DollarnUSD : $"+this.money+"nINR : Rs"+getValue()+"n"; return object; } } class Rupee extends Currency { public Rupee(int amount) { super(amount); } public double getValue() { return this.money; } public String printObj() { String object="Object Name : Rupee nINR : Rs "+getValue()+"n"; return object; } } /** * */ 14
  • 15. 7. IMPLEMENTATION OF CALCULATOR Develop a scientific calculator using even-driven programming paradigm of Java. ALGORITHM: STEP 1: Create a panel consisting of Buttons for various scientific operations. STEP 2: Create Button actions. STEP 3: Place the panel onto a frame. STEP 4: Associate each Button click with the corresponding actionlistener. SimpleCalculator.java import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.lang.*; /** * */ public class SimpleCalculator { public static void main(String[] args) { CalcFrame cf=new CalcFrame(); cf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); cf.setVisible(true); } } class CalcFrame extends JFrame { public CalcFrame() { setTitle("CALCULATOR"); CalcPanel panel=new CalcPanel(); add(panel); pack(); } } class CalcPanel extends JPanel { JButton display; JPanel panel; double result; String lastcmd; boolean start; public CalcPanel() { 15
  • 16. setLayout(new BorderLayout()); result=0; lastcmd="="; start=true; display=new JButton("0"); display.setEnabled(false); add(display,BorderLayout.NORTH); ActionListener insert=new InsertAction(); ActionListener cmd=new CommandAction(); panel=new JPanel(); panel.setLayout(new GridLayout(5,4)); addButton("1",insert); addButton("2",insert); addButton("3",insert); addButton("/",cmd); addButton("4",insert); addButton("5",insert); addButton("6",insert); addButton("*",cmd); addButton("7",insert); addButton("8",insert); addButton("9",insert); addButton("-",cmd); addButton("0",insert); addButton(".",insert); addButton("pow",cmd); addButton("+",cmd); addButton("sin",insert); addButton("cos",insert); addButton("tan",insert); addButton("=",cmd); add(panel, BorderLayout.CENTER); } private void addButton(String label,ActionListener listener) { JButton button=new JButton(label); button.addActionListener(listener); panel.add(button); } private class InsertAction implements ActionListener { public void actionPerformed(ActionEvent ae) { String input=ae.getActionCommand(); if(start==true) { display.setText(""); start=false; 16
  • 17. } if(input.equals("sin")) { Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0; display.setText(""+Math.sin(angle)); } else if(input.equals("cos")) { Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0; display.setText(""+Math.cos(angle)); } else if(input.equals("tan")) { Double angle=Double.parseDouble(display.getText())*2.0*Math.PI/360.0; display.setText(""+Math.tan(angle)); } else display.setText(display.getText()+input); } } private class CommandAction implements ActionListener { public void actionPerformed(ActionEvent ae) { String command=ae.getActionCommand(); if(start==true) { if(command.equals("-")) { display.setText(command); start=false; } else lastcmd=command; } else { calc(Double.parseDouble(display.getText())); lastcmd=command; start=true; } } } public void calc(double x) { if(lastcmd.equals("+")) result=result+x; else if(lastcmd.equals("-")) 17
  • 18. result=result-x; else if(lastcmd.equals("*")) result=result*x; else if(lastcmd.equals("/")) result=result/x; else if(lastcmd.equals("=")) result=x; else if(lastcmd.equals("pow")) { double powval=1.0; for(double i=0.0;i<x;i++) powval=powval*result; result=powval; } display.setText(""+ result); } } 18
  • 19. 8. IMPLEMENTATION OF FIBONACCI SERIES USING FRAMES Write a multi-threaded Java program to print all numbers below 100,000 that are both prime and fibonacci number (some examples are 2, 3, 5, 13, etc.). Design a thread that generates prime numbers below 100,000 and writes them into a pipe. Design another thread that generates fibonacci numbers and writes them to another pipe. The main thread should read both the pipes to identify numbers common to both. ALGORITHM: STEP 1: CreateThread1 which generates prime numbers below 100,000 and store in pipe1. STEP 2: Create Thread2 which generates Fibonacci numbers below 100,000 and store in pipe 2. STEP 3: Write a main program which does the following: (i) Call the two threads created in step1 and step2. (ii) Read the data from pipe1 and pipe 2 and print the numbers common to both. MultiThreadDemo.java import java.util.*; import java.io.*; class Fibonacci extends Thread { private PipedWriter out=new PipedWriter(); public PipedWriter getPipedWriter() { return out; } public void run() { Thread t=Thread.currentThread(); t.setName("Fibonacci"); System.out.println(t.getName()+" Thread started..."); int fibo=0,fibo1=0,fibo2=1; while(true) { try { fibo=fibo1+fibo2; if(fibo>100000) { out.close(); break; } out.write(fibo); sleep(1000); 19
  • 20. } catch(Exception e) { System.out.println("Exception:"+e); } fibo1=fibo2; fibo2=fibo; } System.out.println(t.getName()+" Thread exiting..."); } } class Prime extends Thread { private PipedWriter out1=new PipedWriter(); public PipedWriter getPipedWriter() { return out1; } public void run() { Thread t=Thread.currentThread(); t.setName("Prime"); System.out.println(t.getName() +" Thread Started..."); int prime=1; while(true) { try { if(prime>100000) { out1.close(); break; } if(isPrime(prime)) out1.write(prime); prime++; sleep(0); } catch(Exception e) { System.out.println(t.getName()+" Thread exiting..."); System.exit(0); } } } public boolean isPrime(int n) { int m=(int)Math.round(Math.sqrt(n)); 20
  • 22. 8. IMPLEMENTATION OF FIBONACCI SERIES USING FRAMES Develop a simple OPAC system for library using event-driven and concurrent programming paradigms of Java. Use JDBC to connect to a back-end database. ALGORITHM: STEP 1: Create a Master Database1(Book Details) having the following fields: BookNo.Book Name, Author, No. of pages, Name of Publisher, Cost. STEP 2: Create a Master Database2(User Details) having the following fields : UserID, Department STEP 3: Create a Transaction Database having the following fields: UserID, Book No., Date of Renewal / Date of Return, Fine STEP 4: Create a panel consisting of buttons ADD, UPDATE, DELETE. Associate these button actions with listeners(with Master Database 1) STEP 5: Create a panel consisting of buttons ADD, UPDATE, DELETE. Associate these button actions with listeners(with Master Database 2) STEP 6: Create another panel consisting of buttons UserID, BookID, Return/Renewal,Fine. STEP 7: Associate these buttons with listeners(with Transaction Database). OpacSystem.java import java.sql.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; /** * */ public class OpacSystem implements ActionListener { JRadioButton author=new JRadioButton("Search By Author"); JRadioButton book=new JRadioButton("Search by Book"); JTextField txt=new JTextField(30); JLabel label=new JLabel("Enter Search Key"); JButton search=new JButton("SEARCH"); JFrame frame=new JFrame(); JTable table; DefaultTableModel model; String query="select*from opacTab"; public OpacSystem() { frame.setTitle("OPAC SYSTEM"); frame.setSize(800,500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); 22
  • 23. JPanel p1=new JPanel(); p1.setLayout(new FlowLayout()); p1.add(label); p1.add(txt); ButtonGroup bg=new ButtonGroup(); bg.add(author); bg.add(book); JPanel p2=new JPanel(); p2.setLayout(new FlowLayout()); p2.add(author); p2.add(book); p2.add(search); search.addActionListener(this); JPanel p3=new JPanel(); p3.setLayout(new BorderLayout()); p3.add(p1,BorderLayout.NORTH); p3.add(p2,BorderLayout.CENTER); frame.add(p3,BorderLayout.NORTH); addTable(query); frame.setVisible(true); } public void addTable(String str) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:opacDS"); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery(str); ResultSetMetaData rsmd=rs.getMetaData(); int cols=rsmd.getColumnCount(); model=new DefaultTableModel(1,cols); table=new JTable(model); String[] tabledata=new String[cols]; int i=0; while(i<cols) { tabledata[i]=rsmd.getColumnName(i+1); i++; } model.addRow(tabledata); while(rs.next()) { for(i=0;i<cols;i++) tabledata[i]=rs.getObject(i+1).toString(); model.addRow(tabledata); } frame.add(table,BorderLayout.CENTER); 23
  • 24. con.close(); } catch(Exception e) { System.out.println("Exception:"+e); } } public void actionPerformed(ActionEvent ae) { if(author.isSelected()) query="select*from opacTab where AUTHOR like '"+txt.getText()+"%'"; if(book.isSelected()) query="select*from opacTab where BOOK like '"+txt.getText()+"%'"; while(model.getRowCount()>0) model.removeRow(0); frame.remove(table); addTable(query); } 24
  • 25. 10. IMPLEMENTATION OF MULTITHREADED ECHO SERVER & ECHO CLIENT Develop multi-threaded echo server and a corresponding GUI client in Java. ALGORITHM FOR SERVER: STEP 1: Establish the connection of socket. STEP 2: Assign the local Protocol address to the socket. STEP 3: Move the socket from closed to listener state and provide maximum no. of Connections. STEP 4: Create a new socket connection using client address. STEP 5: Read the data from the socket. STEP 6: Write the data into socket. STEP 7: Close the socket. EchoServer.java import java.io.*; import java.net.*; /** * */ public class EchoServer { public static void main(String [] args) { System.out.println("Server Started...."); try { ServerSocket ss=new ServerSocket(300); while(true) { Socket s= ss.accept(); Thread t = new ThreadedServer(s); t.start(); } } catch(Exception e) { System.out.println("Error: " + e); } } } class ThreadedServer extends Thread { Socket soc; public ThreadedServer(Socket soc) 25
  • 26. { this.soc=soc; } public void run() { try { BufferedReader in=new BufferedReader(new InputStreamReader(soc.getInputStream())); PrintWriter out=new PrintWriter(soc.getOutputStream()); String str=in.readLine(); System.out.println("Message From Client:"+str); out.flush(); out.println("Message To Client:"+str); out.flush(); } catch(Exception e) { System.out.println("Exception:"+e); } } } ALGORITHM FOR CLIENT: STEP 1: Open the socket. STEP 2: Get the host name and port number from client. STEP 3: Write a request to the buffer that contain the request number as a byte to the output stream. STEP 4: Get the message from the user. STEP 5: Write to the socket. STEP 6: Set the write operation for success. STEP 7: Read the contents from the socket / Buffer. STEP 8: Close the socket. EchoClient.java import java.net.*; import java.io.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * */ class EchoClient extends JFrame { 26
  • 27. JTextArea ta; JTextField msg; JPanel panel; JScrollPane scroll; JButton b1=new JButton("Close"); JButton b2=new JButton("Send"); JLabel l1=new JLabel("Echo Client GUI"); Container c; EchoClient() { c=getContentPane(); setSize(300,470); setTitle("GUI Client"); panel=new JPanel(); msg=new JTextField(20); panel.setLayout(new FlowLayout(FlowLayout.CENTER)); ta=new JTextArea(20,20); scroll=new JScrollPane(ta); panel.add(l1); panel.add(ta); panel.add(msg); panel.add(b2); panel.add(b1); c.add(panel); b2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { try { Socket s=new Socket("localhost",300); BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream())); PrintWriter out=new PrintWriter(new OutputStreamWriter(s.getOutputStream())); out.println(msg.getText()); out.flush(); String temp =ta.getText(); if(temp.equalsIgnoreCase("quit")) { System.exit(0); } msg.setText(""); ta.append("n"+in.readLine()); } catch (IOException e) { ta.setText("Exception:"+e); 27
  • 28. } } }); b1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); } public static void main(String args[]) { EchoClient frame=new EchoClient(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } 28
  • 29. 11. MINI PROJECT Develop a programmer's editor in Java that supports syntax high lighting, compilation support, debugging support, etc. ALGORITHM: STEP 1: Create a panel consisting of menu bar containing File, Edit, Compile and Debug. STEP 2: Add submenus for each of the menu. File – New, Open, Save, Quit. Edit – Cut, Copy, Paste. Compile – Compile, Link Debug – Inspect, Call Stack, Watches, BreakPoints. STEP 3: Associate these event sources with Listeners. 29
  翻译: