You are on page 1of 56

Syllabus

IT2305 JAVA PROGRAMMING LAB 0 0 3 2


Use JavaDoc

1. Develop a Java package with simple Stack and Queue classes. comments for documentation.

2. Design a class for Complex numbers in Java. In addition to methods for basic operations on complex numbers, provide a method to return the number of active objects created. 3. Design a Date class similar to the one provided in the java.util package. 4. Develop with suitable hierarchy, classes for Point, Shape, Rectangle, Square, Circle, Ellipse, Triangle, Polygon, etc. Design a simple test application to demonstrate dynamic polymorphism. 5. 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. 6. Write a Java program to read a file that contains DNA sequences of arbitrary length one per line (note that each DNA sequence is just a String). Your program should sort the sequences in descending order with respect to the number of 'TATA' subsequences present. Finally write the sequences in sorted order into another file. 7. Develop a simple paint-like program that can draw basic graphical primitives in different dimensions and colors. Use appropriate menu and buttons. 8. Develop a scientific calculator using even-driven programming paradigm of Java. 9. Develop a template for linked-list class along with its methods in Java. 10. Design a thread-safe implementation of Queue class. Write a multi-threaded producerconsumer application that uses this Queue class. 11. 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. 12. Develop a multi-threaded GUI application of your choice.

Ex.No: 01A

SIMPLE STACK CLASS PACKAGES


AIM: To develop a Java package with simple Stack class and use JavaDoc comments for documentation. PROGRAM: Package: MyStack.Stack package MyStack; import java.io.*; class Stack{ int tos; int size,arr[]; /** * Construct the stack. */ public Stack() { tos = -1; } /** * Set the size of array specified by user */ public void setsize()throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter the stack size :"); size=Integer.parseInt(br.readLine()); arr = new int[size]; } public void push(int item) { if(tos < size-1) { ++tos; arr[tos] = item; } else System.out.println("Stack is Full"); } /** * Return and remove the first inserted item * from the stack. * @return the first inserted item in the stack. */ public int pop() { if(tos > -1)

return arr[tos--]; else return -1; } /** * Display the items in the stack * @Display elements in First In First Out fashion. */ public void display() { if(tos > -1) { System.out.println("The stack is"); for(int i=tos;i>=0;i--) System.out.println(arr[i]); } else System.out.println("The stack is empty"); } } Main class package MyStack; import java.io.*; class StackDemo { public static void main(String args[])throws IOException { int size,choice,opt,item; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); Stack s = new Stack(); s.setsize(); do { System.out.println("1.Push\n2.Pop\n3.Display\n4.Exit\n"); System.out.print("Enter your choice :"); opt = Integer.parseInt(br.readLine()); switch(opt) { case 1: System.out.print("Enter the item to be pushed :"); item = Integer.parseInt(br.readLine()); s.push(item); break; case 2: item = s.pop(); if(item != -1) System.out.println("The popped item is " +item);

else System.out.println("The stack is empty."); break; case 3: s.display(); break; case 4: break; } }while(opt != 4); } } RESULT: Thus a Java package with simple Stack class was developed and JavaDoc comments for documentation was used.

Ex.No: 01B

SIMPLE QUEUE CLASS PACKAGES


