0% found this document useful (0 votes)
3K views23 pages

Java Lab Manual - 5th Sem Cse

This document contains 6 Java programs that demonstrate various concepts: 1. A Rational Number class that efficiently represents fractions 2. A Date class that formats dates similarly to java.util.Date 3. A Lisp-like List class that implements basic operations like car, cdr, cons 4. An interface and implementation for an ADT Stack 5. A Vehicle class hierarchy demonstrating polymorphism 6. Classes for Currency, Rupee and Dollar that demonstrate object serialization
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3K views23 pages

Java Lab Manual - 5th Sem Cse

This document contains 6 Java programs that demonstrate various concepts: 1. A Rational Number class that efficiently represents fractions 2. A Date class that formats dates similarly to java.util.Date 3. A Lisp-like List class that implements basic operations like car, cdr, cons 4. An interface and implementation for an ADT Stack 5. A Vehicle class hierarchy demonstrating polymorphism 6. Classes for Currency, Rupee and Dollar that demonstrate object serialization
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

CS58 / CS2309 Java Lab

1. Rational Number Class in Java


AIM: (i) (ii) (iii) To write a program in Java with the following: Develop a Rational number class. Use JavaDoc comments for documentation Your implementation should use efficient representation for a rational number, i.e. (500/1000) should be represented as (1/2). PROGRAM: [Link] import [Link].*; /** *@author Sreekandan.K */ public class RationalClass { /** The Numerator part of Rational */ private int numerator; /** 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) { [Link]("No Common Divisor for Numerator and Denominator"); [Link]=numerator; [Link]=denominator; } else { [Link]=numerator/g; [Link]=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) { if(d==0) return n; else return gcd(d,n%d); } public static void main(String[] args) { Scanner input=new Scanner([Link]); [Link]("Enter Numerator : "); int numerator=[Link](); [Link]("Enter Denominator : "); int denominator=[Link](); Rational rational = new Rational(numerator,denominator); String str=[Link](); [Link]("Efficient Representation for the rational number :"

+str);

} }

2. Date Class in Java


AIM: To develop Date class in Java similar to the one available in [Link] package. Use JavaDoc comments for documentation. PROGRAM: [Link] import [Link].*; import [Link].*; /** *Class DateFormatDemo formats the date and time by using [Link] package *@author Sreekandan.K */ public class DateFormatDemo { public static void main(String args[]) { /** * @see [Link] package */ Date date=new Date(); /** * @see [Link] package */ DateFormat df; [Link]("Current Date and Time - Available in [Link] Package:"); [Link]("-------------------------------------------------------"); [Link](date); [Link](); [Link]("Formatted Date - Using DateFormat Class from [Link] Package:"); [Link]("---------------------------------------------------------------"); df=[Link]([Link]); [Link]("Default Date Format:"+[Link](date)); df=[Link]([Link]); [Link]("Date In Short Format:"+[Link](date)); df=[Link]([Link]); [Link]("Date In Medium Format:"+[Link](date)); df=[Link]([Link]); [Link]("Date In Long Format:"+[Link](date)); df=[Link]([Link]);

[Link]("Date In Full Format:"+[Link](date)); [Link](); [Link]("Formatted Time - Using DateFormat Class from [Link] Package:"); [Link]("---------------------------------------------------------------"); df=[Link]([Link]); [Link]("Default Time Format:"+[Link](date)); df=[Link]([Link]); [Link]("Time In Short Format:"+[Link](date)); df=[Link]([Link]); [Link]("Time In Medium Format:"+[Link](date)); df=[Link]([Link]); [Link]("Time In Long Format:"+[Link](date)); df=[Link]([Link]); [Link]("Time In Full Format:"+[Link](date)); [Link](); [Link]("Formatted Date and Time - Using SimpleDateFormat Class from [Link] Package:"); [Link]("------------------------------------------------------------------------------"); /** * @see [Link] package */ SimpleDateFormat sdf; sdf=new SimpleDateFormat("dd MMM yyyy hh:mm:sss:S E w D zzz"); [Link]([Link](date)); } }

3. Lisp-like List in Java


AIM: To implement Lisp-like list in Java that performs the basic operations such as 'car', 'cdr', and 'cons'. PROGRAM: [Link] import [Link].*; /** *@author Sreekandan.K */ class Lisp { public Vector car(Vector v) { Vector elt=new Vector();

[Link]([Link](0)); return elt; } public Vector cdr(Vector v) { Vector elt=new Vector(); for(int i=1;i<[Link]();i++) [Link]([Link](i)); return elt; } public Vector cons(int x, Vector v) { [Link](x,0); return v; } } class LispOperation { public static void main(String[] args) { Lisp L=new Lisp(); Vector v=new Vector(4,1); [Link](3); [Link](0); [Link](2); [Link](5); [Link]("Basic Lisp Operations"); [Link]("---------------------"); [Link]("The Elements of the List are:"+v); [Link]("Lisp Operation-CAR:"+[Link](v)); [Link]("Lisp Operation-CDR:"+[Link](v)); [Link]("Elements of the List After CONS:"+[Link](9,v)); } }

4. Java Interface for ADT Stack


AIM: To Design a Java interface for ADT Stack with the following: (i) Develop a class that implement this interface. (ii)Provide necessary exception handling in the implementation. PROGRAM: [Link]

import [Link].*; import [Link].*; 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([Link]); public void push() { try { [Link]("Enter The Element of Stack"); int elt=[Link](); arr[++top]=elt; } catch (Exception e) { [Link]("e"); } } public void pop() { int pop=arr[top]; top--; [Link]("Popped Element Is:"+pop); } public void display() { if(top<0) { [Link]("Stack Is Empty"); return; } else { String str=" "; for(int i=0;i<=top;i++) str=str+" "+arr[i]; [Link]("Stack Elements Are:"+str);

} } } /** *@author Sreekandan.K */ class StackADT { public static void main(String arg[])throws IOException { [Link]("JAVA INTERFACE FOR STACK ADT"); [Link]("============================"); Scanner in=new Scanner([Link]); stack st=new stack(); int no=0; do { [Link]("[Link] \[Link] \[Link] \[Link]"); [Link](); [Link]("Enter Your Choice:"); no=[Link](); switch(no) { case 1: [Link](); break; case 2: [Link](); break; case 3: [Link](); break; case 4: [Link](0); } } while(no<=5); } }

