Anda di halaman 1dari 44

St.

Peters College of Engineering & Technology


Department of Computer Science & Engineering

Lab Manual
CS2309 JAVA LAB List of Experiments
1. Write a java program to Develop Rational number class in Java. Your implementation should use efficient representation for a rational number, i.e. (500 / 1000) should be represented as (). 2. Write a java program to Develop Date class in Java similar to the one available in java.util package. 3. Write a java program to 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. . Write a java program to 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. Write a java program to Design a Vehicle class hierarchy in Java. Write a test program to demonstrate polymorphism. 6. Write a java program to 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. Write a java program to 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.

0032

Ex.No: 01

RATIONAL NUMBERS
AIM:
To a java program to Develop Rational number class in Java. Your implementation should use efficient representation for a rational number, i.e. (500 / 1000) should be represented as ().

PROGRAM: public class rational { /** Rational number class * To give an efficient representation of user's input rational number * For ex: 500/1000 to be displayed as 1/2 */ public void efficient_rep(int a, int b) { int x=b; if(a<b) x=a; /** Assume x = smallest among a and b * Divide the numerator and denominator by x, x-1, x-2... until * both of them cannot be divided further */ for(int i=x;i>=2;i--) { if(a%i==0 && b%i==0) { a=a/i; b=b/i; } } System.out.println(a + "/" + b); } } Output: E:\java>javac Rational.java E:\java>javac rational_main.java E:\java>java rational_main Enter the Numerator and Denominator: 500 1000 1/2 RESULT: 2

Thus a Java program with Rational number class was developed and JavaDoc comments for documentation was used.

Ex.No: 02

DATE CLASS JAVA.UTIL PACKAGE


AIM: To design a Date class similar to the one provided in the java.util package. PROGRAM: // ----------------------------------------------------------------------------// DateExample.java // ----------------------------------------------------------------------------import java.util.Date; import java.text.ParseException; import java.text.SimpleDateFormat; /** * ----------------------------------------------------------------------------* Used to provide an example that exercises most of the functionality of the * java.util.Date class. A Date object represents a precise moment in time, * down to the millisecond. Dates are represented as a long that counts the * number of milliseconds since midnight, January 1, 1970, Greenwich Meantime. * * @version 1.0 * * ----------------------------------------------------------------------------*/ public class DateExample { /** * Helper utility used to print * a String to STDOUT. * @param s String that will be printed to STDOUT. */ private static void prt(String s) { System.out.println(s); } private static void prt() { System.out.println(); } private static void doDateExample() throws InterruptedException { // To create a Date object for the current // date and time use the noargs Date() constructor like this: 4

prt("CURRENT DATE/TIME"); prt("======================================================="); Date now = new Date(); prt(" new Date() : " + now); prt(); prt("CURRENT DATE/TIME (FORMATTED OUTPUT)"); prt("======================================================="); SimpleDateFormat formatPattern = new SimpleDateFormat("HH/dd/yyyy HH:mm:ss"); String nowFormatted = formatPattern.format(now); prt(" new Date() Formatted : " + nowFormatted); prt(); // To create a Date object for a specific time, pass the number of // milliseconds since midnight, January 1, 1970, Greenwich Meantime // to the constructor, like this: // // Establish a date object set in milliseconds // relative to 1/1/1970 GMT prt("DATE OBJECT FOR SPECIFIC TIME"); prt("======================================================="); Date specificDate1 = new Date(24L*60L*60L*1000L); Date specificDate2 = new Date(0L); prt(" new Date(24L*60L*60L*1000L) : " + specificDate1); prt(" new Date(0L) : " + specificDate2); prt(); // You can return the number of milliseconds in the Date // as a long, using the getTime() method. For example, // to time a block of code, you might do this prt("USE getTime() TO RETURN MILLISECONDS"); prt("======================================================="); Date startTime = new Date(); prt(" Start Time : " + startTime); // .... // Insert any "timed code" here... // ... System.out.print(" "); for (int i = 0; i < 100; i++) { System.out.print("."); //Pause for 5 seconds Thread.sleep(5000); } prt(); Date endTime = new Date(); prt(" End Time : " + endTime); long elapsed_time = endTime.getTime() - startTime.getTime(); prt(" That took " + elapsed_time + " milliseconds"); prt(); 5

