0% found this document useful (0 votes)
262 views

Java Lab Manual

The document describes implementing various date and time related operations in Java including: 1) Creating Date objects for the current date/time or for a specific time in milliseconds. Methods like getTime() return the milliseconds. 2) Comparing dates using before(), after(), equals() to check if one date is before/after another or if they are equal. 3) Formatting date/time output and changing a Date object's value using setTime().

Uploaded by

sajeer
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
262 views

Java Lab Manual

The document describes implementing various date and time related operations in Java including: 1) Creating Date objects for the current date/time or for a specific time in milliseconds. Methods like getTime() return the milliseconds. 2) Comparing dates using before(), after(), equals() to check if one date is before/after another or if they are equal. 3) Formatting date/time output and changing a Date object's value using setTime().

Uploaded by

sajeer
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Exp. No.

: 1 IMPLEMENTING STACK AND QUEUE CLASSES AIM: To develop a simple program to implement the concept of stack and queues in Java. ALGORITHM: Step 1: Import the required java packages Step 2: Create a public class. Step 3: Key methods of the Stack class are push(), peek(), pop(), empty() and search(). Step 4: Stack adds and removes elements on a First-In First-Out basis. Write the code using the above functions. Step 5: We use the peek() method to find out what element is at the top of the stack. Step 6: We use the method search()to find out the position of the first element. Step 7: Compile and run the program. PROGRAM:
import java.util.Iterator; import java.util.Stack; public class StackExample { public static void main(String[] args) { Stack<String> sk=new Stack<String>(); sk.push("a"); sk.push("c"); sk.push("e"); sk.push("d"); Iterator it=sk.iterator(); System.out.println("Size before pop() :"+sk.size()); while(it.hasNext()) { String iValue=(String)it.next(); System.out.println("Iterator value :"+iValue); } // get and remove last element from stack String value =(String)sk.pop(); System.out.println("value :"+value); System.out.println("Size After pop() :"+sk.size()); }

EXPECTED OUTPUT: Size before pop() :4 Iterator value :a Iterator value :c Iterator value :e Iterator value :d value :d Size After pop() :3

RESULT: Thus a simple program to implement the concept of stack and queues in Java is implemented and executed. Exp. No.: 2
2

COMPLEX NUMBERS AIM: To develop a java class to implement complex numbers. ALGORITHM: Step 1: Create a public class. Step 2: Create Data type for complex numbers. Step 3: Create a new object with the given real and imaginary parts Step 4: return a string representation of the invoking Complex object Step 5: return the real or imaginary part Step 6: Implement a sample client for testing Step 7: Compile and run the program. PROGRAM:
import java.awt.*; import java.awt.event.*; public class Complex { private final double re; // the real part private final double im; // the imaginary part // create a new object with the given real and imaginary parts public Complex(double real, double imag) { re = real; im = imag; } // return a string representation of the invoking Complex object public String toString() { if (im == 0) return re + ""; if (re == 0) return im + "i"; if (im < 0) return re + " - " + (-im) + "i"; return re + " + " + im + "i"; } // return abs/modulus/magnitude and angle/phase/argument public double abs() { return Math.hypot(re, im); } // Math.sqrt(re*re + im*im) public double phase() { return Math.atan2(im, re); } // between -pi and pi // return a new Complex object whose value is (this + b) public Complex plus(Complex b) { Complex a = this; // invoking object double real = a.re + b.re; double imag = a.im + b.im; return new Complex(real, imag); } // return a new Complex object whose value is (this - b) public Complex minus(Complex b) { Complex a = this; double real = a.re - b.re; double imag = a.im - b.im;

return new Complex(real, imag); } // return a new Complex object whose value is (this * b) public Complex times(Complex b) { Complex a = this; double real = a.re * b.re - a.im * b.im; double imag = a.re * b.im + a.im * b.re; return new Complex(real, imag); } // scalar multiplication // return a new object whose value is (this * alpha) public Complex times(double alpha) { return new Complex(alpha * re, alpha * im); } // return a new Complex object whose value is the conjugate of this public Complex conjugate() { return new Complex(re, -im); } // return a new Complex object whose value is the reciprocal of this public Complex reciprocal() { double scale = re*re + im*im; return new Complex(re / scale, -im / scale); } // return the real or imaginary part public double re() { return re; } public double im() { return im; } // return a / b public Complex divides(Complex b) { Complex a = this; return a.times(b.reciprocal()); } // return a new Complex object whose value is the complex exponential of this public Complex exp() { return new Complex(Math.exp(re) * Math.cos(im), Math.exp(re) * Math.sin(im)); } // return a new Complex object whose value is the complex sine of this public Complex sin() { return new Complex(Math.sin(re) * Math.cosh(im), Math.cos(re) * Math.sinh(im)); } // return a new Complex object whose value is the complex cosine of this public Complex cos() { return new Complex(Math.cos(re) * Math.cosh(im), -Math.sin(re) * Math.sinh(im)); } // return a new Complex object whose value is the complex tangent of this public Complex tan() { return sin().divides(cos()); } // a static version of plus public static Complex plus(Complex a, Complex b) { double real = a.re + b.re; double imag = a.im + b.im; Complex sum = new Complex(real, imag); return sum; }

// sample client for testing public static void main(String[] args) { Complex a = new Complex(5.0, 6.0); Complex b = new Complex(-3.0, 4.0); System.out.println("a = " System.out.println("b = " System.out.println("Re(a) = " System.out.println("Im(a) = " System.out.println("b + a = " System.out.println("a - b = " System.out.println("a * b = " System.out.println("b * a = " System.out.println("a / b = " System.out.println("(a / b) * b = " System.out.println("conj(a) = " System.out.println("|a| = " System.out.println("tan(a) = " } }

+ + + + + + + + + + + + +

a); b); a.re()); a.im()); b.plus(a)); a.minus(b)); a.times(b)); b.times(a)); a.divides(b)); a.divides(b).times(b)); a.conjugate()); a.abs()); a.tan());