AIM: To develop a Java package with simple Queue class and use JavaDoc comments for documentation. PROGRAM: Package: MyQueue.pArrayQueue package MyQueue; public class pArrayQueue{ protected Object[] array; protected int start,end; protected boolean full; static int n; public pArrayQueue(int maxsize){ array = new Object[maxsize]; start = end = 0; full = false; } public boolean isEmpty(){ return ((start == end) && !full); } public void insert(Object o){ if(!full){ array[start = (++start % array.length)] = o;n++;} if(start == end) full = true; } public Object remove(){ if(full) full = false; else if(isEmpty()) return null; n--; return array[end = (++end % array.length)]; } public void display(){ int pos; if(isEmpty()) System.out.println("Queue Empty..."); else { pos=end;

for(int i=0;i<n;i++) { System.out.println(array[pos = (++pos % array.length)]); } } } } Main class package MyQueue; import java.io.*; class pArrayQueueTest{ public static void main(String[] args)throws IOException{ pArrayQueue q = new pArrayQueue(10); Integer j = null; int i,ch,n; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); do { System.out.println("\nMENU\n*****\n1.Enqueue\n2.Dequeue\n3.Display\n4.exit"); System.out.println("Enter U'r Choice: "); ch=Integer.parseInt(br.readLine()); switch(ch) { case 1: { System.out.println("Enter the no of elements to be inserted: "); n=Integer.parseInt(br.readLine()); for(i=0;i<n;i++){ System.out.println("Enter the "+(i+1)+"element: "); j = Integer.parseInt(br.readLine()); q.insert(j); } break; } case 2: { if(!q.isEmpty()) System.out.println("Removed element: " + ((Integer)q.remove())); else System.out.println("Queue is Empty"); break; } case 3: { System.out.println("The elements in the Queue are: "); q.display(); break;

} case 4: System.exit(0); default: System.out.println("Wrong Choice!!!"); } }while(ch!=4); } } RESULT: Thus a Java package with simple Queue class was developed and JavaDoc comments for documentation was used.

Ex.No: 02

COMPLEX NUMBERS CLASSES AND OBJECTS


AIM: To design a class for Complex numbers with methods for basic operations and provide a method to return the number of active objects created in JAVA. PROGRAM: import java.io.*; class compclass { double x; double y; static int i; compclass(double a,double b) { x=a; y=b; i++; } void display() { System.out.println("("+x+"+"+y+"i)"); } } class ComplexManip { public static void main(String args[])throws IOException { double v1,v2; compclass Obj[]=new compclass[4]; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter the First Complex Numbers real value: "); v1=Double.parseDouble(br.readLine()); System.out.print("Enter the First Complex Numbers imaginary value: "); v2=Double.parseDouble(br.readLine()); Obj[0]=new compclass(v1,v2); System.out.print("Enter the First Complex Numbers real value: "); v1=Double.parseDouble(br.readLine()); System.out.print("Enter the First Complex Numbers imaginary value: "); v2=Double.parseDouble(br.readLine()); Obj[1]=new compclass(v1,v2);

double sumx=Obj[0].x+Obj[1].x; double sumy=Obj[0].y+Obj[1].y; double diffx=Obj[0].x-Obj[1].x; double diffy=Obj[0].y-Obj[1].y; Obj[2]=new compclass(sumx,sumy); Obj[3]=new compclass(diffx,diffy); System.out.print("Object 1 ="); Obj[0].display(); System.out.print("Object 2 ="); Obj[1].display(); System.out.print("Sum ="); Obj[2].display(); System.out.print("Difference ="); Obj[3].display(); System.out.println("No of objects created are : "+Obj[3].i); } }

RESULT: Thus a class for Complex numbers with methods for basic operations is designed and a method to return the number of active objects created was provided in JAVA.

Ex.No: 03

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 * @author B.Narmada * ----------------------------------------------------------------------------*/ 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:

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

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

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

Ex.No: 04

SHAPES INHERITANCE
AIM: To develop with suitable hierarchy, classes for Point, Shape, Rectangle, Square, Circle, Ellipse, Triangle, Polygon, etc., and to design a simple test application to demonstrate dynamic polymorphism. PROGRAM: //SHAPES USING INHERITANCE import java.io.*; /** This class demonstrates Shape class * @author B.Narmada * @version */ class Shape { /** data memebers defined with symbolic constant */ double pi=3.14; double tri_const=0.5; /** This method is used for calculating area*/ void area(int a,int b){ } } /**This class is inheritated from * public class Shape */ class Point extends Shape { /**This method does not return any value * @No paramters * @Displays the coordinates of a point */ public void area(int a,int b) { System.out.println("THE COORDINATES OF A POINT ARE:\t("+a+","+b+")"); } } /**This class is inheritated from * public class Shape