prt("USE RESULTS FROM elapsed_time ABOVE TO FORMAT OUTPUT"); prt("======================================================="); long totalTimeMillis = elapsed_time / 1000; String totalTimeSeconds = Integer.toString((int)(totalTimeMillis % 60)); String totalTimeMinutes = Integer.toString((int)((totalTimeMillis % 3600) / 60)); String totalTimeHours = Integer.toString((int)(totalTimeMillis / 3600)); for (int i = 0; i < 2; i++) { if (totalTimeSeconds.length() < 2) { totalTimeSeconds = "0" + totalTimeSeconds; } if (totalTimeMinutes.length() < 2) { totalTimeMinutes = "0" + totalTimeMinutes; } if (totalTimeHours.length() < 2) { totalTimeHours = "0" + totalTimeHours; } } prt("Formatted output : " + totalTimeHours + " hours " + totalTimeMinutes + " minutes " + totalTimeSeconds + " minutes\n"); // You can change a Date by passing the new date as a number of // milliseconds since midnight, January 1, 1970, GMT, to the setTime() // method, like this: prt("USE gsetTime() TO CHANGE A DATE OBJECT"); prt("======================================================="); Date changeDate = new Date(); prt(" new Date() : " + changeDate); changeDate.setTime(24L*60L*60L*1000L); prt(" setTime(24L*60L*60L*1000L) : " + changeDate); prt(); // The before() method returns true if this Date is before the Date // argument, false if it's not. // For example // if (midnight_jan2_1970.before(new Date())) { // The after() method returns true if this Date is after the Date // argument, false if it's not. // For example // if (midnight_jan2_1970.after(new Date())) { // The Date class also has the usual hashCode(), // equals(), and toString() methods. prt("COMPARE DATES USING: before(), after(), equals()"); prt("======================================================="); Date compareDateNow1 = new Date(); Date compareDateNow2 = (Date) compareDateNow1.clone(); Date compareDate1970 = new Date(24L*60L*60L*1000L); 6

prt(" Compare (Equals):"); prt(" - " + compareDateNow1); prt(" - " + compareDateNow2); if (compareDateNow1.equals(compareDateNow2)) { prt(" - The two dates are equal."); } else { prt(" - The two dates are NOT equal."); } prt(); prt(" Compare (Equals):"); prt(" - " + compareDateNow1); prt(" - " + compareDate1970); if (compareDateNow1.equals(compareDate1970)) { prt(" - The two dates are equal."); } else { prt(" - The two dates are NOT equal."); } prt(); prt(" Compare (Before):"); prt(" - " + compareDateNow1); prt(" - " + compareDate1970); if (compareDateNow1.before(compareDate1970)) { prt(" - " + compareDateNow1 + " comes before " + compareDate1970 + "."); } else { prt(" - " + compareDateNow1 + " DOES NOT come before " + compareDate1970 + "."); } prt(); prt(" Compare (After):"); prt(" - " + compareDateNow1); prt(" - " + compareDate1970); if (compareDateNow1.after(compareDate1970)) { prt(" - " + compareDateNow1 + " comes after " + compareDate1970 + "."); } else { prt(" - " + compareDateNow1 + " DOES NOT come after " + compareDate1970 + "."); } prt(); prt("RETRIEVE MILLISECONDS"); prt("======================================================="); // Establish a date object set in milliseconds relative to 1/1/1970 GMT Date y = new Date(1000L*60*60*24); // Retrieve the number of milliseconds since 1/1/1970 GMT (31536000000) long n = y.getTime(); 7