EXPECTED OUTPUT: a = 5.0 + 6.0i b = -3.0 + 4.0i Re(a) = 5.0 Im(a) = 6.0 b+a = 2.0 + 10.0i a-b = 8.0 + 2.0i a*b = -39.0 + 2.0i b*a = -39.0 + 2.0i a/b = 0.36 - 1.52i (a / b) * b = 5.0 + 6.0i conj(a) = 5.0 - 6.0i |a| = 7.810249675906654 tan(a) = -6.685231390246571E-6 + 1.0000103108981198i

RESULT: Thus the program to implement complex numbers is created and executed in Java. Exp. No.: 3 DESIGNING A DATE CLASS AIM:
5

To develop a java Date class similar to the one provided in the java.util package. ALGORITHM: Step 1: Create a public class. Step 2: Declare a constructor for the date class Step 3: return the number of milliseconds in the Date as a long, using the getTime() method Step 4: Use the before() method to return true if this Date is before the Date argument, false if it's not. Step 5: Establish a date object set in milliseconds Step 6: Retrieve the number of milliseconds Step 7: Retrieve the string representation of the date Step 8: Compile and run the program. PROGRAM:
import java.util.Date; import java.text.ParseException; import java.text.SimpleDateFormat; public class DateExample { 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: 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(); 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(); 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"); 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();

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

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(); } }

EXPECTED OUTPUT:
Thu Jan 01 00:00:00 EST 1971

RESULT: Thus a java Date class similar to the one provided in the java.util package is created. Exp. No.: 4 IMPLEMENTING DYNAMIC POLYMORPHISM AIM: To develop a java program that implements dynamic polymorphism.
9

ALGORITHM: Step 1: Declare the main class. Step 2: Create hourly class which extends the main class. Step 3: Declare the method to set hours and rates Step 4: Declare the method to get the hours and rates Step 5: Calculate the total pay by computing the hours and rates. Step 6: Compile and run the program. PROGRAM:
import java.awt.*; import java.awt.event.*; public class Hourly extends Employee { public Hourly(String name, double rate, double hours) super(name); setRate(rate); setHours(hours); } public void setRate(double rate) { this.rate = rate; } public void setHours(double hours) { this.hours = hours; } public double getRate() { return rate; } public double getHours() { return hours; } public double pay() { return rate * hours; } public String toString() { return super.toString() + " (rate is " + rate + " and hours are " + hours + ')'; } private double rate; private double hours; }

10

RESULT: Thus a simple java program that implements dynamic polymorphism is developed and executed. Exp. No.: 5 ARRAYS AND LINKED LIST AIM: To develop a java program that implements arrays and linked list. ALGORITHM:
11

Step 1: Declare the main class. Step 2: Create an object for the linked list class. Step 3: Write code for performing various operations like adding and removing object. Step 4: This class extends AbstractSequentialList and implements List, Cloneable, Serializable. Step 5: LinkedList class provides methods get, insert and remove an element at the beginning and end of the list. Step 6: Compile and run the program. PROGRAM:
import java.util.*; public class LinkedListDemo{ public static void main(String[] args){ LinkedList link=new LinkedList(); link.add("a"); link.add("b"); link.add(new Integer(10)); System.out.println("The contents of array is" + link); System.out.println("The size of an linkedlist is" + link.size()); link.addFirst(new Integer(20)); System.out.println("The contents of array is" + link); System.out.println("The size of an linkedlist is" + link.size()); link.addLast("c"); System.out.println("The contents of array is" + link); System.out.println("The size of an linkedlist is" + link.size()); link.add(2,"j"); System.out.println("The contents of array is" + link); System.out.println("The size of an linkedlist is" + link.size()); link.add(1,"t"); System.out.println("The contents of array is" + link); System.out.println("The size of an linkedlist is" + link.size()); link.remove(3); System.out.println("The contents of array is" + link); System.out.println("The size of an linkedlist is" + link.size()); } }

EXPECTED OUTPUT:
The The The The contents of array is[a, b, 10] size of an linkedlist is3 contents of array is[20, a, b, 10] size of an linkedlist is4 12

The The The The The The The The

contents of array is[20, size of an linkedlist is5 contents of array is[20, size of an linkedlist is6 contents of array is[20, size of an linkedlist is7 contents of array is[20, size of an linkedlist is6

a, b, 10, c] a, j, b, 10, c] t, a, j, b, 10, c] t, a, b, 10, c]

RESULT: Thus a simple java program that implements arrays and linked list is created and executed. Exp. No.: 6 SORTING AIM: To develop a simple program to sort a given string in Java. ALGORITHM: Step 1: Develop an empty Class Structure. Step 2: Add appropriate menus for selecting functions.
13