*/ class Square extends Shape { /**This method does not return any value * @No paramters * @Calculates are of Square * @Displays the area of a Square */ public void area(int a,int b) { System.out.println("AREA OF SQUARE:\t"+a*a); } } /**This class is inheritated from * public class Shape */ class Ellipse extends Shape { /**This method does not return any value * @No paramters * @Calculates are of Ellipse * @Displays the area of a Ellipse */ public void area(int a,int b) { System.out.println("AREA OF ELLIPSE:\t"+pi*a*b); } } /**This class is inheritated from * public class Shape */ class Tri extends Shape { /**This method does not return any value * @No paramters * @Calculates are of Triangle * @Displays the area of a Triangle */ public void area(int a,int b) { System.out.println("AREA OF TRIANGLE:\t"+tri_const*a*b); } } /**This class is inheritated from * public class Shape */ class Rec extends Shape {

/**This method does not return any value * @No paramters * @Calculates are of Rectangle * @Displays the area of a Rectangle */ public void area(int a,int b) { System.out.println("AREA OF RECTANGLE:\t "+a*b); } } /**This class is inheritated from * public class Shape */ class Cir extends Shape { /**This method does not return any value * @No paramters * @Calculates are of Circle * @Displays the area of a Circle */ public void area(int a,int b) { System.out.println("AREA OF CIRCLE:\t "+pi*a*a); } } /**This class is the main class * This class calls the methods in the public class Shape */ class ShapeHierachy { public static void main(String args[])throws IOException { Shape s; Point p=new Point(); Ellipse e=new Ellipse(); Square sq=new Square(); Tri t=new Tri(); Rec r=new Rec(); Cir c=new Cir(); System.out.println("INHERITNACE CONCEPT"); System.out.println("********************"); s=p; System.out.println("Enter the values: "); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int v1=Integer.parseInt(br.readLine()); int v2=Integer.parseInt(br.readLine()); // Dynamic method polymorphism s.area(v1,v2);

s=t; s.area(v1,v2); s=r; s.area(v1,v2); s=c; s.area(v1,v2); s=sq; s.area(v1,v1); s=e; s.area(v1,v2); } }

RESULT: Thus with suitable hierarchy, classes for Point, Shape, Rectangle, Square, Circle, Ellipse, Triangle, Polygon, etc., is implemented and a simple test application to demonstrate dynamic polymorphism is designed.

Ex.No: 05

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

Ex.No: 06

DNA SEQUENCES - CLASSES