prt(" Number of milliseconds since 1/1/1970 (GMT) : " + n); // Computes a hashcode for the date object (1471228935) int i = y.hashCode(); prt(" Hash code for object : " + i); // Retrieve the string representation of the date (Thu Dec 31 16:00:00 PST 1970) String s = y.toString(); prt(" String representation of date : " + s); prt(); prt("PARSE STRING TO DATE"); prt("============================================================== ==="); Date newDate; String inputDate = "1994-02-14"; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); System.out.print(" " + inputDate + " parses as "); try { newDate = formatter.parse(inputDate); prt(newDate + "."); } catch (ParseException e) { prt("Unparseable using " + formatter + "."); } prt(); } public static void main(String[] args) { prt(); try { doDateExample(); } catch (Exception e) { e.printStackTrace(); } } }

RESULT: Thus a Date class similar to the one provided in the java.util package is designed.

Ex.No: 03

LISP LIKE LIST


AIM:
Write a java program to 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].

PROGRAM: import java.util.*; import java.io.*; // To implement LISP-like List in Java to perform functions like car, cdr, cons. class Lisp { Vector v = new Vector(4,1); int i; InputStreamReader isr = new InputStreamReader(System.in); BufferedReader inData = new BufferedReader(isr); String str; //Create a LISP-Like List using VECTOR public void create() { int n; System.out.print("\n Enter the Size of the list:"); //Get Input from the user...Use I/p stream reader for it... try { str = inData.readLine(); n = Integer.parseInt(str); for(i=0;i { int temp; System.out.print("\n Enter the element " + (i+1) + " of the list:"); str = inData.readLine(); temp=Integer.parseInt(str); v.addElement(new Integer(temp)); } } catch (IOException e) { System.out.println("Error!"); System.exit(1); } } //Display the content of LISP-List public void display() { 9

int n=v.size(); System.out.print("[ "); for(i=0;i { System.out.print(v.elementAt(i) + " "); } System.out.println("]"); } /* The car of a list is, quite simply, the first item in the list. For Ex: car of L.car() of a list [3 0 2 5] returns 3. Gives the CAR of LISP-List */ public void car() { System.out.println("\n CAR of the List: " + v.elementAt(0)); } /* The cdr of a list is the rest of the list, that is, the cdr function returns the part of the list that follows the first item. For ex: cdr of a list [3 0 2 5] returns [0 2 5] */ public void cdr() { int n=v.size(); System.out.print("\n The CDR of the List is:"); System.out.print("[ "); for(i=1;i { System.out.print(v.elementAt(i) + " "); } System.out.println("]"); } /* The cons function constructs lists. It is useful to add element to the front of the list; it is the inverse of car and cdr. For example, cons can be used to make a five element list from the four element list. For ex: adding 7 to [3 0 2 5], cons(7) gives [7 3 0 2 5] */ public void cons(int x) { v.insertElementAt(x,0); System.out.print("\n The List after using CONS and adding an element:"); display(); } // Returns the length of the LISP-List public int length() { return v.size(); } 10

} class Lisp_List { public static void main(String[] args) { Lisp a = new Lisp(); a.create(); System.out.print("\n The contents of the List are:"); a.display(); a.car(); a.cdr(); a.cons(5); System.out.println("\n\n The length of the list is " + a.length()); } }

Output
Enter the Size of the list:4 Enter the element 1 of the list:3 Enter the element 2 of the list:0 Enter the element 3 of the list:2 Enter the element 4 of the list:5 The contents of the List are:[ 3 0 2 5 ] CAR of the List: 3 The CDR of the List is:[ 0 2 5 ] The List after using CONS and adding an element:[ 5 3 0 2 5 ] The length of the list is 5 RESULT: Thus a program for Lisp like list in java was implemented and the outputs are checked.

11

Ex.No: 04

ADT STACK - INTERFACE