Step 3: Compare the arrays of string. Step 4: Get the smallest element at the last index Step 4: Repeat the same steps for array[1] to array[n-1] Step 5: Compile and execute the code. PROGRAM:
public class BubbleSortDescendingOrder { public static void main(String[] args) { //create an int array we want to sort using bubble sort algorithm int intArray[] = new int[]{5,90,35,45,150,3}; //print array before sorting using bubble sort algorithm System.out.println("Array Before Bubble Sort"); for(int i=0; i < intArray.length; i++){ System.out.print(intArray[i] + " "); } //sort an array in descending order using bubble sort algorithm bubbleSort(intArray); System.out.println(""); //print array after sorting using bubble sort algorithm System.out.println("Array After Bubble Sort"); for(int i=0; i < intArray.length; i++){ System.out.print(intArray[i] + " "); } } private static void bubbleSort(int[] intArray) { /* * In bubble sort, we basically traverse the array from first * to array_length - 1 position and compare the element with the next one. * Element is swapped with the next element if the next element is smaller. * * Bubble sort steps are as follows. * * 1. Compare array[0] & array[1] * 2. If array[0] < array [1] swap it. * 3. Compare array[1] & array[2] * 4. If array[1] < array[2] swap it. * ... * 5. Compare array[n-1] & array[n] * 6. if [n-1] < array[n] then swap it. * * After this step we will have smallest element at the last index. * * Repeat the same steps for array[1] to array[n-1] * */ int n = intArray.length; int temp = 0; for(int i=0; i < n; i++){ for(int j=1; j < (n-i); j++){ if(intArray[j-1] < intArray[j]){ //swap the elements! temp = intArray[j-1]; intArray[j-1] = intArray[j]; intArray[j] = temp;

14

} } } } } /*

EXPECTED OUTPUT:
Array Before Bubble Sort 5 90 35 45 150 3 Array After Bubble Sort 150 90 45 35 5 3

RESULT: Thus a simple program to sort a given string in descending order is implemented in Java. Exp. No.: 7 A SIMPLE PAINT APPLICATION AIM: To develop a simple paint application using menus and buttons in Java. ALGORITHM: Step 1: Develop an empty Class Structure. Step 2: Create constants for menu shortcuts. Step 3: Add appropriate menus for selecting functions and set the frame size.
15

Step 4: Add event handlers. Step 5: Implement the method for drawing different shapes. Step 6: Add a panel for drawing Shapes and implement proper event handlers. Step 7: Compile and execute the code. PROGRAM:
package graph; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SimpleDrawingTool extends Frame{ //constants for menu private static final private static final private static final private static final private static final private static final private static final private private private private shortcuts int kControlA int kControlD int kControlC int kControlR int kControlP int kControlT int kControlX = = = = = = = 65; 68; 67; 82; 80; 84; 88;

RectangleShape rectangle = new RectangleShape(); OvalShape oval = new OvalShape(); PolygonShape polygon = new PolygonShape(); TriangleShape triangle = new TriangleShape();

private DrawingPanel panel; public SimpleDrawingTool() { //set frame's title super("Simple Drawing Tool"); //add menu addMenu(); //add drawing panel addPanel(); //add window listener this.addWindowListener(new WindowHandler()); //set frame size this.setSize(400, 400); //make this frame visible this.setVisible(true); } public static void main(String[] args) { SimpleDrawingTool simpleDrawingTool = new SimpleDrawingTool(); } /** This method creates menu bar and menu items and then attach the menu bar with the frame of this drawing tool. */ private void addMenu() {

16

//Add menu bar to our frame MenuBar menuBar = new MenuBar(); Menu file = new Menu("File"); Menu shape = new Menu("Shapes"); Menu about = new Menu("About"); //now add menu items to these Menu objects file.add(new MenuItem("Exit", new MenuShortcut(kControlX))).addActionListener(new WindowHandler()); shape.add(new MenuItem("Rectangle", new MenuShortcut(kControlR))).addActionListener(new shape.add(new MenuItem("Circle", new MenuShortcut(kControlC))).addActionListener(new shape.add(new MenuItem("Triangle", new MenuShortcut(kControlT))).addActionListener(new shape.add(new MenuItem("Polygon", new MenuShortcut(kControlP))).addActionListener(new shape.add(new MenuItem("Draw Polygon", new MenuShortcut(kControlD))).addActionListener(new WindowHandler()); WindowHandler()); WindowHandler()); WindowHandler()); WindowHandler());

about.add(new MenuItem("About", new MenuShortcut(kControlA))).addActionListener(new WindowHandler()); //add menus to menubar menuBar.add(file); menuBar.add(shape); menuBar.add(about); //menuBar.setVisible(true); if(null == this.getMenuBar()) { this.setMenuBar(menuBar); } }//addMenu() /** This method adds a panel to SimpleDrawingTool for drawing shapes. */ private void addPanel() { panel = new DrawingPanel(); //get size of SimpleDrawingTool frame Dimension d = this.getSize(); //get insets of frame Insets ins = this.insets(); //exclude insets from the size of the panel d.height = d.height - ins.top - ins.bottom; d.width = d.width - ins.left - ins.right; panel.setSize(d); panel.setLocation(ins.left, ins.top); panel.setBackground(Color.white); //add mouse listener. Panel itself will be handling mouse events panel.addMouseListener(panel); this.add(panel); }//end of addPanel(); //Inner class to handle events private class WindowHandler extends WindowAdapter implements ActionListener

17

public void windowClosing(WindowEvent e) { System.exit(0); }

public void actionPerformed(ActionEvent e) { //check to see if the action command is equal to exit if(e.getActionCommand().equalsIgnoreCase("exit")) { System.exit(0); } else if(e.getActionCommand().equalsIgnoreCase("Rectangle")) { Menu menu = getMenuBar().getMenu(1); for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(true),i++); getMenuBar().getShortcutMenuItem(new MenuShortcut(kControlR)).setEnabled(false); panel.drawShape(rectangle); } else if(e.getActionCommand().equalsIgnoreCase("Circle")) { Menu menu = getMenuBar().getMenu(1); for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(true),i++); getMenuBar().getShortcutMenuItem(new MenuShortcut(kControlC)).setEnabled(false); panel.drawShape(oval); } else if(e.getActionCommand().equalsIgnoreCase("Triangle")) { Menu menu = getMenuBar().getMenu(1); for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(true),i++); getMenuBar().getShortcutMenuItem(new MenuShortcut(kControlT)).setEnabled(false); panel.drawShape(triangle); } else if(e.getActionCommand().equalsIgnoreCase("Polygon")) { Menu menu = getMenuBar().getMenu(1); for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(true),i++); getMenuBar().getShortcutMenuItem(new MenuShortcut(kControlP)).setEnabled(false); panel.drawShape(polygon); } else if(e.getActionCommand().equalsIgnoreCase("Draw Polygon")) { Menu menu = getMenuBar().getMenu(1); for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(true),i++);

18

getMenuBar().getShortcutMenuItem(new MenuShortcut(kControlP)).setEnabled(false); panel.repaint(); } else if(e.getActionCommand().equalsIgnoreCase("About")) { JOptionPane.showMessageDialog(null, "This small freeware program is written by Yasir Feroze Minhas.", "About", JOptionPane.PLAIN_MESSAGE); } }//actionPerformed() }//windowHandler - Inner Class ends here }//SimpleDrawingTool class DrawingPanel extends Panel implements MouseListener { private Point sPoint = null; private Point ePoint = null; private Shapes shape = null; private java.util.ArrayList list = new java.util.ArrayList(); //override panel paint method to draw shapes public void paint(Graphics g) { g.setColor(Color.green); shape.draw(list, g); } public void drawShape(Shapes shape) { this.shape = shape; } //define mouse handler public void mouseClicked(MouseEvent e) { //if user wants to draw triangle, call repaint after 3 clicks if(shape instanceof TriangleShape) { list.add(e.getPoint()); if(list.size() > 2) { repaint(); } } else if(shape instanceof PolygonShape) { list.add(e.getPoint()); } }//mouseClicked public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} public void mousePressed(MouseEvent e) { sPoint = e.getPoint(); }//mousePressed public void mouseReleased(MouseEvent e) {