AIM: To write a Java program to read a file that contains DNA sequences of arbitrary length one per line (note that each DNA sequence is just a String). The program should sort the sequences in ascending order with respect to the number of 'TATA' subsequences present. Finally to write the sequences in sorted order into another file PROGRAM: import java.io.*; import java.util.*; public class Sort { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new FileReader("d:\\java\\DNA.txt")); Map<String, String> map=new TreeMap<String, String>(); String line=""; while((line=reader.readLine())!=null){ map.put(getField(line),line); } reader.close(); FileWriter writer = new FileWriter("d:\\java\\op1.txt"); for(String val : map.values()){ writer.write(val); writer.write("\n"); } writer.close(); } private static String getField(String line) { return line.split(" ")[0];//extract value you want to sort on } }

INPUT: d:\\java\\DNA.txt ACAAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGGGCCACGGCCAC CGCTGCCCTGCC CCTGGAGGGTGGCCCCACCGGCCGAGACAGCGAGCATATGCAGGAAGCGGCAGGAA TAAGGAAAAGCAGC CTCCTGACTTTCCTCGCTTGGTGGTTTGAGTGGACCTCCCAGGCCAGTGCCGGGCCCC TCATAGGAGAGG AAGCTCGGGAGGTGGCCAGGCGGCAGGAAGGCGCACCCCCCCAGCAATCCGCGCGC CGGGACAGAATGCC CTGCAGGAACTTCTTCTGGAAGACCTTCTCCTCCTGCAAATAAAACCTCACCCATGAA TGCTCACGCAAG TTTAATTACAGACCTGAA

RESULT: Thus a Java program to read a file that contains DNA sequences of arbitrary length one per line (note that each DNA sequence is just a String) is written. The program should sorts the sequences in ascending order with respect to the number of 'TATA' subsequences present. Finally the sequences in sorted order is written into another file

Ex.No: 07

SIMPLE PAINT PROGRAM APPLET


AIM: To develop a simple paint-like program that can draw basic graphical primitives in different colors and to use appropriate buttons in JAVA language PROGRAM: /** * A simple program where the user can sketch curves in a variety of colors. * A color palette is shown on the right of the applet. * The user can select a drawing color by clicking on a color in the palette. * Under the colors is a "Clear button" that the user can press to clear the sketch. * The user draws by clicking and dragging in a large white area that occupies most of the applet. * The user's drawing is not persistant. * It is cleared if the applet is resized. * If it is covered, in whole or part, and then uncovered, the part was covered is gone. */ import java.awt.*; import java.awt.event.*; import java.applet.*; //<applet code=SimplePaint height=500 width=700></applet> public class SimplePaint extends Applet implements MouseListener, MouseMotionListener { private final static int BLACK = 0, RED = 1, // Some constants to make GREEN = 2, // the code more readable. BLUE = 3, // These numbers code for CYAN = 4, // the differnet drawing colors. MAGENTA = 5, YELLOW = 6; private int currentColor = BLACK; // The currently selected drawing color, // coded as one of the above constants. /* The following variables are used when the user is sketching a curve while dragging a mouse. */ private int prevX, prevY; private boolean dragging; // The previous location of the mouse. // This is set to true while the user is drawing.

private Graphics graphicsForDrawing; // A graphics context for the applet // that is used to draw the user's curve. public void init() {

// When the applet is first created, the applet is set to // listen for mouse events and mouse motion events from // itself. addMouseListener(this); addMouseMotionListener(this); } public void update(Graphics g) { // Redefine update so it does not fill the applet with the // background color before calling paint(). This is OK // since the paint() method always draws over the entire // surface of the applet. paint(g); } public void paint(Graphics g) { // Draw the contents of the applet. Since no information is // saved about what the user has drawn, the user's drawing // is erased whenever this routine is called. int width = getSize().width; // Width of the applet. int height = getSize().height; // Height of the applet. int colorSpacing = (height - 56) / 7; // Distance between the top of one colored rectangle in the palette // and the top of the rectangle below it. The height of the // rectangle will be colorSpacing - 3. There are 7 colored rectangles, // so the available space is divided by 7. The available space allows // for the gray border and the 50-by-50 CLEAR button. /* First, fill in the white drawing area, allowing for a three-pixel border at top, bottom, and left and allowing for the 56-pixel wide strip on the right that is occupied by the color palette and CLEAR button. (I could just fill the whole applet with white and then draw over some of it, but that leads to increased flickering when the applet is redrawn.) */ g.setColor(Color.white); g.fillRect(3, 3, width - 59, height - 6); /* Draw a 3-pixel border around the applet in gray. This has to be done by drawing three rectangles of different sizes. */ g.setColor(Color.gray); g.drawRect(0, 0, width-1, height-1); g.drawRect(1, 1, width-3, height-3); g.drawRect(2, 2, width-5, height-5); /* Draw a 56-pixel wide gray rectangle along the right edge of the applet. The color palette and Clear button will be drawn on top of this. (This covers some of the same area as the border I just drew. */

g.fillRect(width - 56, 0, 56, height); /* Draw the "Clear button" as a 50-by-50 white rectangle in the lower right corner of the applet, allowing for a 3-pixel border. */ g.setColor(Color.white); g.fillRect(width-53, height-53, 50, 50); g.setColor(Color.black); g.drawRect(width-53, height-53, 49, 49); g.drawString("CLEAR", width-48, height-23); /* Draw the seven color rectangles. */ g.setColor(Color.black); g.fillRect(width-53, 3 + 0*colorSpacing, 50, colorSpacing-3); g.setColor(Color.red); g.fillRect(width-53, 3 + 1*colorSpacing, 50, colorSpacing-3); g.setColor(Color.green); g.fillRect(width-53, 3 + 2*colorSpacing, 50, colorSpacing-3); g.setColor(Color.blue); g.fillRect(width-53, 3 + 3*colorSpacing, 50, colorSpacing-3); g.setColor(Color.cyan); g.fillRect(width-53, 3 + 4*colorSpacing, 50, colorSpacing-3); g.setColor(Color.magenta); g.fillRect(width-53, 3 + 5*colorSpacing, 50, colorSpacing-3); g.setColor(Color.yellow); g.fillRect(width-53, 3 + 6*colorSpacing, 50, colorSpacing-3); /* Draw a 2-pixel white border around the color rectangle of the current drawing color. */ g.setColor(Color.white); g.drawRect(width-55, 1 + currentColor*colorSpacing, 53, colorSpacing); g.drawRect(width-54, 2 + currentColor*colorSpacing, 51, colorSpacing-2); } // end paint() private void changeColor(int y) { // Change the drawing color after the user has clicked the // mouse on the color palette at a point with y-coordinate y. // (Note that I can't just call repaint and redraw the whole // applet, since that whould erase the user's drawing.) int width = getSize().width; // Width of applet. int height = getSize().height; // Height of applet. int colorSpacing = (height - 56) / 7; // Space for one color rectangle. int newColor = y / colorSpacing; // Which color number was clicked? if (newColor < 0 || newColor > 6) return; // Make sure the color number is valid.