AIM: To design a Java interface for ADT Stack and to develop two different classes that implement this interface, one using array and the other using linked-list. PROGRAM: import java.lang.*; import java.io.*; import java.util.*; interface MystackArray { int n=10; public void pop(); public void push(); public void peek(); public void display(); } interface MyStackLinkList { class Link { public Object data; public Link next; public Link(Object d, Link n) { data = d; next = n; } } } //Stack using Array class StackArray implements MystackArray { int stack[]=new int[n]; int top=-1; public void push() { try{ DataInputStream dis=new DataInputStream(System.in); if(top==(n-1)) { System.out.println("overflow"); return; } 12

else { System.out.println("enter element"); int ele=Integer.parseInt(dis.readLine()); stack[++top]=ele; } } catch(Exception e) { System.out.println("e"); } } public void pop() { if(top<0) { System.out.println("underflow"); return; } else { int popper=stack[top]; top--; System.out.println("popped element" +popper); } } public void peek() { if(top<0) { System.out.println("underflow"); return; } else { int popper=stack[top]; System.out.println("popped element" +popper); } } public void display() { if(top<0) { System.out.println("empty"); return; } else { String str=" "; for(int i=0;i<=top;i++) 13

str=str+" "+stack[i]; System.out.println("elements are"+str); } } } //Stack using Linked List class LinkList implements MyStackLinkList { private Link head; // reference to first Link private Link tail; // reference to last Link private int size; public LinkList() { tail = null; head = null; } public Object peekHead() // return reference to first Object { return head.data; } public Object peekTail() // return reference to last Object { return tail.data; } //THE ADD METHOD, NOT SURE IF DONE RIGHT public void addHead(Object newData) { if (head == null) { head = new Link(newData, tail); } else if (head != null && tail == null) { tail = head; head = new Link (newData, tail); } else { head.next = head; head = new Link (newData, head.next); } } //THE REMOVE METHOD public Object removeHead() { Link removing = head; 14

if (head != null) { head = head.next; } return removing.data; } } class Stackadt { public static void main(String arg[])throws IOException { DataInputStream dis=new DataInputStream(System.in); int c,ch; do { System.out.println("\nMENU\n1.Stack using Array\n2.Stack using Linked List\n3.Exit"); c=Integer.parseInt(dis.readLine()); switch(c) { case 1: { StackArray stk=new StackArray(); do{ System.out.println("enter ur choice for\n1.push\n2.pop\n3.peek\n4.display\n5.exit"); System.out.print("Enter U'r Choice: "); ch=Integer.parseInt(dis.readLine()); switch(ch){ case 1: stk.push(); break; case 2:stk.pop(); break; case 3:stk.peek(); break; case 4:stk.display(); break; case 5:break; default: System.out.print("Wrong Choice!!! "); } }while(ch!=5); break; } case 2: { Scanner scan = new Scanner(System.in); int choice = 0; LinkList first = new LinkList(); 15

while (choice != 4) { System.out.println("What would you like to do? (enter the number)"); System.out.println("1 - Push onto Head of Stack."); System.out.println("2 - Remove from Head of Stack."); System.out.println("3 - Peek at Head of Stack."); System.out.println("4 - Close Program."); System.out.print("Enter U'r Choice: "); choice = scan.nextInt(); switch(choice) { case 1: System.out.println("What do you want to push on Head?"); Object pushingHead = scan.next(); first.addHead(pushingHead); break; case 2: System.out.println("Removing: " + first.removeHead()); break; case 3: System.out.println("Peeking at Head of Stack: " + first.peekHead()); break; case 4: break; default: System.out.print("Wrong Choice!!! "); } } break; } case 3: System.exit(0); default: System.out.println("Wrong Choice!!!"); } }while(c!=3); } }

RESULT: Thus a Java interface for ADT Stack and to develop two different classes that implement this interface, one using array and the other using linked-list was developed.

16