19

ePoint = e.getPoint(); if(ePoint.getX() < sPoint.getX()) { Point temp = ePoint; ePoint = sPoint; sPoint = temp; } if(ePoint.getY() < sPoint.getY()) { int temp = (int)ePoint.getY(); ePoint.y = (int)sPoint.getY(); sPoint.y = temp; } if(shape instanceof RectangleShape || shape instanceof OvalShape) { list.clear(); list.add(sPoint); list.add(ePoint); repaint(); } }//mouseReleased }//DrawingPanel

EXPECTED OUTPUT:

20

RESULT: Thus a simple paint application program is implemented using the menus and buttons in Java. Exp. No.: 8
21

SCIENTIFIC CALCULATOR AIM: To develop a scientific calculator using even-driven programming in Java. ALGORITHM: Step 1: Step 2: Step 3: Step 4: Step 5: Step 6: Step 7: Create a Calculator Frame (size 200 by 270) Add MenuBar to it. Add MenuItem (CheckBox type Basic And Extended) Add TextField (to show the result of the calculations) Add CheckBox for radians and degree Add Button to the Frame (20 for basic and another 8 for extended) The following Action/Item methods to be included (a) actionPerformed(ActionEvent ae){ all the action performed on the calculator will be noted by this method like pressing add(+) button etc} (b) itemStateChanged(ItemEvent ie){ this will checks on the menubar itemse.g. if you click on the extended item of View menu you will see the extended view of the calculator} Step 8: The other methods/classes to be used (i) makeCalculator(){ this will build the GUI for the calculator} (ii) resetButtons (num) { this will reset the buttons i.e. change the property to false} (iii)reciprocal(num){ if num is zero than error message else num =1/num} (iv) changeSign(num){ change the sign of the num} (v) factorial(num){ if num is less than 1 error message else do the factorial} (vi) class MessageBox extends Dialog implements ActionListener {this class is called from other methods to display the error messages.Make a constructor}
PROGRAM:
import java.awt.*; import java.awt.event.*; // class CalcFrame for creating a calcul // ator 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); } }); } }

22

// main class Calculator implemnets two interfaces ActionListener and ItemListener public class Calculator implements ActionListener, ItemListener { // creating instances of objects CalcFrame fr; MenuBar mb; Menu view, font, about; MenuItem bold, regular, author; CheckboxMenuItem basic, scientific; CheckboxGroup cbg; Checkbox radians, degrees; 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("Basic Calculator"); // set the size fr.setSize(200,270); fr.setBackground(Color.blue);; // create a menubar for the frame mb = new MenuBar(); // add menu the menubar view = new Menu("View"); font = new Menu ("Font"); about = new Menu("About"); // create instance of object for View me // nu basic = new CheckboxMenuItem("Basic",true); // add a listener to receive item events // when the state of an item changes basic.addItemListener(this); scientific = new CheckboxMenuItem("Scientific"); // add a listener to receive item events when the state of an item changes