/* Remove the hilite from the current color, by drawing over it in gray. Then change the current drawing color and draw a hilite around the new drawing color. */ Graphics g = getGraphics(); g.setColor(Color.gray); g.drawRect(width-55, 1 + currentColor*colorSpacing, 53, colorSpacing); g.drawRect(width-54, 2 + currentColor*colorSpacing, 51, colorSpacing-2); currentColor = newColor; g.setColor(Color.white); g.drawRect(width-55, 1 + currentColor*colorSpacing, 53, colorSpacing); g.drawRect(width-54, 2 + currentColor*colorSpacing, 51, colorSpacing-2); g.dispose(); } // end changeColor() private void setUpDrawingGraphics() { // This routine is called in mousePressed when the // user clicks on the drawing area. It sets up the // graphics context, graphicsForDrawing, to be used // to draw the user's sketch in the current color. graphicsForDrawing = getGraphics(); switch (currentColor) { case BLACK: graphicsForDrawing.setColor(Color.black); break; case RED: graphicsForDrawing.setColor(Color.red); break; case GREEN: graphicsForDrawing.setColor(Color.green); break; case BLUE: graphicsForDrawing.setColor(Color.blue); break; case CYAN: graphicsForDrawing.setColor(Color.cyan); break; case MAGENTA: graphicsForDrawing.setColor(Color.magenta); break; case YELLOW: graphicsForDrawing.setColor(Color.yellow); break; } } // end setUpDrawingGraphics() public void mousePressed(MouseEvent evt) { // This is called when the user presses the mouse anywhere // in the applet. There are three possible responses,

// depending on where the user clicked: Change the // current color, clear the drawing, or start drawing // a curve. (Or do nothing if user clicks on the border.) int x = evt.getX(); // x-coordinate where the user clicked. int y = evt.getY(); // y-coordinate where the user clicked. int width = getSize().width; // Width of the applet. int height = getSize().height; // Height of the applet. if (dragging == true) // Ignore mouse presses that occur return; // when user is already drawing a curve. // (This can happen if the user presses // two mouse buttons at the same time.) if (x > width - 53) { // User clicked to the right of the drawing area. // This click is either on the clear button or // on the color palette. if (y > height - 53) repaint(); // Clicked on "CLEAR button". else changeColor(y); // Clicked on the color palette. } else if (x > 3 && x < width - 56 && y > 3 && y < height - 3) { // The user has clicked on the white drawing area. // Start drawing a curve from the point (x,y). prevX = x; prevY = y; dragging = true; setUpDrawingGraphics(); } } // end mousePressed() public void mouseReleased(MouseEvent evt) { // Called whenever the user releases the mouse button. // If the user was drawing a curve, the curve is done, // so we should set drawing to false and get rid of // the graphics context that we created to use during // the drawing. if (dragging == false) return; // Nothing to do because the user isn't drawing. dragging = false; graphicsForDrawing.dispose(); graphicsForDrawing = null; } public void mouseDragged(MouseEvent evt) { // Called whenever the user moves the mouse // while a mouse button is held down. If the