Ex.No: 05

VEHICLE CLASS HIERARCHY-POLYMORPHISM


AIM:
Write a java program to Design a Vehicle class hierarchy in Java. Write a test program to demonstrate polymorphism.

PROGRAM: import java.util.*; abstract class Vehicle {boolean engstatus=false; abstract void start(); abstract void moveForward(); abstract void moveBackward(); abstract void applyBrake(); abstract void turnLeft(); abstract void turnRight(); abstract void stop(); } class Porsche extends Vehicle { void truckManufacture() { System.out.println("Porsche World Wide Car manufactures "); } void gearSystem() { System.out.println("\n automatic gearing system.. So don't worry !!"); } void start() { engstatus=true; System.out.println("\n engine is ON "); } void moveForward() { if(engstatus==true) System.out.println("\nCar is moving in forward direction .. Slowly gathering speed "); else System.out.println("\n Car is off...Start engine to move"); } void moveBackward() { if(engstatus=true) System.out.println("\n Car is moving in reverse direction ..."); else System.out.println("\n Car is off...Start engine to move"); } void applyBrake() 17

{ System.out.println("\n Speed is decreasing gradually"); } void turnLeft() { System.out.println("\n Taking a left turn.. Look in the mirror and turn "); } void turnRight() { System.out.println("\n Taking a right turn.. Look in the mirror and turn "); } void stop() { engstatus=false; System.out.println("\n Car is off "); } } class Volvo extends Vehicle { void truckManufacture() { System.out.println("Volvo Truck Manufactures"); } void gearSystem() { System.out.println("\nManual Gear system...ooops....take care while driving ") ; } void start() { engstatus=true; System.out.println("\n engine is ON "); } void moveForward() { if(engstatus==true) System.out.println("\n truck is moving in forward direction .. Slowly gathering speed "); else System.out.println("\n truck is off...Start engine to move"); } void moveBackward() { if(engstatus=true) System.out.println("\n truck is moving in reverse direction ..."); else System.out.println("\n truck is off...Start engine to move"); } void applyBrake() { System.out.println("\n Speed is decreasing gradually"); } 18

void turnLeft() { System.out.println("\n Taking a left turn.. Look in the mirror and turn "); } void turnRight() { System.out.println("\n Taking a right turn.. Look in the mirror and turn "); } void stop() { engstatus=false; System.out.println("\n Truck is off "); } } class Vehicle1 { public static void main(String[] args) { Porsche v1=new Porsche(); v1.truckManufacture(); v1.start(); v1.gearSystem(); v1.moveForward(); v1.applyBrake(); v1.turnLeft(); v1.moveForward(); v1.applyBrake(); v1.turnRight(); v1.moveBackward(); v1.stop(); v1.moveForward(); Volvo v2= new Volvo(); v2.truckManufacture(); v2.start(); v2.gearSystem(); v2.moveForward(); v2.applyBrake(); v2.turnLeft(); v2.moveForward(); v2.applyBrake(); v2.turnRight(); v2.moveBackward(); v2.stop(); v2.moveForward(); } } RESULT: 19

Thus Vehicle class hierarchy using polymorphism is implemented and output is verified. Ex.No: 06

CURRENCY CLASS OBJECT SERIALIZATION


AIM:
Write a java program to 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.

PROGRAM: SerializationRead.java import java.io.*; import java.util.*; public class SerializationRead { public static void main(String args[]) { try { Currency obj; FileInputStream fis = new FileInputStream("serial.txt"); ObjectInputStream ois = new ObjectInputStream(fis); System.out.println("Reading from file using Object Serialization:"); for(int i=1;i<=25;i++) { obj = (Currency)ois.readObject(); if((obj.currency).equals("$")) System.out.println(obj + " = " + obj.dollarToRupee(obj.amount)); else System.out.println(obj + " = " + obj); } ois.close(); } catch(Exception e) { System.out.println("Exception during deserialization." + e); } } }