23

scientific.addItemListener(this); // create instance of object for font me // nu bold = new MenuItem("Arial Bold"); bold.addActionListener(this); regular = new MenuItem("Arial Regular"); regular.addActionListener(this); // for about menu author = new MenuItem("Author"); author.addActionListener(this); // add the items in the menu view.add(basic); view.add(scientific); font.add(bold); font.add(regular); about.add(author); // add the menus in the menubar mb.add(view); mb.add(font); mb.add(about); // add menubar to the frame fr.setMenuBar(mb); // override the layout manager 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 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); 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);

24

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 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

25

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(false); 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(false); 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(false); 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(false); 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(false); 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);

26

scientificKey[5].setVisible(false); fr.add(scientificKey[5]); // aTan scientificKey[6] = new Button("aTan"); scientificKey[6].addActionListener(this); scientificKey[6].setBounds(220, 180, BWIDTH + 10, scientificKey[6].setBackground(Color.yellow); scientificKey[6].setVisible(false); fr.add(scientificKey[6]); // E scientificKey[7] = new Button("E"); scientificKey[7].addActionListener(this); scientificKey[7].setBounds(220, 210, BWIDTH + 10, scientificKey[7].setBackground(Color.yellow); scientificKey[7].setVisible(false); fr.add(scientificKey[7]); // to degrees scientificKey[8] = new Button("todeg"); scientificKey[8].addActionListener(this); scientificKey[8].setBounds(180, 240, BWIDTH + 10, scientificKey[8].setBackground(Color.yellow); scientificKey[8].setVisible(false); fr.add(scientificKey[8]); // to radians scientificKey[9] = new Button("torad"); scientificKey[9].addActionListener(this); scientificKey[9].setBounds(220, 240, BWIDTH + 10, scientificKey[9].setBackground(Color.yellow); scientificKey[9].setVisible(false); fr.add(scientificKey[9]); cbg = new CheckboxGroup(); degrees = new Checkbox("Degrees", cbg, true); radians = new Checkbox("Radians", cbg, false); degrees.addItemListener(this); radians.addItemListener(this); degrees.setBounds(185, 75, 3 * BWIDTH, BHEIGHT); radians.setBounds(185, 95, 3 * BWIDTH, BHEIGHT); degrees.setVisible(false); radians.setVisible(false); fr.add(degrees); fr.add(radians); fr.add(display); fr.setVisible(true); } // end of makeCalculator

BHEIGHT);

BHEIGHT);

BHEIGHT);

BHEIGHT);

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) {

27

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; } // 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;

28

} // 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; } // now for scientific buttons if (buttonText == "Sin") { if (degrees.getState()) display.setText(Double.toString(Math.sin(Math.PI * displayNumber/180))); else { display.setText(Double.toString(Math.sin(displayNumber))); currentNumber = 0; decimalPointPressed = false; } } if (buttonText == "Cos") { if (degrees.getState()) display.setText(Double.toString(Math.cos(Math.PI * displayNumber/180))); else{ display.setText(Double.toString( Math.cos(displayNumber))); currentNumber = 0; decimalPointPressed = false; } } if (buttonText == "Tan") { if (degrees.getState()) display.setText(Double.toString(Math.tan(Math.PI * displayNumber/180))); else { display.setText(Double.toString(Math.tan(displayNumber))); currentNumber = 0; decimalPointPressed = false; } } if (buttonText == "aSin") { if (degrees.getState()) display.setText(Double.toString(Math.asin(displayNumber)* 180/Math.PI ));

29

else { display.setText(Double.toString(Math.asin(displayNumber))); currentNumber = 0; decimalPointPressed = false; } } if (buttonText == "aCos") { if (degrees.getState()) display.setText(Double.toString(Math.acos(displayNumber)* 180/Math.PI )); else { display.setText(Double.toString(Math.acos(displayNumber))); currentNumber = 0; decimalPointPressed = false; } } if (buttonText == "aTan") { if (degrees.getState()) display.setText(Double.toString(Math.atan(displayNumber)* 180/Math.PI )); else { display.setText(Double.toString(Math.atan(displayNumber))); currentNumber = 0; decimalPointPressed = false; } } 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; } 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"){

30

// 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) 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(); } if (buttonText == "Arial Regular") { for (int i =0; i < 10; ++i) key[i].setFont(new Font("Arial", Font.PLAIN, 12)); } if (buttonText == "Arial Bold") { for (int i =0; i < 10; ++i) key[i].setFont(new Font("Arial", Font.BOLD, 12)); } if (buttonText == "Author") {

31

MessageBox mb = new MessageBox ( fr, "Calculator ver 1.0 beta ", true, "Author: Inder Mohan Singh."); mb.show(); } } // end of action events public void itemStateChanged(ItemEvent ie) { if (ie.getItem() == "Basic") { basic.setState(true); scientific.setState(false); fr.setTitle("Basic Calculator"); fr.setSize(200,270); // check if the scientific keys are visi // ble. if true hide them if (scientificKey[0].isVisible()) { for (int i=0; i < 8; ++i) scientificKey[i].setVisible(false); radians.setVisible(false); degrees.setVisible(false); } } if (ie.getItem() == "Scientific") { basic.setState(false); scientific.setState(true); fr.setTitle("Scientific Calculator"); fr.setSize(270,270); // check if the scientific keys are visi // ble. if true display them if (!scientificKey[0].isVisible()) { for (int i=0; i < 10; ++i) scientificKey[i].setVisible(true); radians.setVisible(true); degrees.setVisible(true); } } } // 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"); } else { for (int i=(theNum -1); i > 1; --i)