// user is drawing, draw a line segment from the // previous mouse location to the current mouse // location, and set up prevX and prevY for the // next call. Note that in case the user drags // ouside of the drawing area, the values of // x and y are "clamped" to lie within this // area. This avoids drawing on the color palette // or clear buton. if (dragging == false) return; // Nothing to do because the user isn't drawing. int x = evt.getX(); // x-coordinate of mouse. int y = evt.getY(); // y=coordinate of mouse. if (x < 3) // Adjust the value of x, x = 3; // to make sure it's in if (x > getSize().width - 57) // the drawing area. x = getSize().width - 57; if (y < 3) // Adjust the value of y, y = 3; // to make sure it's in if (y > getSize().height - 4) // the drawing area. y = getSize().height - 4; graphicsForDrawing.drawLine(prevX, prevY, x, y); // Draw the line. prevX = x; // Get ready for the next line segment in the curve. prevY = y; } // end mouseDragged. public void mouseEntered(MouseEvent evt) { } public void mouseExited(MouseEvent evt) { } public void mouseClicked(MouseEvent evt) { } public void mouseMoved(MouseEvent evt) { } } // end class SimplePaint // Some empty routines. // (Required by the MouseListener // and MouseMotionListener // interfaces).

OUTPUT:

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.

Ex.No: 08

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

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

Ex.No: 09

LINKED LIST TEMPLATE


AIM: To develop a template for linked-list class along with its methods in Java. PROGRAM: import java.util.*; import java.io.*; public class LinkedListExample { public static void main(String args[])throws IOException { System.out.println("Linked List Example!"); LinkedList <Integer>list = new LinkedList<Integer>(); int num; int size,ch; Iterator iterator; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); do { System.out.println("\nMENU\n*****"); System.out.println("1.Insert\n2.Insert At First Position\n3.Insert At Last Position\n4.Insert At a specified Location\n5.Display List\n6.Display First element\n7.Display Last Element\n8.Display Element At a Position\n9.Remove First element\n10.Remove Last Element\n11.Remove Elements At a Position\n12.Remove All Elements\n13.Exit"); System.out.print("Enter U'r Choice: "); ch=Integer.parseInt(br.readLine()); switch(ch) { case 1: { //Adding data in the list System.out.print("Enter the no of elements the insert: "); size=Integer.parseInt(br.readLine()); for(int i=0;i<size;i++) { System.out.print("Enter "+(i+1)+" element: "); num=Integer.parseInt(br.readLine()); list.add(num); } System.out.print( "Linked list data: "); //Create a iterator

iterator = list.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next()+" "); } break; } case 2: { System.out.print("Enter element to be inserted in 1st location: "); num=Integer.parseInt(br.readLine()); list.addFirst(num); System.out.print("Now the list contain: "); iterator = list.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next()+" "); } System.out.println(); System.out.println("Now the size of list: " + list.size()); break; } case 3: { //Adding last or append System.out.print("Enter element to be inserted in Last location: "); num=Integer.parseInt(br.readLine()); list.addLast(num); System.out.print("Now the list contain: "); iterator = list.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next()+" "); } System.out.println(); System.out.println("Now the size of list: " + list.size()); break; } case 4: { System.out.print("Enter the location after which element has to be inserted: "); int pos=Integer.parseInt(br.readLine()); System.out.print("Enter element to be inserted at "+pos+":"); num=Integer.parseInt(br.readLine()); list.add(pos-1,num); System.out.print("Now the list contain: "); iterator = list.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next()+" "); } System.out.println(); System.out.println("Now the size of list: " + list.size()); break; }

case 5: { System.out.println(); //Check list empty or not if (list.isEmpty()){ System.out.println("Linked list is empty"); } else{ System.out.print("Now the list contain: "); iterator = list.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next()+" "); } System.out.println(); System.out.println("Now the size of list: " + list.size()); } break; } case 6: { //Retrieve first data System.out.println("First data: " + list.getFirst()); //Retrieve lst data break; } case 7: { System.out.println("Last data: " + list.getLast()); //Retrieve specific data break; } case 8: { System.out.print("Enter the position of the element to be displayed: "); int pos=Integer.parseInt(br.readLine()); System.out.println("Data at "+pos+" position: " + list.get(pos-1)); break; } case 9: { //Remove first int first = list.removeFirst(); System.out.println("Data removed from 1st location: " + first); System.out.print("Now the list contain: "); iterator = list.iterator(); //After removing data while (iterator.hasNext()){ System.out.print(iterator.next()+" "); }

System.out.println(); System.out.println("Now the size of list: " + list.size()); break; } case 10: { //Remove last int last = list.removeLast(); System.out.println("Data removed from last location: " + last); System.out.print("Now the list contain: "); iterator = list.iterator(); //After removing data while (iterator.hasNext()){ System.out.print(iterator.next()+" "); } System.out.println(); System.out.println("Now the size of list: " + list.size()); break; } case 11: { //Remove 2nd data System.out.print("Enter the position of the element to be displayed: "); int pos=Integer.parseInt(br.readLine()); int second = list.remove(pos-1); System.out.println("Data removed from "+pos+" location: " + second); System.out.print("Now the list contain: "); iterator = list.iterator(); //After removing data while (iterator.hasNext()){ System.out.print(iterator.next()+" "); } System.out.println(); System.out.println("Now the size of list: " + list.size()); break; } case 12: { //Remove all list.clear(); if (list.isEmpty()){ System.out.println("Linked list is empty"); } else{ System.out.println( "Linked list size: "+list.size()); } break; } case 13: { System.exit(0);

break; } default: System.out.println("Wrong Choice!!!"); } }while(ch!=13); } }