20

SerializationWrite.java import java.io.*; import java.util.*; class Currency implements Serializable { protected String currency; protected int amount; public Currency(String cur, int amt) { this.currency = cur; this.amount = amt; } public String toString() { return currency + amount; } public String dollarToRupee(int amt) { return "Rs" + amt * 45; } } class Rupee extends Currency { public Rupee(int amt) { super("Rs",amt); } } class Dollar extends Currency { public Dollar(int amt) { super("$",amt); } } public class SerializationWrite { public static void main(String args[]) { Random r = new Random(); try { Currency currency; FileOutputStream fos = new FileOutputStream("serial.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); 21

System.out.println("Writing to file using Object Serialization:"); for(int i=1;i<=25;i++) { Object[] obj = { new Rupee(r.nextInt(5000)),new Dollar(r.nextInt(5000)) }; currency = (Currency)obj[r.nextInt(2)]; // RANDOM Objects for Rs and $ System.out.println(currency); oos.writeObject(currency); oos.flush(); } oos.close(); } catch(Exception e) { System.out.println("Exception during Serialization: " + e); } } }

Output: vivek@ubuntu:~/Desktop$ javac SerializationWrite.java vivek@ubuntu:~/Desktop$ java SerializationWrite Writing to file using Object Serialization: $4645 Rs105 $2497 $892 Rs1053 Rs1270 $1991 Rs4923 Rs4443 Rs3537 Rs2914 $53 $561 $4692 Rs860 $2764 Rs752 $1629 $2880 Rs2358 Rs3561 $3796 Rs341 Rs2010 22

Rs427 vivek@ubuntu:~/Desktop$ javac SerializationRead.java vivek@ubuntu:~/Desktop$ java SerializationRead Reading from file using Object Serialization: $4645 = Rs209025 Rs105 = Rs105 $2497 = Rs112365 $892 = Rs40140 Rs1053 = Rs1053 Rs1270 = Rs1270 $1991 = Rs89595 Rs4923 = Rs4923 Rs4443 = Rs4443 Rs3537 = Rs3537 Rs2914 = Rs2914 $53 = Rs2385 $561 = Rs25245 $4692 = Rs211140 Rs860 = Rs860 $2764 = Rs124380 Rs752 = Rs752 $1629 = Rs73305 $2880 = Rs129600 Rs2358 = Rs2358 Rs3561 = Rs3561 $3796 = Rs170820 Rs341 = Rs341 Rs2010 = Rs2010 Rs427 = Rs427 RESULT: Thus a simple paint-like program that can draw basic graphical primitives in different colors is designed and use appropriate buttons were used in JAVA language.

23

Ex.No: 07

SCIENTIFIC CALCULATOR - EVENT-DRIVEN PROGRAMMING


AIM: To develop a scientific calculator using even-driven programming paradigm of Java. 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 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; 24

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); 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); 25

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]); //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 26

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); 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); 27

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]); // 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]); 28

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 addition if(buttonText == "+") { addButtonPressed = true; initialNumber = displayNumber; currentNumber = 0; decimalPointPressed = false; } // if button pressed is subtract if (buttonText == "-") { subtractButtonPressed = true; initialNumber = displayNumber; currentNumber = 0; decimalPointPressed = false; 29

} // 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; } // factorial button if (buttonText == "x!") { display.setText(factorial(displayNumber)); currentNumber = 0; decimalPointPressed = false; } // power button if (buttonText == "x^n") { powerButtonPressed = true; initialNumber = displayNumber; currentNumber = 0; decimalPointPressed = false; } 30