32

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(); }

33

EXPECTED OUTPUT:

34

RESULT: Thus the scientific calculator program is implemented using the even-driven programming in Java. Exp. No.: 9 JAVA TEMPLATE FOR LINKED LIST
35

AIM: To develop a simple to implement linked list in Java. ALGORITHM: Step 1: Transformation of global hits to local hits. Step 2: Creation of links between hits. Step 3: Matching of links into local segments. Step 4: Fitting of local segments. Step 5: Filtering of local segments. Step 6: Fitting of local segments in one layer to local segments in other layers; transformation back to global system. PROGRAM:
import java.util.List; import java.util.LinkedList; import java.util.Iterator; import java.util.ListIterator; import java.util.Collections; import java.util.Random; public class LinkedListExample { public void doLinkedListExample() { final int MAX = 10; int counter = 0; System.out.println("+--------------------------------------------------------------------+"); System.out.println("| Create/Store objects in an LinkedList container. |"); System.out.println("+--------------------------------------------------------------------+"); System.out.println(); List listA = new LinkedList(); List listB = new LinkedList(); for (int i = 0; i < MAX; i++) { System.out.println(" - Storing Integer(" + i + ")"); listA.add(new Integer(i)); } System.out.println(" - Storing String(Alex)"); listA.add("Alex"); System.out.println(" - Storing String(Melody)"); listA.add("Melody"); System.out.println(" - Storing String(Jeff)"); listA.add("Jeff"); System.out.println(" - Storing String(Alex)"); listA.add("Alex"); System.out.println(); System.out.println("+--------------------------------------------------------------------+");

36

System.out.println("| Retrieve objects in an LinkedList container using an Iterator. |"); System.out.println("+--------------------------------------------------------------------+"); System.out.println(); Iterator i = listA.iterator(); while (i.hasNext()) { System.out.println(i.next()); } System.out.println(); System.out.println("+--------------------------------------------------------------------+"); System.out.println("| Retrieve objects in an LinkedList container using a ListIterator. |"); System.out.println("+--------------------------------------------------------------------+"); System.out.println(); counter = 0; ListIterator li = listA.listIterator(); while (li.hasNext()) { System.out.println("Element [" + counter + "] = " + li.next()); System.out.println(" - hasPrevious = " + li.hasPrevious()); System.out.println(" - hasNext = " + li.hasNext()); System.out.println(" - previousIndex = " + li.previousIndex()); System.out.println(" - nextIndex = " + li.nextIndex()); System.out.println(); counter++; } System.out.println(); System.out.println("+--------------------------------------------------------------------+"); System.out.println("| Retrieve objects in an LinkedList container using index. |"); System.out.println("+--------------------------------------------------------------------+"); System.out.println(); for (int j=0; j < listA.size(); j++) { System.out.println("[" + j + "] - " + listA.get(j)); } System.out.println(); System.out.println("+--------------------------------------------------------------------+"); System.out.println("| Search for a particular Object and return its index location. |"); System.out.println("+--------------------------------------------------------------------+"); System.out.println(); int locationIndex = listA.indexOf("Jeff"); System.out.println("Index location of the String \"Jeff\" is: " +

37

locationIndex); System.out.println(); System.out.println("+--------------------------------------------------------------------+"); System.out.println("| Search for an object and return the first and last (highest) index. |"); System.out.println("+--------------------------------------------------------------------+"); System.out.println(); System.out.println("First occurance search for String \"Alex\". Index = " + listA.indexOf("Alex")); System.out.println("Last Index search for String \"Alex\". Index = " + listA.lastIndexOf("Alex")); System.out.println(); System.out.println("+--------------------------------------------------------------------+"); System.out.println("| Extract a sublist from the main list, then print the new List. |"); System.out.println("+--------------------------------------------------------------------+"); System.out.println(); List listSub = listA.subList(10, listA.size()); System.out.println("New Sub-List from index 10 to " + listA.size() + ": " + listSub); System.out.println(); System.out.println("+--------------------------------------------------------------------+"); System.out.println("| Sort the Sub-List created above. |"); System.out.println("+--------------------------------------------------------------------+"); System.out.println(); System.out.println("Original List : " + listSub); Collections.sort(listSub); System.out.println("New Sorted List : " + listSub); System.out.println(); System.out.println(); System.out.println("+--------------------------------------------------------------------+"); System.out.println("| Reverse the Sub-List created above. |"); System.out.println("+--------------------------------------------------------------------+"); System.out.println(); System.out.println("Original List : " + listSub); Collections.reverse(listSub); System.out.println("New Reversed List : " + listSub); System.out.println();

38

System.out.println(); System.out.println("+--------------------------------------------------------------------+"); System.out.println("| Check to see if the Lists are empty. |"); System.out.println("+--------------------------------------------------------------------+"); System.out.println(); System.out.println("Is List A empty? " + listA.isEmpty()); System.out.println("Is List B empty? " + listB.isEmpty()); System.out.println("Is Sub-List empty? " + listSub.isEmpty()); System.out.println(); System.out.println("+--------------------------------------------------------------------+"); System.out.println("| Clone the initial List. |"); System.out.println("| NOTE: The contents of the List are object references, so both |"); System.out.println("| of the List's contain the same exact object reference's. |"); System.out.println("+--------------------------------------------------------------------+"); System.out.println(); System.out.println("List A (before) : " + listA); System.out.println("List B (before) : " + listB); System.out.println("Sub-List (before) : " + listSub); System.out.println(); System.out.println("Are List's A and B equal? " + listA.equals(listB)); System.out.println(); listB = new LinkedList(listA); System.out.println("List A (after) : " + listA); System.out.println("List B (after) : " + listB); System.out.println("Sub-List (after) : " + listSub); System.out.println(); System.out.println("Are List's A and B equal? " + listA.equals(listB)); System.out.println(); System.out.println("+--------------------------------------------------------------------+"); System.out.println("| Shuffle the elements around in some Random order for List A. |"); System.out.println("+--------------------------------------------------------------------+"); System.out.println(); System.out.println("List A (before) : " + listA); System.out.println("List B (before) : " + listB); System.out.println("Sub-List (before) : " + listSub);

39

System.out.println(); System.out.println("Are List's A and B equal? " + listA.equals(listB)); System.out.println(); Collections.shuffle(listA, new Random()); System.out.println("List A (after) : " + listA); System.out.println("List B (after) : " + listB); System.out.println("Sub-List (after) : " + listSub); System.out.println(); System.out.println("Are List's A and B equal? " + listA.equals(listB)); System.out.println(); System.out.println("+--------------------------------------------------------------------+"); System.out.println("| Convert a List to an Array. |"); System.out.println("+--------------------------------------------------------------------+"); System.out.println(); Object[] objArray = listA.toArray(); for (int j=0; j < objArray.length; j++) { System.out.println("Array Element [" + j + "] = " + objArray[j]); } System.out.println(); System.out.println("+--------------------------------------------------------------------+"); System.out.println("| Remove (clear) Elements from List A. |"); System.out.println("+--------------------------------------------------------------------+"); System.out.println(); System.out.println("List A (before) : " + listA); System.out.println("List B (before) : " + listB); System.out.println(); listA.clear(); System.out.println("List A (after) : " + listA); System.out.println("List B (after) : " + listB); System.out.println(); } public static void main(String[] args) { LinkedListExample listExample = new LinkedListExample(); listExample.doLinkedListExample(); } }