RESULT: Thus a template for linked-list class along with its methods was designed in Java.

Ex.No: 10

PRODUCER-CONSUMER APPLICATION MULTI THREADING


AIM: To design a thread-safe implementation of Queue class and write a multi-threaded producer-consumer application that uses this Queue class. PROGRAM: import java.util.*; import java.io.*; import java.util.concurrent.*; /** Producer-Consumer in Java, for J2SE 1.5 using concurrent. */ public class ProdCons15 { protected boolean done = false; /** Inner class representing the Producer side */ class Producer implements Runnable { protected BlockingQueue queue; Producer(BlockingQueue theQueue) { this.queue = theQueue; } public void run() { try { while (true) { Object justProduced = getRequestFromNetwork(); queue.put(justProduced); System.out.println("Produced 1 object; List size now " + queue.size()); if (done) { return; } } } catch (InterruptedException ex) { System.out.println("Producer INTERRUPTED"); } } Object getRequestFromNetwork() { // Simulation of reading from client try { Thread.sleep(10); // simulate time passing during read } catch (InterruptedException ex) { System.out.println("Producer Read INTERRUPTED"); } return(new Object());

} } /** Inner class representing the Consumer side */ class Consumer implements Runnable { protected BlockingQueue queue; Consumer(BlockingQueue theQueue) { this.queue = theQueue; } public void run() { try { while (true) { Object obj = queue.take(); int len = queue.size(); System.out.println("List size now " + len); process(obj); if (done) { return; } } } catch (InterruptedException ex) { System.out.println("CONSUMER INTERRUPTED"); } } void process(Object obj) { // Thread.sleep(xxx) // Simulate time passing System.out.println("Consuming object " + obj); } } ProdCons15(int nP, int nC) { BlockingQueue myQueue = new LinkedBlockingQueue(); for (int i=0; i<nP; i++) new Thread(new Producer(myQueue)).start(); for (int i=0; i<nC; i++) new Thread(new Consumer(myQueue)).start(); } public static void main(String[] args) throws IOException, InterruptedException { // Start producers and consumers int numProducers = 4; int numConsumers = 3; ProdCons15 pc = new ProdCons15(numProducers, numConsumers); // Let the simulation run for, say, 10 seconds Thread.sleep(100); // End of simulation - shut down gracefully

pc.done = true; } } 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.

Ex.No: 11

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

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

Ex.No: 12

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) { 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: Thus a multi-threaded GUI application for finding even and odd numbers was designed.

You might also like