// now for scientific buttons if (buttonText == "Sin") { display.setText(Double.toString(Math.sin(displayNumber))); currentNumber = 0; decimalPointPressed = false; } if (buttonText == "Cos") { display.setText(Double.toString(Math.cos(displayNumber))); currentNumber = 0; decimalPointPressed = false; } if (buttonText == "Tan") { display.setText(Double.toString(Math.tan(displayNumber))); currentNumber = 0; decimalPointPressed = false; } if (buttonText == "aSin") { display.setText(Double.toString(Math.asin(displayNumber))); currentNumber = 0; decimalPointPressed = false; } if (buttonText == "aCos") { display.setText(Double.toString(Math.acos(displayNumber))); currentNumber = 0; decimalPointPressed = false; } if (buttonText == "aTan") { display.setText(Double.toString(Math.atan(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 if (buttonText == "torad") display.setText(Double.toString(Math.toRadians(displayNumber))); if (buttonText == "Pi") { display.setText(Double.toString(Math.PI)); currentNumber =0; decimalPointPressed = false; 31

} if (buttonText == "Round") roundButtonPressed = true; // check if decimal point is pressed if (buttonText == ".") { String displayedNumber = display.getText(); boolean decimalPointFound = false; int i; decimalPointPressed = true; // check for decimal point for (i =0; i < displayedNumber.length(); ++i) { if(displayedNumber.charAt(i) == '.') { decimalPointFound = true; continue; } } if (!decimalPointFound) decimalPlaces = 1; } if(buttonText == "CA"){ // set all buttons to false resetAllButtons(); display.setText("0"); currentNumber = 0; } if (buttonText == "CE") { display.setText("0"); currentNumber = 0; decimalPointPressed = false; } if (buttonText == "E") { display.setText(Double.toString(Math.E)); currentNumber = 0; decimalPointPressed = false; } // the main action if (buttonText == "=") { currentNumber = 0; // if add button is pressed if(addButtonPressed) 32

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; } 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"); } 33

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) { System.exit(0); } }); } public void actionPerformed(ActionEvent ae) { dispose(); } 34

RESULT: Thus a scientific calculator using even-driven programming paradigm of Java is developed.

35

Ex.No: 08

PRIME AND FIBONACCI NUMBERS 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.) and to design a thread that generates prime numbers below 100,000 and writes them into a pipe. Also to 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. PROGRAM: // Multithreading (odd or even) import java.io.*; import java.lang.*; import java.awt.*; import java.awt.event.*; class test extends Frame implements ActionListener,Runnable { int lower,upper; Label l1=new Label("PRIME"); Label l2=new Label("FIBONACCI"); Label l3=new Label("BOTH PRIME AND FIBONACCI NUMBER"); List lb1=new List(); List lb2=new List(); List lb3=new List(); int a[]=new int[50]; int b[]=new int[50]; Button b2=new Button("EXIT"); test(int low,int up) { lower = low; upper = up; setLayout(new FlowLayout()); setSize(250,400); setTitle("Thread Demo"); setVisible(true); add(l1);add(lb1);add(l2);add(lb2);add(l3);add(lb3);add(b2); b2.addActionListener(this); Thread t=new Thread(this); t.start(); addWindowListener( new WindowAdapter() 36

{ public void windowClosing(WindowEvent e) { System.exit(0); } } ); } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==b2) System.exit(0); } public void run() { try { int f1, f2=0, f3=1; for(int i=1;i<=upper;i++) { lb2.add(String.valueOf(f3)); a[i]=f3; f1 = f2; f2 = f3; f3 = f1 + f2; Thread.sleep(100); } }catch(Exception e){} try { int k=1; for(int i=lower;i<upper;i++) { int flag=0; for(int j=2;j<i;j++) { if(i%j==0) { flag = 1; break; } } if(flag==0) { b[k++]=i; lb1.add(String.valueOf(i)); } Thread.sleep(100); } } catch(Exception e){} 37

try { for(int i=1;i<upper;i++) { for(int j=1;j<upper;j++) if(b[i]==a[j]) lb3.add(String.valueOf(b[i])); Thread.sleep(500); } } catch(Exception e){} } public static void main(String args[]) { int lower,upper; lower = Integer.parseInt(args[0]); upper = Integer.parseInt(args[1]); test ob = new test(lower,upper); } } RESULT: Thus 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.) is written and a thread that generates prime numbers below 100,000 and writes them into a pipe is designed. Also an another thread that generates Fibonacci numbers and writes them to another pipe is designed. The main thread reads both the pipes to identify numbers common to both.