40

EXPECTED OUTPUT:
+---------------------------------------------------------------------+ | Convert a List to an Array. | +---------------------------------------------------------------------+ Array Element [0] = Melody Array Element [1] = 4 Array Element [2] = 5 Array Element [3] = 8 Array Element [4] = Jeff Array Element [5] = Alex Array Element [6] = 0 Array Element [7] = 1 Array Element [8] = Alex Array Element [9] = 3 Array Element [10] = 9 Array Element [11] = 6 Array Element [12] = 2 Array Element [13] = 7 +---------------------------------------------------------------------+ | Remove (clear) Elements from List A. | +---------------------------------------------------------------------+ List A (before) : [Melody, 4, 5, 8, Jeff, Alex, 0, 1, Alex, 3, 9, 6, 2, 7] List B (before) : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, Melody, Jeff, Alex, Alex] List A (after) : [] List B (after) : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, Melody, Jeff, Alex, Alex]

41

RESULT: Thus a simple program to sort a given string in descending order is implemented in Java. Exp. No.: 10 MULTI-THREADED PRODUCER-CONSUMER APPLICATION AIM: To develop a multi-threaded producer-consumer application in Java. ALGORITHM: Step 1: Implement the Test class. Step 2: Call the object's wait method, Step 3: Wait approach the role of the release of the current thread acquired the lock, and call the object's notifyAll () method. Step 4: The value of the array is only used to mark Step 5: Then the next time (which may be other producers) to place items starting position Step 6: The direction of rotation through a fixed round-table to the orderly production and consumption PROGRAM:
import java.util.*; import java.io.*; public class Test { public static void main(String[] args) { Godown godown = new Godown(30); Consumer c1 = new Consumer(50, godown); Consumer c2 = new Consumer(20, godown); Consumer c3 = new Consumer(30, godown); Producer p1 = new Producer(10, godown); Producer p2 = new Producer(10, godown); Producer p3 = new Producer(10, godown); Producer p4 = new Producer(10, godown); Producer p5 = new Producer(10, godown); Producer p6 = new Producer(10, godown);

42

} } /** * Warehouse */ class Godown { public static final int max_size = 100; // Maximum inventory public int curnum; // Current inventory Godown() { } Godown(int curnum) { this.curnum = curnum; } /** * Specify the quantity of product production * * @param neednum */ public synchronized void produce(int neednum) { // Tests whether the necessary production while (neednum + curnum > max_size) { System.out.println(" The number of products to be produced " + neednum + " Over the remaining inventory " + (max_size curnum) + " For the time being, the production tasks cannot be performed !"); try { // The current thread to wait for the production wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // Meet production conditions for production, this is a simple change to the current inventory curnum += neednum; System.out.println(" Produced " + neednum + " Products, warehousing capacity " + curnum); // Wake up in the object monitor all threads waiting on notifyAll(); } /** * The consumer specifies the number of products *

Producer p7 = new Producer(80, godown); c1.start(); c2.start(); c3.start(); p1.start(); p2.start(); p3.start(); p4.start(); p5.start(); p6.start(); p7.start();

43

* @param neednum */ public synchronized void consume(int neednum) { // Test that you can consumption while (curnum < neednum) { try { // The current thread to wait for the production wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // Matching criteria, the consumer, this is a simple change to the current inventory curnum -= neednum; System.out.println(" Already consumed " + neednum + " Products, warehousing capacity " + curnum); // Wake up in the object monitor all threads waiting on notifyAll(); } } /** * Producer */ class Producer extends Thread { private int neednum; // The production number of the product private Godown godown; // Warehouse Producer(int neednum, Godown godown) { this.neednum = neednum; this.godown = godown; } public void run() { // Specify the quantity of product production godown.produce(neednum); } } /** * Consumers */ class Consumer extends Thread { private int neednum; product private Godown godown;

// The production number of the // Warehouse

Consumer(int neednum, Godown godown) { this.neednum = neednum; this.godown = godown; } public void run() { // The consumer specifies the number of products godown.consume(neednum); }

44

EXPECTED OUTPUT: Already consumed 20 Products, warehousing capacity 10 Produced 10 Products, warehousing capacity 20 Produced 10 Products, warehousing capacity 30 Already consumed 30 Products, warehousing capacity 0 Produced 10 Products, warehousing capacity 10 Produced 10 Products, warehousing capacity 20 Produced 10 Products, warehousing capacity 30 Produced 10 Products, warehousing capacity 40 The number of products to be produced 80 Over the remaining inventory 60 For the time being, the production tasks cannot be performed !

45

RESULT: Thus a multi-threaded producer-consumer application is developed in java. Exp. No.: 11 GENERATING PRIME AND FIBNOACCI NUMBER AIM: To write a java program for generating prime and Fibnoacci numbers from 1 to 1000. ALGORITHM: Step 1: pick a random number and check some formula involving the witness and the potential prime N. Step 2: After several iterations, they declare N to be "definitely composite" or "probably prime". Step 3: For a given test, there may be some composite numbers that will be declared "probably prime" no matter what witness is chosen. Step 4: The characteristic of every field is either zero or a prime number. Step 5: Compile and run the program PROGRAM: public class Fibonacci { public static void main(String []args) { int f1=0; int f2=0; int f3=1; System.out.println(The Fibo series is ::); System.out.println(f2); for(int i=0;i<10;i++) { System.out.println(f3); f1=f2; f2=f3; f3=f1+f2; } } }
46

public class prime_nos { public static void main(String []args) throws IOException { Scanner scan = new Scanner(System.in); int i,c,n; System.out.println(Enter the starting range ::); int a=scan.nextInt(); System.out.println(Enter the ending range ::); int b=scan.nextInt(); System.out.println(The prime nos are ::); for(n=a;n<b;n++) { c=0; for(i=1;i<=n;i++) { if(n%i==0) c++; } if(c==2) { System.out.println(n); } } } }

EXPECTED OUTPUT:
Enter the starting Range: 1000 1, 1, 2, 3, 5, 8, 13, 21, 34, 55.

47

RESULT: Thus a simple program to sort a given string in descending order is implemented in Java. Exp. No.: 12 A MULTI-THREADED GUI APPLICATION AIM: To write a java program to implement multithreading with GUI. ALGORITHM: Step 1: Create a GUI window using java swing or applet. Step 2: Write the code for implementing the menus. Step 3: Implement the java package for the client and server application. Step 4: Use corresponding port number to transfer the message from server to the client Step 5: Compile and run the client and server program PROGRAM:
package proj4; import java.net.*; import java.io.*; public class Server implements Runnable { ServerSocket serverSocket = null; Socket clientSocket = null; ObjectOutputStream out = null; ObjectInputStream in = null; int port; static int defaultPort = 30000; boolean isConnected = false; Thread thread; DataPacket packet = null; public Server(int _port) { try { serverSocket = new ServerSocket(_port); serverSocket.setSoTimeout(1000*120); //2 minutes time out isConnected = true; System.out.println("server started successfully"); thread = new Thread(this); thread.setDaemon(true); //thread.run(); } catch (IOException e) { System.err.print("Could not listen on port: " + port); System.exit(1); } try { System.out.println("Waiting for Client");

48

} public Server() { this(defaultPort); //server listens to port 30000 as default } public void run() { System.out.println("Thread running, listening for clients");//debugging purposes while (isConnected) { try { packet = this.getData(); Thread.sleep(0); } catch(InterruptedException e) { e.printStackTrace(); } } } public DataPacket getData() { try { packet = (DataPacket)in.readObject(); } catch (Exception ex) { System.out.println(ex.getMessage()); } return packet; } public void sendData(DataPacket dp) { try { out.writeObject(dp); } catch (IOException e) { e.printStackTrace(); } try { out.flush(); } catch (IOException e) { e.printStackTrace(); } } public void closeConnection() throws IOException {

clientSocket = serverSocket.accept(); System.out.println("Client Connected"); thread.run(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } try { out = new ObjectOutputStream(clientSocket.getOutputStream()); System.out.println("output stream created successfully"); } catch (IOException e) { e.printStackTrace(); } try { in = new ObjectInputStream(clientSocket.getInputStream()); System.out.println("input stream created successfully"); } catch (IOException e) { e.printStackTrace(); }

49

out.close(); in.close(); clientSocket.close(); serverSocket.close(); } }

EXPECTED OUTPUT:

RESULT:
50

Thus a multi-threaded GUI application is implemented in Java. References: Exp. No.: 3 http://www.idevelopment.info/data/Programming/java/date/DateExample.java Exp. No.: 7 http://www.developer.com/net/vb/article.php/874351/A-Simple-Java-Drawing-Tool.htm Exp. No.: 8 http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=2056&lngWId=2

51

You might also like