5. Vehicle Class Hierarchy in Java


AIM: To design a vehicle class hierarchy in Java that demonstrates the concept of polymorphism.

PROGRAM: [Link] import [Link].*; class Vehicle { String regno; int model; Vehicle(String r, int m) { regno=r; model=m; } void display() { [Link]("Registration Number:"+regno); [Link]("Model Number:"+model); } } class Twowheeler extends Vehicle { int wheel; Twowheeler(String r,int m,int n) { super(r,m); wheel=n; } void display() { [Link]("Vehicle : Two Wheeler"); [Link]("====================="); [Link](); [Link]("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() { [Link]("Vehicle : Three Wheeler");

[Link]("======================="); [Link](); [Link]("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() { [Link]("Vehicle : Four Wheeler"); [Link]("======================"); [Link](); [Link]("Number of Leaf:"+leaf); } } /** *@author Sreekandan.K */ public class VehicleDemo { public static void main(String arg[]) { Twowheeler two=new Twowheeler("TN75 9843", 2011,2); Threewheeler three=new Threewheeler("TN30 8766", 2010,3); Fourwheeler four=new Fourwheeler("TN15 2630",2009,4); [Link](); [Link](); [Link](); } }

6. Object Serialization
AIM: (i) (ii) (iii) (iv) To write a program in java to demonstrate object serialization with the following: 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 leave the value if it reads a Rupee.

PROGRAM: [Link] import [Link].*; import [Link].*; abstract class Currency implements Serializable { protected double money; public abstract double getValue(); public abstract String printObj(); public Currency(double money) { [Link]=money; } } class Dollar extends Currency { public Dollar(int money) { super(money); } public double getValue() { return [Link]*51; } public String printObj() { String object="Object Name : Dollar\nUSD : $"+[Link]+"\nINR : Rs"+getValue()+"\n"; return object; } } class Rupee extends Currency { public Rupee(int amount) { super(amount); } public double getValue() { return [Link]; } public String printObj() { String object="Object Name : Rupee \nINR : Rs "+getValue()+"\n"; return object;

} } /** *@author Sreekandan.K */ public class writeObj { public static void main(String[] args) throws FileNotFoundException,IOException { FileOutputStream fos=new FileOutputStream("[Link]"); ObjectOutputStream oos=new ObjectOutputStream(fos); Random rand=new Random(); for(int i=0;i<10;i++) { Object[] obj={new Rupee([Link](100)),new Dollar([Link](100))}; Currency currency=(Currency)obj[[Link](2)]; [Link](currency); } [Link](null); [Link](); } } [Link] import [Link].*; /** *@author Sreekandan.K */ public class readObj { public static void main(String[] args) throws IOException,ClassNotFoundException { Currency currency=null; FileInputStream fis=new FileInputStream("[Link]"); ObjectInputStream ois=new ObjectInputStream(fis); while((currency=(Currency)[Link]())!=null) { [Link]([Link]()); } [Link](); } }

7. Scientific Calculator in Java


AIM:

To design a scientific calculator using event-driven programming paradigm of Java. PROGRAM: [Link] import [Link].*; import [Link].*; import [Link].*; import [Link].*; /** *@author Sreekandan.K */ public class SimpleCalculator { public static void main(String[] args) { CalcFrame cf=new CalcFrame(); [Link](JFrame.EXIT_ON_CLOSE); [Link](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() { setLayout(new BorderLayout()); result=0; lastcmd="="; start=true; display=new JButton("0");

[Link](false); add(display,[Link]); ActionListener insert=new InsertAction(); ActionListener cmd=new CommandAction(); panel=new JPanel(); [Link](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, [Link]); } private void addButton(String label,ActionListener listener) { JButton button=new JButton(label); [Link](listener); [Link](button); } private class InsertAction implements ActionListener { public void actionPerformed(ActionEvent ae) { String input=[Link](); if(start==true) { [Link](""); start=false; } if([Link]("sin")) {

Double angle=[Link]([Link]())*2.0*[Link]/360.0; [Link](""+[Link](angle)); } else if([Link]("cos")) { Double angle=[Link]([Link]())*2.0*[Link]/360.0; [Link](""+[Link](angle)); } else if([Link]("tan")) { Double angle=[Link]([Link]())*2.0*[Link]/360.0; [Link](""+[Link](angle)); } else [Link]([Link]()+input); } } private class CommandAction implements ActionListener { public void actionPerformed(ActionEvent ae) { String command=[Link](); if(start==true) { if([Link]("-")) { [Link](command); start=false; } else lastcmd=command; } else { calc([Link]([Link]())); lastcmd=command; start=true; } } } public void calc(double x) { if([Link]("+")) result=result+x; else if([Link]("-")) result=result-x;

else if([Link]("*")) result=result*x; else if([Link]("/")) result=result/x; else if([Link]("=")) result=x; else if([Link]("pow")) { double powval=1.0; for(double i=0.0;i<x;i++) powval=powval*result; result=powval; } [Link](""+ result); } }

8. Multithreading in Java
AIM: (i) (ii) (iii) To write a multi-threaded java program with the following: 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. Design a main thread should read both the pipes to identify numbers common to both prime and Fibonacci and print all the numbers common to both prime and Fibonacci. PROGRAM: [Link] import [Link].*; import [Link].*; class Fibonacci extends Thread { private PipedWriter out=new PipedWriter(); public PipedWriter getPipedWriter() { return out; } public void run() { Thread t=[Link](); [Link]("Fibonacci"); [Link]([Link]()+" Thread started..."); int fibo=0,fibo1=0,fibo2=1;

while(true) { try { fibo=fibo1+fibo2; if(fibo>100000) { [Link](); break; } [Link](fibo); sleep(1000); } catch(Exception e) { [Link]("Exception:"+e); } fibo1=fibo2; fibo2=fibo; } [Link]([Link]()+" Thread exiting..."); } } class Prime extends Thread { private PipedWriter out1=new PipedWriter(); public PipedWriter getPipedWriter() { return out1; } public void run() { Thread t=[Link](); [Link]("Prime"); [Link]([Link]() +" Thread Started..."); int prime=1; while(true) { try { if(prime>100000) { [Link](); break; } if(isPrime(prime))

[Link](prime); prime++; sleep(0); } catch(Exception e) { [Link]([Link]()+" Thread exiting..."); [Link](0); } } } public boolean isPrime(int n) { int m=(int)[Link]([Link](n)); if(n==1||n==2) return true; for(int i=2;i<=m;i++) if(n%i==0) return false; return true; } } /** *@author Sreekandan.K */ public class MultiThreadDemo { public static void main(String[] args)throws Exception { Thread t=[Link](); [Link]("Main"); [Link]([Link]()+" Thread Started..."); Fibonacci fibObj=new Fibonacci(); Prime primeObj=new Prime(); PipedReader pr=new PipedReader([Link]()); PipedReader pr1=new PipedReader([Link]()); [Link](); [Link](); int fib=[Link](),prm=[Link](); [Link]("The numbers common to PRIME and FIBONACCI:"); while((fib!=-1)&&(prm!=-1)) { while(prm<=fib) { if(fib==prm) [Link](prm);

prm=[Link](); } fib=[Link](); } [Link]([Link]()+ " Thread exiting..."); } }

9. OPAC System
AIM: To develop a simple OPAC system for library using event-driven programming paradigms of Java. Use JDBC to connect to a back-end database. PROGRAM: [Link] import [Link].*; import [Link].*; import [Link].*; import [Link].*; import [Link].*; /** *@author Sreekandan.K */ 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() { [Link]("OPAC SYSTEM"); [Link](800,500); [Link](JFrame.EXIT_ON_CLOSE); [Link](new BorderLayout()); JPanel p1=new JPanel(); [Link](new FlowLayout()); [Link](label);

[Link](txt); ButtonGroup bg=new ButtonGroup(); [Link](author); [Link](book); JPanel p2=new JPanel(); [Link](new FlowLayout()); [Link](author); [Link](book); [Link](search); [Link](this); JPanel p3=new JPanel(); [Link](new BorderLayout()); [Link](p1,[Link]); [Link](p2,[Link]); [Link](p3,[Link]); addTable(query); [Link](true); } public void addTable(String str) { try { [Link]("[Link]"); Connection con=[Link]("jdbc:odbc:opacDS"); Statement stmt=[Link](); ResultSet rs=[Link](str); ResultSetMetaData rsmd=[Link](); int cols=[Link](); model=new DefaultTableModel(1,cols); table=new JTable(model); String[] tabledata=new String[cols]; int i=0; while(i<cols) { tabledata[i]=[Link](i+1); i++; } [Link](tabledata); while([Link]()) { for(i=0;i<cols;i++) tabledata[i]=[Link](i+1).toString(); [Link](tabledata); } [Link](table,[Link]); [Link]();

} catch(Exception e) { [Link]("Exception:"+e); } } public void actionPerformed(ActionEvent ae) { if([Link]()) query="select*from opacTab where AUTHOR like '"+[Link]()+"%'"; if([Link]()) query="select*from opacTab where BOOK like '"+[Link]()+"%'"; while([Link]()>0) [Link](0); [Link](table); addTable(query); } public static void main(String[] args) { OpacSystem os=new OpacSystem(); } }

10.

Multi-threaded Echo Server


To develop a multi-threaded echo server and a corresponding GUI client in Java.

AIM: PROGRAM: [Link] import [Link].*; import [Link].*; /** *@author Sreekandan.K */ public class EchoServer { public static void main(String [] args) { [Link]("Server Started...."); try { ServerSocket ss=new ServerSocket(300); while(true)

{ Socket s= [Link](); Thread t = new ThreadedServer(s); [Link](); } } catch(Exception e) { [Link]("Error: " + e); } } } class ThreadedServer extends Thread { Socket soc; public ThreadedServer(Socket soc) { [Link]=soc; } public void run() { try { BufferedReader in=new BufferedReader(new InputStreamReader([Link]())); PrintWriter out=new PrintWriter([Link]()); String str=[Link](); [Link]("Message From Client:"+str); [Link](); [Link]("Message To Client:"+str); [Link](); } catch(Exception e) { [Link]("Exception:"+e); } } } [Link] import [Link].*; import [Link].*; import [Link].*; import [Link].*; import [Link].*; /** *@author Sreekandan.K

*/ class EchoClient extends JFrame { 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); [Link](new FlowLayout([Link])); ta=new JTextArea(20,20); scroll=new JScrollPane(ta); [Link](l1); [Link](ta); [Link](msg); [Link](b2); [Link](b1); [Link](panel); [Link](new ActionListener() { public void actionPerformed(ActionEvent ae) { try { Socket s=new Socket("localhost",300); BufferedReader in=new BufferedReader(new InputStreamReader([Link]())); PrintWriter out=new PrintWriter(new OutputStreamWriter([Link]())); [Link]([Link]()); [Link](); String temp =[Link](); if([Link]("quit")) { [Link](0); } [Link](""); [Link]("\n"+[Link]()); }

catch (IOException e) { [Link]("Exception:"+e); } } }); [Link](new ActionListener() { public void actionPerformed(ActionEvent e) { [Link](0); } }); } public static void main(String args[]) { EchoClient frame=new EchoClient(); [Link](JFrame.EXIT_ON_CLOSE); [Link](true); } }

You might also like