38

Ex.No: 09 OPAC USING JDBC AIM:


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.

PROGRAM: import java.sql.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Datas extends JFrame implements ActionListener { JTextField id; JTextField name; JButton next; JButton addnew; JPanel p; static ResultSet res; static Connection conn; static Statement stat; public Datas() { super("Our Application"); 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 DSNName stat = conn.createStatement(); 39

res = stat.executeQuery("Select * from stu"); // Customers is the table name res.next(); } catch(Exception e) { System.out.println("Error" +e); } d.showRecord(res); } public void actionPerformed(ActionEvent e) { if(e.getSource() == next) { try { res.next(); } catch(Exception ee) {} showRecord(res); }} public void showRecord(ResultSet res) { try { id.setText(res.getString(2)); name.setText(res.getString(3)); } catch(Exception e) {} }//end of the main //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); } } } //end of the class

import java.sql.*; import java.sql.DriverManager.*; class Ja { String bookid,bookname; int booksno; Connection con; Statement stmt; ResultSet rs; Ja() { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection("jdbc:odbc:custo"); } catch(Exception e) 40

{ System.out.println("connection error"); } } void myput() { try { stmt=con.createStatement(); rs=stmt.executeQuery("SELECT * FROM stu"); while(rs.next()) { booksno=rs.getInt(1); bookid=rs.getString(2); bookname=rs.getString(3); System.out.println("\n"+ booksno+"\t"+bookid+"\t"+bookname); } rs.close(); stmt.close(); con.close(); } catch(SQLException e) { System.out.println("sql error"); } } } class prog1 { public static void main(String arg[]) { Ja j=new Ja(); j.myput(); }} RESULT: Thus a thread-safe implementation of Queue class and write a multi-threaded producerconsumer application that uses this Queue class was designed in JAVA.

41

Ex.No: 10

GUI APPLICATION - MULTI THREADING


AIM: To develop a multi-threaded GUI application for finding even and odd numbers. PROGRAM: // Multithreading GUI(odd or even) import java.io.*; import java.lang.*; import java.awt.*; import java.awt.event.*; class test extends Frame implements ActionListener,Runnable { int lower,upper; Label l1=new Label("ODD"); Label l2=new Label("EVEN"); List lb1=new List(); List lb2=new List(); Button b2=new Button("EXIT"); test(int low,int up) { lower = low; upper = up; setLayout(new FlowLayout()); setSize(500,500); setTitle("Thread Demo"); setVisible(true); add(l1);add(lb1);add(l2);add(lb2);add(b2); b2.addActionListener(this); Thread t=new Thread(this); t.start(); addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } ); } public void actionPerformed(ActionEvent ae) { 42

if(ae.getSource()==b2) System.exit(0); } public void run() { try { if((lower % 2) != 0) { lower = lower + 1; } while(lower <= upper) { Thread.sleep(1000); lb2.add(String.valueOf(lower)); lower += 2; Thread.sleep(500); } }catch(Exception e){} } public static void main(String args[]) { int lower,upper; lower = Integer.parseInt(args[0]); upper = Integer.parseInt(args[1]); test ob = new test(lower,upper); if((lower % 2) == 0) { lower = lower + 1; } try { while(lower <= upper) { Thread.sleep(1000); ob.lb1.add(String.valueOf(lower)); lower = lower + 2; Thread.sleep(500); } } catch(Exception e){} } } RESULT 43

Thus a multi-threaded GUI application for finding even and odd numbers was designed.

44

Anda mungkin juga menyukai