Prepared by S.VARADHARAJAN ASSISTANT PROFESSOR DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
www.vidyarthiplus.com www.vidyarthiplus.com 2
CS2309 JAVA LAB L T P C 0 0 3 2
1. 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 (). 2. Develop Date class in Java similar to the one available in java.util package. Use JavaDoc 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, 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. TOTAL= 45
PERIODS
www.vidyarthiplus.com www.vidyarthiplus.com 3
REQUIREMENTS
HARDWARE:
Pentium IV with 2 GB RAM, 160 GB HARD Disk, Monitor 1024 x 768 colour 60 Hz. 30 Nodes
SOFTWARE:
Windows /Linux operating system JDK 1.6(or above) 30 user license
www.vidyarthiplus.com www.vidyarthiplus.com 4
TABLE OF CONTENTS
LIST OF EXPERIMENTS 1 Rational number 2 Date class in Java 3 Implement Lisp-like list in Java. 4 Java interface for ADT Stack using array and the sing linked- list. 5 Polymorphism 6 object serialization 7 scientific calculator 8 Multi-threaded Java program Fibonacci number (some examples are 2, 3, 5, 13, etc.). prime numbers below 100,000 and writes them into a pipe Main thread should read both the pipes. 9 A Simple OPAC system for library 10 Multi-threaded echo server GUI client. 11 [Mini-Project] programmers editor.
www.vidyarthiplus.com www.vidyarthiplus.com 5
Ex No1: Rational Numbers
AIM To write a Java Program to develop a class for Rational numbers.
ALGORITHM:
Step 1:-Declare a class called Rational and invoke a function called gcd(a,b). Step 2:-Find out the reminder when a is divided by b and pass it as a parameter to the function. Step 3:-Create an object for the class and declare the required string and integer variables. Step 4:-Create an object of class DataInputStream .Read the numbers through the ReadLine() method into the object. Step 5:-Convert the input accepted into Integers through the parseInt method and store them in variables a and b. Step 6:-store the value returned by the function GCD in variable l. Step 7:-Divide a by l and b by l and store them in variables x and y.
Program:-
import java.io.*; class rational1 { public rational1(){}
public long gcd(long a,long b) { if(b==0) return a; else return gcd(b,a%b); } } public class rational www.vidyarthiplus.com www.vidyarthiplus.com 6
{ public static void main(String args[])throws IOException { /** * create and initialize a new Rational object */ rational1 r=new rational1(); /** * The Numerator and Denominator part of Rational */ long a,b,x,y; String str; DataInputStream in= new DataInputStream(System.in); System.out.println("Enter the value for A"); str=in.readLine(); a=Integer.parseInt(str); System.out.println("Enter the value for B"); str=in.readLine(); b=Integer.parseInt(str);
long l=r.gcd(a,b); System.out.println(); System.out.println("The GCD of the number is:"+l); x=a/l; y=b/l; System.out.println(); System.out.println("The resultant value is: "+x+"/"+y); } }
www.vidyarthiplus.com www.vidyarthiplus.com 7
Output
Enter the value for A 500 Enter the value for B 1000
The GCD of the number is:500
The resultant value is: 1/2
Result Thus the above program was executed and verified successfully.
www.vidyarthiplus.com www.vidyarthiplus.com 8
Ex No 2: Date Class in Java
AIM To design a Date class in Java.
ALGORITHM:- Step 1: Declare a class called Date example and create an object called date. Step 2:- Display the Date and Time through these objects with the Methods in Date Class. Step 3:- Declare two objects called start time and end time for this class . Step 4:- Create another object called changed object and display the changed time with the calculation Step 5:- In the main function create object for the class Date and display the time and date accordingly.
www.vidyarthiplus.com www.vidyarthiplus.com 9
SOURCE CODE
import java.util.Date; import java.text.ParseException; import java.text.SimpleDateFormat; public class DateExample { private static void DateExample() { Date date = new Date(); System.out.println("Current Date and Time is : " + date); System.out.println(); System.out.println("Date object showing specific date and time"); Date particulardate1 = new Date(2000,3,12); Date particulardate2 = new Date(2000,4,12,9,10); System.out.println(); System.out.println("First Particular date : " + particulardate1); System.out.println("Second Particular date: " + particulardate2); System.out.println(); System.out.println("Demo of getTime() method returning milliseconds"); System.out.println(); Date strtime = new Date(); System.out.println("Start Time: " + strtime); Date endtime = new Date(); System.out.println("End Time is: " + endtime); long elapsed_time = endtime.getTime() - strtime.getTime(); System.out.println("Elapsed Time is:" + elapsed_time + "milliseconds"); System.out.println(); System.out.println("Changed date object using setTime() method"); System.out.println(); Date chngdate = new Date(); System.out.println("Date before change is: " + chngdate); chngdate.setHours(12); System.out.println("Now the Changed date is: " + chngdate); System.out.println(); } www.vidyarthiplus.com www.vidyarthiplus.com 10
public static void main(String[] args) { System.out.println(); DateExample(); } }
OUTPUT
D:\java>java DateExample
Current Date and Time is : Thu May 05 09:56:18 IST 2011
Date object showing specific date and time
First Particular date : Thu Apr 12 00:00:00 IST 3900 Second Particular date: Sat May 12 09:10:00 IST 3900
Demo of getTime() method returning milliseconds
Start Time: Thu May 05 09:56:18 IST 2011 End Time is: Thu May 05 09:56:18 IST 2011 Elapsed Time is:0 milliseconds
Changed date object using setHours() method
Date before change is: Thu May 05 09:56:18 IST 2011 Now the Changed date is: Thu May 05 12:56:18 IST 2011
Result Thus the above program was executed and verified successfully.
www.vidyarthiplus.com www.vidyarthiplus.com 11
3.Implement Lisp-like list in Java.
Aim: To Implement basic operations such as 'car', 'cdr', and 'cons' using Lisp-like list in Java. If L is a list [3, 0, 2, 5], L.car() returns 3, while L.cdr() returns [0,2,5]
public interface ADTStack { public void push (Object item); public Object pop (); }
www.vidyarthiplus.com www.vidyarthiplus.com 18
Output:-
C:\>java ADTArray 100 Hi
C:\>java ADTList 100 Hi
C:\>java ADTStack Exception in thread main java.lang.NoSuchMethodError:main
Result: Thus the above program was executed and verified successfully.
www.vidyarthiplus.com www.vidyarthiplus.com 19
Ex no: 5 Polymorphism Aim:- To develop a vehicle class hierarchy in Java to demonstrate the concept of polymorphism.
Algorithm:-
Step 1:-Declare a super class called vehicle with data elements doors,wheels and seats.
Step 2:-Derive another class called car and invoke a function tostring() to display the variables.
Step 3:-Derive another class called motorcycle with same data and method called setseats() .
Step 4:-Declare another sub class called Truck with 2 constructors and finally assign values to variables.
Step 5:-In the main function, create an object for class motorcycle and display all details of sub classes through object.
www.vidyarthiplus.com www.vidyarthiplus.com 20
Sourcecode:-
//This is the class that will be inherited public class Vehicle { public int doors; public int seats; public int wheels; Vehicle() { wheels=4; doors=4; seats=4; } } //This class inherits Vehicle.java public class Car extends Vehicle { public String toString() { return "This car has "+seats+" Seats, "+doors+" Doors "+ "and "+wheels+" wheels."; } } //This class inherits Vehicle.java public class MotorCycle extends Vehicle { MotorCycle() { wheels=2; doors=0; seats=1; } www.vidyarthiplus.com www.vidyarthiplus.com 21
void setSeats(int num) { seats=num; } public String toString() { return "This motorcycle has "+seats+" Seats, "+doors+" Doors "+ "and "+wheels+" wheels."; } } //This class inherits Vehicle.java public class Truck extends Vehicle { boolean isPickup; Truck() { isPickup=true; } Truck(boolean aPickup) { this(); isPickup=aPickup; } Truck(int doors, int seats, int inWheels, boolean isPickup) { this.doors=doors; this.seats=seats; wheels=inWheels; this.isPickup=isPickup; } public String toString() { return "This "+(isPickup?"pickup":"truck")+ " has "+seats+" Seats, "+doors+" Doors "+"and "+wheels+" wheels."; www.vidyarthiplus.com www.vidyarthiplus.com 22
} } //This class tests the classes that inherit Vehicle.java public class VehiclesTest { public static void main(String args[]) { MotorCycle mine = new MotorCycle(); System.out.println(mine); Car mine2 = new Car(); System.out.println(mine2); mine2.doors=2; System.out.println(mine2); Truck mine3 = new Truck(); System.out.println(mine3); Truck mine4 = new Truck(false); mine4.doors=2; System.out.println(mine4);
} }
www.vidyarthiplus.com www.vidyarthiplus.com 23
Output
This motorcycle has 1 Seats, 0 Doors and 2 wheels This car has 4 Seats, 4 Doors and 4 wheels This car has 4 Seats, 2 Doors and 4 wheels This pickup has 4 Seats, 4 Doors and 4 wheels This truck has 4 Seats, 2 Doors and 4 wheels
Result: Thus the above program was executed and verified successfully.
www.vidyarthiplus.com www.vidyarthiplus.com 24
Ex No:-6 Object Serialization
Aim:-To write a Java Program to randomly generate objects and write them into a file using concept of Object Serialization.
Algorithm:-
Step 1:Declare a class called Currency .Open a file in output mode with a name.
Step 2:-Write new data into the object using writeobject() method.
Step 3:-Similarly create an input stream object .Read it both in terms of Dollars and Rupees.close the output object.
Step 4:-derive a class called Dollar which implements serializable interface.Invoke a constructor and function to display the data.
Step 5:Similarly declare a class called Rupee with private variables and use print function to display the variables.
Step 6: terminate the execution. The output is displayed as dollar to rupee conversion and vice versa.
Sourcecode:-
// Currency conversion import java.io.*; public class Currency { www.vidyarthiplus.com www.vidyarthiplus.com 25
Result: Thus the above program was executed and verified successfully.
www.vidyarthiplus.com www.vidyarthiplus.com 28
EX NO: 7 Scientific Calculator
AIM: To design a scientific calculator using event-driven programming paradigm of Java.
ALGORITHM: Step1: Define a class CalcFrame for creating a calculator frame and added windolistener to close the calculator Step2: create instance of object for View menu and various other objects Step3: add a listener to receive item events when the state of an item changes Step4: Define the methods for all operations of stientific calculator Step5::Get the input and display the result
PROGRAM
/** Scientific calculator*/
import java.awt.*; import java.awt.event.*; // class CalcFrame for creating a calculator frame and added windolistener to // close the calculator class CalcFrame extends Frame { CalcFrame( String str) { // call to superclass super(str); // to close the calculator(Frame) addWindowListener(new WindowAdapter() { public void windowClosing (WindowEvent we) { System.exit(0); } }); } }
// main class Calculator implemnets two // interfaces ActionListener // and ItemListener public class Calculator implements ActionListener, ItemListener { // creating instances of objects www.vidyarthiplus.com www.vidyarthiplus.com 29
CalcFrame fr; TextField display; Button key[] = new Button[20]; // creates a button object array of 20 Button clearAll, clearEntry, round; Button scientificKey[] = new Button[10]; // creates a button array of 8 // declaring variables boolean addButtonPressed, subtractButtonPressed, multiplyButtonPressed; boolean divideButtonPressed, decimalPointPressed, powerButtonPressed; boolean roundButtonPressed = false; double initialNumber;// the first number for the two number operation double currentNumber = 0; // the number shown in the screen while it is being pressed int decimalPlaces = 0;
// main function public static void main (String args[]) { // constructor Calculator calc = new Calculator(); calc.makeCalculator(); }
public void makeCalculator() { // size of the button final int BWIDTH = 25; final int BHEIGHT = 25; int count =1; // create frame for the calculator fr = new CalcFrame("Scientific Calculator"); // set the size fr.setSize(300,350); fr.setBackground(Color.blue);; fr.setLayout(null); // set the initial numbers that is 1 to 9 for (int row = 0; row < 3; ++row) { for (int col = 0; col < 3; ++col) { // this will set the key from 1 to 9 key[count] = new Button(Integer.toString(count)); key[count].addActionListener(this); // set the boundry for the keys key[count].setBounds(30*(col + 1), 30*(row + 4),BWIDTH,BHEIGHT); key[count].setBackground(Color.yellow); // add to the frame fr.add(key[count++]); } }
// Now create, addlistener and add to frame all other keys //0 key[0] = new Button("0"); key[0].addActionListener(this); key[0].setBounds(30,210,BWIDTH,BHEIGHT); www.vidyarthiplus.com www.vidyarthiplus.com 30
key[0].setBackground(Color.yellow); fr.add(key[0]); //decimal key[10] = new Button("."); key[10].addActionListener(this); key[10].setBounds(60,210,BWIDTH,BHEIGHT); key[10].setBackground(Color.yellow); fr.add(key[10]); //equals to key[11] = new Button("="); key[11].addActionListener(this); key[11].setBounds(90,210,BWIDTH,BHEIGHT); key[11].setBackground(Color.yellow); fr.add(key[11]); //multiply key[12] = new Button("*"); key[12].addActionListener(this); key[12].setBounds(120,120,BWIDTH,BHEIGHT); key[12].setBackground(Color.yellow); fr.add(key[12]); //divide key[13] = new Button("/"); key[13].addActionListener(this); key[13].setBounds(120,150,BWIDTH,BHEIGHT); key[13].setBackground(Color.yellow); fr.add(key[13]); //addition key[14] = new Button("+"); key[14].addActionListener(this); key[14].setBounds(120,180,BWIDTH,BHEIGHT); key[14].setBackground(Color.yellow); fr.add(key[14]); //subtract key[15] = new Button("-"); key[15].addActionListener(this); key[15].setBounds(120,210,BWIDTH,BHEIGHT); key[15].setBackground(Color.yellow); fr.add(key[15]); //reciprocal key[16] = new Button("1/x"); key[16].addActionListener(this); key[16].setBounds(150,120,BWIDTH,BHEIGHT); key[16].setBackground(Color.yellow); fr.add(key[16]); //power key[17] = new Button("x^n"); key[17].addActionListener(this); key[17].setBounds(150,150,BWIDTH,BHEIGHT); key[17].setBackground(Color.yellow); fr.add(key[17]); www.vidyarthiplus.com www.vidyarthiplus.com 31
//change sign key[18] = new Button("+/-"); key[18].addActionListener(this); key[18].setBounds(150,180,BWIDTH,BHEIGHT); key[18].setBackground(Color.yellow); fr.add(key[18]); //factorial key[19] = new Button("x!"); key[19].addActionListener(this); key[19].setBounds(150,210,BWIDTH,BHEIGHT); key[19].setBackground(Color.yellow); fr.add(key[19]); // CA clearAll = new Button("CA"); clearAll.addActionListener(this); clearAll.setBounds(30, 240, BWIDTH+20, BHEIGHT); clearAll.setBackground(Color.yellow); fr.add(clearAll); // CE clearEntry = new Button("CE"); clearEntry.addActionListener(this); clearEntry.setBounds(80, 240, BWIDTH+20, BHEIGHT); clearEntry.setBackground(Color.yellow); fr.add(clearEntry); // round round = new Button("Round"); round.addActionListener(this); round.setBounds(130, 240, BWIDTH+20, BHEIGHT); round.setBackground(Color.yellow); fr.add(round); // set display area display = new TextField("0"); display.setBounds(30,90,150,20); display.setBackground(Color.white);
// key for scientific calculator // Sine scientificKey[0] = new Button("Sin"); scientificKey[0].addActionListener(this); scientificKey[0].setBounds(180, 120, BWIDTH + 10, BHEIGHT); scientificKey[0].setVisible(true); scientificKey[0].setBackground(Color.yellow); fr.add(scientificKey[0]); // cosine scientificKey[1] = new Button("Cos"); scientificKey[1].addActionListener(this); scientificKey[1].setBounds(180, 150, BWIDTH + 10, BHEIGHT); scientificKey[1].setBackground(Color.yellow); scientificKey[1].setVisible(true); www.vidyarthiplus.com www.vidyarthiplus.com 32
fr.add(scientificKey[1]); // Tan scientificKey[2] = new Button("Tan"); scientificKey[2].addActionListener(this); scientificKey[2].setBounds(180, 180, BWIDTH + 10, BHEIGHT); scientificKey[2].setBackground(Color.yellow); scientificKey[2].setVisible(true); fr.add(scientificKey[2]); // PI scientificKey[3] = new Button("Pi"); scientificKey[3].addActionListener(this); scientificKey[3].setBounds(180, 210, BWIDTH + 10, BHEIGHT); scientificKey[3].setBackground(Color.yellow); scientificKey[3].setVisible(true); fr.add(scientificKey[3]); // aSine scientificKey[4] = new Button("aSin"); scientificKey[4].addActionListener(this); scientificKey[4].setBounds(220, 120, BWIDTH + 10, BHEIGHT); scientificKey[4].setBackground(Color.yellow); scientificKey[4].setVisible(true); fr.add(scientificKey[4]); // aCos scientificKey[5] = new Button("aCos"); scientificKey[5].addActionListener(this); scientificKey[5].setBounds(220, 150, BWIDTH + 10, BHEIGHT); scientificKey[5].setBackground(Color.yellow); scientificKey[5].setVisible(true); fr.add(scientificKey[5]); // aTan scientificKey[6] = new Button("aTan"); scientificKey[6].addActionListener(this); scientificKey[6].setBounds(220, 180, BWIDTH + 10, BHEIGHT); scientificKey[6].setBackground(Color.yellow); scientificKey[6].setVisible(true); fr.add(scientificKey[6]); // E scientificKey[7] = new Button("E"); scientificKey[7].addActionListener(this); scientificKey[7].setBounds(220, 210, BWIDTH + 10, BHEIGHT); scientificKey[7].setBackground(Color.yellow); scientificKey[7].setVisible(true); fr.add(scientificKey[7]); // to degrees scientificKey[8] = new Button("todeg"); scientificKey[8].addActionListener(this); scientificKey[8].setBounds(180, 240, BWIDTH + 10, BHEIGHT); scientificKey[8].setBackground(Color.yellow); scientificKey[8].setVisible(true); fr.add(scientificKey[8]); www.vidyarthiplus.com www.vidyarthiplus.com 33
// to radians scientificKey[9] = new Button("torad"); scientificKey[9].addActionListener(this); scientificKey[9].setBounds(220, 240, BWIDTH + 10, BHEIGHT); scientificKey[9].setBackground(Color.yellow); scientificKey[9].setVisible(true); fr.add(scientificKey[9]); fr.add(display); fr.setVisible(true); } // end of makeCalculator
public void actionPerformed(ActionEvent ae) { String buttonText = ae.getActionCommand(); double displayNumber = Double.valueOf(display.getText()).doubleValue(); // if the button pressed text is 0 to 9 if((buttonText.charAt(0) >= '0') & (buttonText.charAt(0) <= '9')) { if(decimalPointPressed) { for (int i=1;i <=decimalPlaces; ++i) currentNumber *= 10; currentNumber +=(int)buttonText.charAt(0)- (int)'0'; for (int i=1;i <=decimalPlaces; ++i) { currentNumber /=10; } ++decimalPlaces; display.setText(Double.toString(currentNumber)); } else if (roundButtonPressed) { int decPlaces = (int)buttonText.charAt(0) - (int)'0'; for (int i=0; i< decPlaces; ++i) displayNumber *=10; displayNumber = Math.round(displayNumber); for (int i = 0; i < decPlaces; ++i) { displayNumber /=10; } display.setText(Double.toString(displayNumber)); roundButtonPressed = false; } else { currentNumber = currentNumber * 10 + (int)buttonText.charAt(0)-(int)'0'; display.setText(Integer.toString((int)currentNumber)); } }
// if button pressed is subtract if (buttonText == "-") { subtractButtonPressed = true; initialNumber = displayNumber; currentNumber = 0; decimalPointPressed = false; }
// if button pressed is divide if (buttonText == "/") { divideButtonPressed = true; initialNumber = displayNumber; currentNumber = 0; decimalPointPressed = false; }
// if button pressed is multiply if (buttonText == "*") { multiplyButtonPressed = true; initialNumber = displayNumber; currentNumber = 0; decimalPointPressed = false; }
// if button pressed is reciprocal if (buttonText == "1/x") { // call reciprocal method display.setText(reciprocal(displayNumber)); currentNumber = 0; decimalPointPressed = false; }
// if button is pressed to change a sign // if (buttonText == "+/-") { // call changesign meyhod to change the // sign display.setText(changeSign(displayNumber)); currentNumber = 0; decimalPointPressed = false; }
// this will convert the numbers displayed to degrees if (buttonText == "todeg") display.setText(Double.toString(Math.toDegrees(displayNumber))); // this will convert the numbers display // ed to radians www.vidyarthiplus.com www.vidyarthiplus.com 36
if (buttonText == "torad") display.setText(Double.toString(Math.toRadians(displayNumber)));
// the main action if (buttonText == "=") { currentNumber = 0; // if add button is pressed if(addButtonPressed) display.setText(Double.toString(initialNumber + displayNumber)); // if subtract button is pressed if(subtractButtonPressed) display.setText(Double.toString(initialNumber - displayNumber)); // if divide button is pressed if (divideButtonPressed) { // check if the divisor is zero if(displayNumber == 0) { MessageBox mb = new MessageBox ( fr, "Error ", true, "Cannot divide by zero."); mb.show(); } else display.setText(Double.toString(initialNumber/displayNumber)); }
// if multiply button is pressed if(multiplyButtonPressed) display.setText(Double.toString(initialNumber * displayNumber)); // if power button is pressed if (powerButtonPressed) display.setText(power(initialNumber, displayNumber)); // set all the buttons to false resetAllButtons(); } } // end of action events
public void itemStateChanged(ItemEvent ie) { } // end of itemState
// this method will reset all the button // Pressed property to false public void resetAllButtons() { addButtonPressed = false; subtractButtonPressed = false; multiplyButtonPressed = false; divideButtonPressed = false; decimalPointPressed = false; powerButtonPressed = false; roundButtonPressed = false; }
www.vidyarthiplus.com www.vidyarthiplus.com 38
public String factorial(double num) { int theNum = (int)num; if (theNum < 1) { MessageBox mb = new MessageBox (fr, "Facorial Error", true, "Cannot find the factorial of numbers less than 1."); mb.show(); return ("0"); } else { for (int i=(theNum -1); i > 1; --i) theNum *= i; return Integer.toString(theNum); }
}
public String reciprocal(double num) { if (num ==0) { MessageBox mb = new MessageBox(fr,"Reciprocal Error", true, "Cannot find the reciprocal of 0"); mb.show(); } else num = 1/num; return Double.toString(num); } public String power (double base, double index) { return Double.toString(Math.pow(base, index)); } public String changeSign(double num) { return Double.toString(-num); } }
class MessageBox extends Dialog implements ActionListener { Button ok; MessageBox(Frame f, String title, boolean mode, String message) { super(f, title, mode); Panel centrePanel = new Panel(); Label lbl = new Label(message); centrePanel.add(lbl); add(centrePanel, "Center"); Panel southPanel = new Panel(); ok = new Button ("OK"); ok.addActionListener(this); southPanel.add(ok); add(southPanel, "South"); pack(); addWindowListener (new WindowAdapter() { public void windowClosing (WindowEvent we) { www.vidyarthiplus.com www.vidyarthiplus.com 39
System.exit(0); } }); }
public void actionPerformed(ActionEvent ae) { dispose(); } }
OUTPUT:
RESULT:
Thus a scientific calculator using even-driven programming paradigm of Java is developed.
www.vidyarthiplus.com www.vidyarthiplus.com 40
EX NO:-8 Multithreading
Aim:- To 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.
private PipedWriter primeWriter = new PipedWriter();
public PipedWriter getPipedWriter() { return primeWriter; }
@Override public void run() { super.run(); generatePrime(); }
public void generatePrime() { for (int i = 2; i < 10000; i++) { if (isPrime(i)) { try { //System.out.println("From Prime : " + i); primeWriter.write(i);
MATCH ::2 MATCH ::3 MATCH ::5 MATCH ::13 MATCH ::89 MATCH ::233 MATCH ::1597
C:\jdk1.5\bin>
Result: Thus the above program was executed and verified successfully.
www.vidyarthiplus.com www.vidyarthiplus.com 46
Ex.No: 9 A Simple OPAC system for library
Aim:- To develop a simple OPAC System for library management system using event-driven and concurrent programming paradigms and java database connectivity.
Algorithm:-
Step 1:Initiate a class and declare the driver for the Driver name required to connect to the database.
Step 2:-Enclose the coding in a try block to handle errors and trap the exception in a catch block.
Step 3:-Establish the connection object to connect to the backend.
Step 4:-Create an object for Statement object using createStatement() object.
Step 5:-Issue a query through executeQuery() method.
public Datas() www.vidyarthiplus.com www.vidyarthiplus.com 47
{
super("Our Application"); Container c = getContentPane(); c.setLayout(new GridLayout(5,1)); id = new JTextField(20); name = new JTextField(20); next = new JButton("Next BOOK"); p = new JPanel(); c.add(new JLabel("ISBN",JLabel.CENTER)); c.add(id); c.add(new JLabel("Book Name",JLabel.CENTER)); c.add(name); c.add(p); p.add(next); next.addActionListener(this); pack(); setVisible(true); addWindowListener(new WIN());
}
public static void main(String args[]) { Datas d = new Datas(); try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); conn = DriverManager.getConnection("jdbc:odbc:custo"); // cust is the DSN Name stat = conn.createStatement(); res = stat.executeQuery("Select * from stu"); // Customers is the table name res.next();
//Inner class WIN implemented class WIN extends WindowAdapter { public void windowClosing(WindowEvent w) { JOptionPane jop = new JOptionPane(); jop.showMessageDialog(null,"Database","Thanks",JOptionPane.QUESTION_MESSAGE);
} else { frame.add(jtp2); frame.add(jtp3); jtp1.setBounds(10, 40, 670, 400); jl1.setBounds(500, 380, 670, 150); jl2.setBounds(550, 380, 670, 150); jl3.setBounds(600, 380, 670, 150); } } } public void mouseEntered(MouseEvent ew) {} public void mouseExited(MouseEvent ew) {} public void mousePressed(MouseEvent ew) {} public void mouseReleased(MouseEvent ew) {} public void mouseMoved(MouseEvent e) { jl1.setText("X-: "+Integer.toString(e.getX())); jl2.setText("Y-: "+Integer.toString(e.getY())); } public void mouseDragged(MouseEvent e) {} public void actionPerformed(ActionEvent ae) {} public void open() { JFileChooser fileChooser = new JFileChooser(); fileChooser.addChoosableFileFilter(new MyFilter()); int select=fileChooser.showOpenDialog(frame); if(select==JFileChooser.APPROVE_OPTION) { File file=fileChooser.getSelectedFile(); String filename=fileChooser.getSelectedFile().getName(); try { FileInputStream fis=new FileInputStream(file); int n=fis.available(); byte dat[]=new byte[n]; fis.read(dat); String data=new String(dat); jtp1.setTitleAt(0, filename); jta1.setText(data); opt.setEnabled(true); } catch(Exception e) { e.printStackTrace(); } }
} public int getCurrentLineNumber() { int line; int caretPosition = jta1.getCaretPosition(); Element root = jta1.getDocument().getDefaultRootElement(); line = root.getElementIndex(caretPosition) + 1; return line; } public void compile() { try { jtp2.setTitleAt(0,"Compile"); String ta1=jta1.getText().trim(); StringBuffer sb=new StringBuffer(ta1); int id1=ta1.indexOf("public class"); int id2=ta1.indexOf(" ",id1+13); www.vidyarthiplus.com www.vidyarthiplus.com 63
class MyFilter extends javax.swing.filechooser.FileFilter { public boolean accept(File file) { return file.isDirectory() || file.getName().endsWith(".java"); } public String getDescription() { return "*.java"; } }
/* Test Frame Design */ import javax.swing.*; import java.awt.*; public class Test { public Test() { JFrame f = new JFrame("Test"); f.setLayout(new FlowLayout()); JTextField jt1 = new JTextField(25); f.add(jt1); f.setVisible(true); f.setSize(200,200); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String args[]) { new Test(); } }