java lab manual
TRANSCRIPT
![Page 1: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/1.jpg)
AIM
To develop a Java package with simple Stack and Queue classes. Use JavaDoc comments for documentation.
ALGORITHM
![Page 2: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/2.jpg)
SOURCE CODE
//package com.st.joesph.demo.queue;
/** * Array-based implementation of the queue. * @author Durai Murugan */public class ArrayQueue {
private Object [ ] theArray;private int currentSize;private int front;private int back;
private static final int DEFAULT_CAPACITY = 10;
/** * Construct the queue. */public ArrayQueue( ){
theArray = new Object[ DEFAULT_CAPACITY ];makeEmpty( );
}
/** * Test if the queue is logically empty. * @return <b>true</b> if empty, <code>false</code> otherwise. */public boolean isEmpty( ){
return currentSize == 0;}
/** * Make the queue logically empty. */public void makeEmpty( ){
currentSize = 0;front = 0;back = -1;
}
/** * Return and remove the least recently inserted item * from the queue. * @return the least recently inserted item in the queue. */public Object dequeue( ){
if( isEmpty( ) )throw new RuntimeException( "ArrayQueue dequeue" );
currentSize--;
Object returnValue = theArray[ front ];front = increment( front );
![Page 3: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/3.jpg)
return returnValue;}
/** * Get the least recently inserted item in the queue. * Does not alter the queue. * @return the least recently inserted item in the queue. */public Object getFront( ){
if( isEmpty( ) )throw new RuntimeException( "ArrayQueue getFront" );
return theArray[ front ];}
/** * Insert a new item into the queue. * @param x the item to insert. */public void enqueue( Object x ){
if( currentSize == theArray.length )doubleQueue( );
back = increment( back );theArray[ back ] = x;currentSize++;
}
/** * Internal method to increment with wraparound. * @param x any index in theArray's range. * @return x+1, or 0 if x is at the end of theArray. */private int increment( int x ){
if( ++x == theArray.length )x = 0;
return x;}
/** * Internal method to expand theArray. */private void doubleQueue( ){
Object [ ] newArray;
newArray = new Object[ theArray.length * 2 ];
// Copy elements that are logically in the queuefor( int i = 0; i < currentSize; i++, front =
increment( front ) )newArray[ i ] = theArray[ front ];
theArray = newArray;front = 0;back = currentSize - 1;
}}
![Page 4: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/4.jpg)
//package com.st.joesph.demo.queue;
/** * Array-based implementation of the stack. * @author Durai Murugan */public class ArrayStack {
private Object [ ] theArray; private int topOfStack; private static final int DEFAULT_CAPACITY = 10;
/** * Construct the stack. */ public ArrayStack( ) { theArray = new Object[ DEFAULT_CAPACITY ]; topOfStack = -1; } /** * Test if the stack is logically empty. * @return true if empty, false otherwise. */ public boolean isEmpty( ) { return topOfStack == -1; } /** * Make the stack logically empty. */ public void makeEmpty( ) { topOfStack = -1; } /** * Get the most recently inserted item in the stack. * Does not alter the stack. * @return the most recently inserted item in the stack. */ public Object top( ) { if( isEmpty( ) ) throw new RuntimeException( "ArrayStack top" ); return theArray[ topOfStack ]; } /** * Remove the most recently inserted item from the stack. */ public void pop( ) { if( isEmpty( ) ) throw new RuntimeException( "ArrayStack pop" ); topOfStack--; } /**
![Page 5: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/5.jpg)
* Return and remove the most recently inserted item * from the stack. * @return the most recently inserted item in the stack. */ public Object topAndPop( ) { if( isEmpty( ) ) throw new RuntimeException( "ArrayStack topAndPop" ); return theArray[ topOfStack-- ]; } /** * Insert a new item into the stack. * @param x the item to insert. */ public void push( Object x ) { if( topOfStack + 1 == theArray.length ) doubleArray( ); theArray[ ++topOfStack ] = x; } /** * Internal method to extend theArray. */ private void doubleArray( ) { Object [ ] newArray; newArray = new Object[ theArray.length * 2 ]; for( int i = 0; i < theArray.length; i++ ) newArray[ i ] = theArray[ i ]; theArray = newArray; } }
![Page 6: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/6.jpg)
//package com.st.joesph.demo.queue;
public class QueueStackTester {
public static void main(String[] args) {
System.out.println("****************************");System.out.println("Queue Example");System.out.println("****************************");
ArrayQueue aq = new ArrayQueue();
aq.enqueue(new String("1"));aq.enqueue(new String("2"));aq.enqueue(new String("3"));aq.enqueue(new String("4"));
System.out.println("Queue Elements -> 1, 2, 3, 4");System.out.println("Queue FIFO -> "+aq.getFront());System.out.println("Queue removed element -> "+
aq.dequeue());System.out.println("Queue FIFO -> "+aq.getFront());
System.out.println("****************************");System.out.println("Stack Example");System.out.println("****************************");
ArrayStack arrayStack = new ArrayStack();arrayStack.push(new String("a"));arrayStack.push(new String("b"));arrayStack.push(new String("c"));arrayStack.push(new String("d"));
System.out.println("Stack Elements -> a, b, c, d");System.out.println("Stack LIFO -> "+arrayStack.top());arrayStack.pop();System.out.println("POP on Stack " );System.out.println("Stack LIFO -> "+arrayStack.top());
}}
![Page 7: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/7.jpg)
OUTPUT
E:\User\Manikandan\Experiment 1>java QueueStackTester****************************Queue Example****************************Queue Elements -> 1, 2, 3, 4Queue FIFO -> 1Queue removed element -> 1Queue FIFO -> 2****************************Stack Example****************************Stack Elements -> a, b, c, dStack LIFO -> dPOP on StackStack LIFO -> c
E:\User\Manikandan\Experiment 1>
![Page 8: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/8.jpg)
AIM
To 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.
ALGORITHM
![Page 9: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/9.jpg)
SOURCE CODE
public class ComplexNumber {
public static int counter = 0;
private double realPart;private double imaginaryPart;
/** * Default Constructor */public ComplexNumber(){
counter++;}
/** * Parameterized Constructor * @param realPart * @param imaginaryPart */public ComplexNumber(double realPart, double imaginaryPart) {
this();this.realPart = realPart;this.imaginaryPart = imaginaryPart;
}
/** * Parameterized Constructor * @param realPart * @param imaginaryPart */public ComplexNumber(ComplexNumber complexNumber) {
this();this.realPart = complexNumber.getRealPart();this.imaginaryPart = complexNumber.getImaginaryPart();
}
/** * @return the realPart */public double getRealPart() {
return realPart;}
/** * @param realPart the realPart to set */public void setRealPart(double realPart) {
this.realPart = realPart;}
/** * @return the imaginaryPart */public double getImaginaryPart() {
![Page 10: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/10.jpg)
return imaginaryPart;}
/** * @param imaginaryPart the imaginaryPart to set */public void setImaginaryPart(double imaginaryPart) {
this.imaginaryPart = imaginaryPart;}
public ComplexNumber getComplexConjugate(){return new ComplexNumber(this.realPart, this.imaginaryPart *
-1);}
/** * @param multiComNum * @return */public ComplexNumber multiplyTo(ComplexNumber multiComNum){
ComplexNumber result = new ComplexNumber();//(a+bi)* (c+di) = (ac - bd) + (ad + bc) idouble _real = ((this.realPart * multiComNum.getRealPart())
- (this.imaginaryPart * multiComNum.getImaginaryPart()));double _imgry = ((this.realPart *
multiComNum.getImaginaryPart()) + (this.imaginaryPart * multiComNum.getRealPart()));
result.setRealPart(_real);result.setImaginaryPart(_imgry);return result;
}
/** * @param addComNum * @return */public ComplexNumber addTo(ComplexNumber addComNum){
ComplexNumber result = new ComplexNumber();//(a+bi) + (c+di) = (a+c) + (b+d) idouble _real = (this.realPart + addComNum.getRealPart());double _imgry = (this.imaginaryPart +
addComNum.getImaginaryPart());result.setRealPart(_real);result.setImaginaryPart(_imgry);return result;
}
/** * @param subsComNum * @return */public ComplexNumber subsTo(ComplexNumber subsComNum){
ComplexNumber result = new ComplexNumber();//(a+bi) - (c+di) = (a-c) + (b-d) idouble _real = (this.realPart - subsComNum.getRealPart());double _imgry = (this.imaginaryPart -
subsComNum.getImaginaryPart());result.setRealPart(_real);
![Page 11: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/11.jpg)
result.setImaginaryPart(_imgry);return result;
}
/** * @param divComNum * @return */public ComplexNumber divTo(ComplexNumber divComNum){
ComplexNumber result = new ComplexNumber(divComNum);//(a+bi) / (c+di) = (a+bi)(c-di) / (c +di)(c - di)//numerator partresult = result.multiplyTo(divComNum.getComplexConjugate());//dr double dnr = divComNum.getRealPart() *
divComNum.getRealPart() + divComNum.getImaginaryPart() * divComNum.getRealPart();
result.setRealPart(result.getRealPart() / dnr);result.setImaginaryPart(result.getImaginaryPart() / dnr);return result;
}
public String toString(){String imgPart = ((this.imaginaryPart) < 0 ?
String.valueOf(this.imaginaryPart) : "+"+this.imaginaryPart);return this.realPart+""+imgPart+"i";
}
public static void main(String[] args) {System.out.println("************************************");System.out.println("Complex Number Example");System.out.println("************************************");ComplexNumber complexNumber = new ComplexNumber(8, 4);ComplexNumber complexNumber2 = new ComplexNumber(1, 2);System.out.println("Complex Number = "+complexNumber);System.out.println(complexNumber +" ComplexConjugate =
"+complexNumber.getComplexConjugate());System.out.println("\nComplex Multiplication ");System.out.println("("+complexNumber+") ("+complexNumber2
+") = "+ complexNumber.multiplyTo(complexNumber2));
System.out.println("\nComplex Addition ");System.out.println("("+complexNumber+") + ("+complexNumber2
+") = "+ complexNumber.addTo(complexNumber2));
System.out.println("\nComplex Subraction ");System.out.println("("+complexNumber+") - ("+complexNumber2
+") = "+ complexNumber.subsTo(complexNumber2));
System.out.println("\nComplex Division ");System.out.println("("+complexNumber+") / ("+complexNumber2
+") = "+ complexNumber.divTo(complexNumber2));System.out.println("\nThe number of active objects created
during the basic complex number operations - "+ComplexNumber.counter);}
}
![Page 12: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/12.jpg)
OUTPUT
E:\User\Manikandan\Experiment 2>java ComplexNumber************************************Complex Number Example************************************Complex Number = 8.0+4.0i8.0+4.0i ComplexConjugate = 8.0-4.0i
Complex Multiplication(8.0+4.0i) (1.0+2.0i) = 0.0+20.0i
Complex Addition(8.0+4.0i) + (1.0+2.0i) = 9.0+6.0i
Complex Subraction(8.0+4.0i) - (1.0+2.0i) = 7.0+2.0i
Complex Division(8.0+4.0i) / (1.0+2.0i) = 1.6666666666666667+0.0i
The number of active objects created during the basic complex number operations - 9
E:\User\Manikandan\Experiment 2>------------------------------------------------------------------------------------------
![Page 13: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/13.jpg)
AIM
To design a Date class similar to the one provided in the java.util package.
ALGORITHM
![Page 14: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/14.jpg)
SOURCE CODE
import java.util.Date;import java.text.ParseException;import java.text.SimpleDateFormat;public class DateExample {
private static void DateExample() {
Date date = new Date(); System.out.println("Current Date and Time is : " + date); System.out.println();
System.out.println("Date object showing specific date and time"); Date particulardate1 = new Date(24L*60L*60L*1000L); Date particulardate2 = new Date(0L); System.out.println(); System.out.println("First Particular date : " + particulardate1); System.out.println("Second Particular date: " + particulardate2); System.out.println();
System.out.println("Demo of getTime() method returning milliseconds"); System.out.println(); Date strtime = new Date(); System.out.println("Start Time: " + strtime); Date endtime = new Date(); System.out.println("End Time is: " + endtime); long elapsed_time = endtime.getTime() - strtime.getTime(); System.out.println("Elapsed Time is:" + elapsed_time + " milliseconds"); System.out.println();
System.out.println("Changed date object using setTime() method"); System.out.println(); Date chngdate = new Date(); System.out.println("Date before change is: " + chngdate); chngdate.setTime(24L*60L*60L*1000L); System.out.println("Now the Changed date is: " + chngdate); System.out.println(); }
public static void main(String[] args) { System.out.println(); DateExample(); }
}
![Page 15: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/15.jpg)
OUTPUT
\ E:\User\Manikandan\Experiment 3>java simpledate************************************
Current Date and Time is : Mon Dec 10 18:39:27 GMT+05:30 2007
Date object showing specific date and time
First Particular date : Fri Jan 02 05:30:00 GMT+05:30 1970Second Particular date: Thu Jan 01 05:30:00 GMT+05:30 1970
Demo of getTime() method returning milliseconds
Start Time: Mon Dec 10 18:39:28 GMT+05:30 2007End Time is: Mon Dec 10 18:39:28 GMT+05:30 2007Elapsed Time is:0 milliseconds
Changed date object using setTime() method
Date before change is: Mon Dec 10 18:39:28 GMT+05:30 2007Now the Changed date is: Fri Jan 02 05:30:00 GMT+05:30 1970
![Page 16: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/16.jpg)
AIM
To develop with suitable hierarchy, classes for Point, Shape, Rectangle, Square, Circle, Ellipse, Triangle, Polygon, etc. Design a simple test application to demonstrate dynamic polymorphism.
ALGORITHM
![Page 17: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/17.jpg)
SOURCE CODE
public class Circle implements IShape {
private double radius;
public Circle(double radius){this.radius = radius;
}
public Double getAreaValue() {double area = 2 * 3.14 * radius * radius;return area;
}
public String getObjectName() {return "Circle";
}
}
public class DynamicPolymorphsim {
public static void main(String[] args) {
System.out.println("********************************************");System.out.println("\tDynamic Polymorphsim Example");
System.out.println("********************************************");Circle circleObject = new Circle(2.4);System.out.println("Circle object is created.\n");
Square square = new Square(2);System.out.println("Square object is created.\n");
Rectangular rectangular = new Rectangular(2, 10);System.out.println("Rectangular object is created.\n");
Triangle triangle = new Triangle(3, 2.76);System.out.println("Rectangular object is created.\n");
NonShape ec = new NonShape();System.out.println("NonShape object is created.\n");
System.out.println("---------------------------------------");System.out.println(" Calling Dynamic Polymorphsim method");
![Page 18: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/18.jpg)
System.out.println("---------------------------------------");
getShapeObjectDetails(circleObject);getShapeObjectDetails(square);getShapeObjectDetails(rectangular);getShapeObjectDetails(triangle);getShapeObjectDetails(ec);
}
public static void getShapeObjectDetails(Object iShape){if(iShape != null){
if(iShape instanceof IShape){IShape iShape1 = (IShape)iShape;System.out.println("Area of the
"+iShape1.getObjectName() +" = "+iShape1.getAreaValue());}else{
System.out.println("\nPassed object which is not implemented from IShape Interface");
}
}}
}
public interface IShape {
/** * @return the </code>IShape</code> Object Name */public String getObjectName();
/** * @return the <b>Area</b> value of the object */public Double getAreaValue();
}
public class NonShape {
public double getAreaValue(){return 0.0;
}
public String getObjectName(){return "test"; }}
![Page 19: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/19.jpg)
public class Rectangular implements IShape {
private double width;private double length;public Rectangular(double width, double length){
this.width = width;this.length = length;
}
public Double getAreaValue() {return width * length;
}
public String getObjectName() {return "Rectangular";
}
}
public class Square implements IShape {
private double size;
public Square(double size){this.size = size;
}
public Double getAreaValue() {return size * size;
}
public String getObjectName() {return "Square";
}
}
![Page 20: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/20.jpg)
public class Triangle implements IShape {
private double base;private double height;
public Triangle(double base, double height){this.base = base;this.height = height;
}
public Double getAreaValue() {double area = 0.5 * base * height;return area;
}
public String getObjectName() {return "Triangle";
}}
![Page 21: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/21.jpg)
OUTPUT
E:\User\Manikandan\Experiment 4>javac *.java
E:\User\Manikandan\Experiment 4>java DynamicPolymorphsim******************************************** Dynamic Polymorphsim Example********************************************Circle object is created.
Square object is created.
Rectangular object is created.
Rectangular object is created.
NonShape object is created.
--------------------------------------- Calling Dynamic Polymorphsim method---------------------------------------Area of the Circle = 36.172799999999995Area of the Square = 4.0Area of the Rectangular = 20.0Area of the Triangle = 4.14
Passed object which is not implemented from IShape Interface
E:\User\Manikandan\Experiment 4>
![Page 22: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/22.jpg)
AIM
To design a Java interface for ADT Stack. Develop two different classes that implement this interface, one using array and the other using linked-list. Provide necessary exception handling in both the implementations.
ALGORITHM
![Page 23: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/23.jpg)
SOURCE CODE
/** * Array-based implementation of the stack. * @author Durai Murugan */public class ArrayStack implements Stack {
private Object [ ] theArray; private int topOfStack; private static final int DEFAULT_CAPACITY = 10;
/** * Construct the stack. */ public ArrayStack( ) { theArray = new Object[ DEFAULT_CAPACITY ]; topOfStack = -1; } /** * Test if the stack is logically empty. * @return true if empty, false otherwise. */ public boolean isEmpty( ) { return topOfStack == -1; } /** * Make the stack logically empty. */ public void makeEmpty( ) { topOfStack = -1; } /** * Get the most recently inserted item in the stack. * Does not alter the stack. * @return the most recently inserted item in the stack. * @throws UnderflowException if the stack is empty. */ public Object top( ) { if( isEmpty( ) ) throw new UnderflowException( "ArrayStack top" ); return theArray[ topOfStack ]; } /** * Remove the most recently inserted item from the stack. * @throws UnderflowException if the stack is empty. */ public void pop( ) { if( isEmpty( ) ) throw new UnderflowException( "ArrayStack pop" ); topOfStack--; }
![Page 24: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/24.jpg)
/** * Return and remove the most recently inserted item * from the stack. * @return the most recently inserted item in the stack. * @throws Underflow if the stack is empty. */ public Object topAndPop( ) { if( isEmpty( ) ) throw new UnderflowException( "ArrayStack topAndPop" ); return theArray[ topOfStack-- ]; } /** * Insert a new item into the stack. * @param x the item to insert. */ public void push( Object x ) { if( topOfStack + 1 == theArray.length ) doubleArray( ); theArray[ ++topOfStack ] = x; } /** * Internal method to extend theArray. */ private void doubleArray( ) { Object [ ] newArray; newArray = new Object[ theArray.length * 2 ]; for( int i = 0; i < theArray.length; i++ ) newArray[ i ] = theArray[ i ]; theArray = newArray; } }
![Page 25: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/25.jpg)
//ListStack class//// CONSTRUCTION: with no initializer//// ******************PUBLIC OPERATIONS*********************// void push( x ) --> Insert x// void pop( ) --> Remove most recently inserted item// Object top( ) --> Return most recently inserted item// Object topAndPop( ) --> Return and remove most recent item// boolean isEmpty( ) --> Return true if empty; else false// void makeEmpty( ) --> Remove all items// ******************ERRORS********************************// top, pop, or topAndPop on empty stack
/** * List-based implementation of the stack. * @author Durai Murugan */public class LinkedListStack implements Stack {
/** * Construct the stack. */public LinkedListStack( ) {
topOfStack = null;}
/** * Test if the stack is logically empty. * @return true if empty, false otherwise. */public boolean isEmpty( ) {
return topOfStack == null;}
/** * Make the stack logically empty. */public void makeEmpty( ) {
topOfStack = null;}
/** * Insert a new item into the stack. * @param x the item to insert. */public void push( Object x ) {
topOfStack = new ListNode( x, topOfStack );}
/** * Remove the most recently inserted item from the stack. * @throws UnderflowException if the stack is empty. */public void pop( ) {
if( isEmpty( ) )throw new UnderflowException( "ListStack pop" );
![Page 26: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/26.jpg)
topOfStack = topOfStack.next;}
/** * Get the most recently inserted item in the stack. * Does not alter the stack. * @return the most recently inserted item in the stack. * @throws UnderflowException if the stack is empty. */public Object top( ) {
if( isEmpty( ) )throw new UnderflowException( "ListStack top" );
return topOfStack.element;}
/** * Return and remove the most recently inserted item * from the stack. * @return the most recently inserted item in the stack. * @throws UnderflowException if the stack is empty. */public Object topAndPop( ) {
if( isEmpty( ) )throw new UnderflowException( "ListStack topAndPop" );
Object topItem = topOfStack.element;topOfStack = topOfStack.next;return topItem;
}
private ListNode topOfStack;
}
public class ListNode {public Object element;public ListNode next;
// Constructorspublic ListNode( Object theElement ) {
this( theElement, null );}
public ListNode( Object theElement, ListNode n ) {element = theElement;next = n;
}}
![Page 27: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/27.jpg)
public interface Stack {/** * Insert a new item into the stack. * @param x the item to insert. */void push( Object x );
/** * Remove the most recently inserted item from the stack. * @exception UnderflowException if the stack is empty. */void pop( );
/** * Get the most recently inserted item in the stack. * Does not alter the stack. * @return the most recently inserted item in the stack. * @exception UnderflowException if the stack is empty. */Object top( );
/** * Return and remove the most recently inserted item * from the stack. * @return the most recently inserted item in the stack. * @exception UnderflowException if the stack is empty. */Object topAndPop( );
/** * Test if the stack is logically empty. * @return true if empty, false otherwise. */boolean isEmpty( );
/** * Make the stack logically empty. */void makeEmpty( );
}
![Page 28: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/28.jpg)
public class StackTester {
public static void main(String[] args) {
System.out.println("******************************************");System.out.println("Stack using Array & Linked List
example");
System.out.println("******************************************");
ArrayStack arrayStack = new ArrayStack();arrayStack.push(new String("a"));arrayStack.push(new String("b"));arrayStack.push(new String("c"));System.out.println("Stack[using array] elements -> a, b,
c");System.out.println("Stack LIFO and POP ->
"+arrayStack.topAndPop());System.out.println("Stack LIFO -> "+arrayStack.top());arrayStack.pop();try{
arrayStack.pop();arrayStack.topAndPop();
}catch(RuntimeException rte){System.err.println("Exception occured while POP
operation is happened on Stack[by using array]");}System.out.println("\n\n******************************");System.out.println("Stack using Linked List example");System.out.println("******************************");
LinkedListStack linkedListStack = new LinkedListStack();linkedListStack.push(new Integer(10));linkedListStack.push(new Integer(20));linkedListStack.push(new Integer(30));linkedListStack.push(new Integer(40));System.out.println("Stack[using linked list] elements -> 10,
20, 30, 40");System.out.println("Stack TOP ->"+linkedListStack.top());linkedListStack.pop();System.out.println("Stack TOP after POP -
>"+linkedListStack.top());linkedListStack.pop();linkedListStack.pop();linkedListStack.pop();try{
linkedListStack.pop();}catch(RuntimeException rte){
System.err.println("Exception occured while POP operation is happened on Stack[by using linked list]");
}
}}
![Page 29: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/29.jpg)
/** * Exception class for access in empty containers * such as stacks, queues, and priority queues. * @author Durai Murugan */public class UnderflowException extends RuntimeException {
/** * Construct this exception object. * @param message the error message. */public UnderflowException( String message ) {
super( message );}
}
OUTPUT
E:\User\Manikandan\Experiment 5>javac *.java
E:\User\Manikandan\Experiment 5>java StackTester******************************************Stack using Array & Linked List example******************************************Stack[using array] elements -> a, b, cStack LIFO and POP -> cStack LIFO -> bException occured while POP operation is happened on Stack[by using array]
******************************Stack using Linked List example******************************Stack[using linked list] elements -> 10, 20, 30, 40Stack TOP ->40Stack TOP after POP ->30Exception occured while POP operation is happened on Stack[by using linked list]
E:\User\Manikandan\Experiment 5>
![Page 30: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/30.jpg)
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). Your program should sort the sequences in descending order with respect to the number of 'GC'
ALGORITHM
![Page 31: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/31.jpg)
SOURCE CODE
import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class FileOperation {/** * subsequence search text */public static String SEARCH_CONTENT = "GC";
public static void main(String[] args) {String fi = ".\\file\\input.txt";String out = ".\\file\\output.txt";
System.out.println("****************************************************");
System.out.println(" DNA sequence example by File Read/Write Operation");
System.out.println("*****************************************************");
FileOperation fo = new FileOperation();String content = fo.getFileContent(fi);fo.writeTextToFile(content, out);
}
public void writeTextToFile(String content, String filePath){File outFile = null;FileOutputStream fis = null;BufferedOutputStream bos = null;outFile = new File(filePath);try {
System.out.println("\nSorted contents are written into "+outFile.getCanonicalPath());
fis = new FileOutputStream(outFile);bos = new BufferedOutputStream(fis);bos.write(content.getBytes());bos.close();
} catch (IOException e) {e.printStackTrace();
}
![Page 32: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/32.jpg)
}
public String getFileContent(String filePath) {String content = null;File file = new File(filePath);FileReader fr = null;BufferedReader br = null;List<FileContent> listFileContent = new
ArrayList<FileContent>(); try {
System.out.println("DNA Sequence file is located from ["+file.getCanonicalPath()+"]");
System.out.println("\n-----------------------------------------------------------------------");
fr = new FileReader(file);br = new BufferedReader(fr);int i = 0;String lineString = br.readLine();while(lineString != null){
System.out.println(lineString);//System.out.println(" bb --> "+
getSeqCount(lineString, "GC"));FileContent fileContent = new FileContent(i++,
getSeqCount(lineString, SEARCH_CONTENT), lineString);listFileContent.add(fileContent);lineString = br.readLine();
}fr.close();br.close();
} catch (FileNotFoundException e) {e.printStackTrace();
} catch (IOException e) {e.printStackTrace();
}
System.out.println("-----------------------------------------------------------------------");
System.out.println("Contents are loaded to find SubSequences of '"+SEARCH_CONTENT+"' for sorting the DNA contents");
content = sortLines(listFileContent);System.out.println("\nDNA Sequence contents are
sorted.....");return content;
}
public String sortLines(List<FileContent> listFileContents){List<FileContent> _lstFileContent = listFileContents;StringBuffer stringBuffer = new StringBuffer();int [] seqCntArray = new int [listFileContents.size()+1];int i = 0;for(FileContent fileContent : _lstFileContent){
seqCntArray[i++] = fileContent.getSeqCount();}/*SORTING THE ARRAY */
![Page 33: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/33.jpg)
Arrays.sort(seqCntArray);
for(int itr = seqCntArray.length; itr > 0 ; itr--){for(int j=0; j < _lstFileContent.size() ; j++){
FileContent fileContent = listFileContents.get(j);
if(fileContent.getSeqCount() == seqCntArray[itr-1]){
//System.out.println(" contents -- ["+fileContent.getLineString()+"] "+fileContent.getSeqCount());
stringBuffer.append(fileContent.getLineString()+"\n");listFileContents.remove(fileContent);
}}
}return stringBuffer.toString();
}
public int getSeqCount(String lineString, String text){int seqCount = 0;
if(lineString != null && text != null && lineString.contains(text)){
int strLen = lineString.length();String [] textSplit = lineString.split(text);//System.out.println(" length --"+textSplit.length);if(textSplit == null){
return seqCount;}else {
seqCount = textSplit.length - 1;}
}return seqCount;
}
}class FileContent{
private int lineNumber;private int seqCount;private String lineString;
/** * Parameterized Consatructor * @param seqCount * @param lineString */public FileContent(int lineNumber, int seqCount, String
lineString) {super();this.lineNumber = lineNumber;this.seqCount = seqCount;this.lineString = lineString;
}/** * @return the seqCount */
![Page 34: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/34.jpg)
public int getSeqCount() {return seqCount;
}/** * @param seqCount the seqCount to set */public void setSeqCount(int seqCount) {
this.seqCount = seqCount;}/** * @return the lineString */public String getLineString() {
return lineString;}/** * @param lineString the lineString to set */public void setLineString(String lineString) {
this.lineString = lineString;}/** * @return the lineNumber */public int getLineNumber() {
return lineNumber;}/** * @param lineNumber the lineNumber to set */public void setLineNumber(int lineNumber) {
this.lineNumber = lineNumber;}
}
![Page 35: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/35.jpg)
OUTPUT
INPUT FILE
ACAAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGGGCCACGGCCACCGCTGCCCTGCCCCTGGAGGGTGGCCCCACCGGCCGAGACAGCGAGCATATGCAGGAAGCGGCAGGAATAAGGAAAAGCAGCCTCCTGACTTTCCTCGCTTGGTGGTTTGAGTGGACCTCCCAGGCCAGTGCCGGGCCCCTCATAGGAGAGGAAGCTCGGGAGGTGGCCAGGCGGCAGGAAGGCGCACCCCCCCAGCAATCCGCGCGCCGGGACAGAATGCCCTGCAGGAACTTCTTCTGGAAGACCTTCTCCTCCTGCAAATAAAACCTCACCCATGAATGCTCACGCAAGTTTAATTACAGACCTGAA
OUTPUT FILE
ACAAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGGGCCACGGCCACCGCTGCCCTGCCAAGCTCGGGAGGTGGCCAGGCGGCAGGAAGGCGCACCCCCCCAGCAATCCGCGCGCCGGGACAGAATGCCCCTGGAGGGTGGCCCCACCGGCCGAGACAGCGAGCATATGCAGGAAGCGGCAGGAATAAGGAAAAGCAGCCTCCTGACTTTCCTCGCTTGGTGGTTTGAGTGGACCTCCCAGGCCAGTGCCGGGCCCCTCATAGGAGAGGCTGCAGGAACTTCTTCTGGAAGACCTTCTCCTCCTGCAAATAAAACCTCACCCATGAATGCTCACGCAAGTTTAATTACAGACCTGAA
E:\User\Manikandan\Experimrnt 6>java FileOperation**************************************************** DNA sequence example by File Read/Write Operation*****************************************************DNA Sequence file is located from [E:\User\Manikandan\Experimrnt 6\file\input.txt]
-----------------------------------------------------------------------ACAAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGGGCCACGGCCACCGCTGCCCTGCCCCTGGAGGGTGGCCCCACCGGCCGAGACAGCGAGCATATGCAGGAAGCGGCAGGAATAAGGAAAAGCAGCCTCCTGACTTTCCTCGCTTGGTGGTTTGAGTGGACCTCCCAGGCCAGTGCCGGGCCCCTCATAGGAGAGGAAGCTCGGGAGGTGGCCAGGCGGCAGGAAGGCGCACCCCCCCAGCAATCCGCGCGCCGGGACAGAATGCCCTGCAGGAACTTCTTCTGGAAGACCTTCTCCTCCTGCAAATAAAACCTCACCCATGAATGCTCACGCAAGTTTAATTACAGACCTGAA-----------------------------------------------------------------------Contents are loaded to find SubSequences of 'GC' for sorting the DNA contents
DNA Sequence contents are sorted.....
Sorted contents are written into E:\User\Manikandan\Experimrnt 6\file\output.txt
E:\User\Manikandan\Experimrnt 6>
![Page 36: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/36.jpg)
AIM
To develop a simple paint-like program that can draw basic graphical primitives in different dimensions and colors. Use appropriate menu and buttons.
ALGORITHM
![Page 37: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/37.jpg)
SOURCE CODE
/** This is the abstract parent class for different shape classes, like rectangle, oval, polygon and triangle. It provides an abstract method draw().*/
import java.util.*;import java.awt.*;
public abstract class Shapes {
/**abstract method draw() @return void */ public abstract void draw(java.util.List list, Graphics g);
}//different implementations of Shape classclass RectangleShape extends Shapes{ Point sPoint = null; Point ePoint = null; public void draw(java.util.List list, Graphics g) { Iterator it = list.iterator(); //if the list does not contain the required two points, return. if(list.size()<2) { return; } sPoint = (Point)it.next(); ePoint = (Point)it.next(); if(sPoint == null || ePoint == null) { return; } else { g.fillRect((int)sPoint.getX(), (int)sPoint.getY(), (int)(ePoint.getX()-sPoint.getX()), (int)(ePoint.getY()-sPoint.getY())); }//end of if list.clear(); }//end of draw for rectangle}//rectangle
class OvalShape extends Shapes{ Point sPoint = null; Point ePoint = null; public void draw(java.util.List list, Graphics g)
![Page 38: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/38.jpg)
{ Iterator it = list.iterator(); //if the list does not contain the required two points, return. if(list.size()<2) { return; } sPoint = (Point)it.next(); ePoint = (Point)it.next(); if(sPoint == null || ePoint == null) { return; } else { g.fillOval((int)sPoint.getX(), (int)sPoint.getY(), (int)(ePoint.getX()-sPoint.getX()), (int)(ePoint.getY()-sPoint.getY())); }//end of if list.clear(); }//end of draw for Oval}//OvalShapeclass TriangleShape extends Shapes{ public void draw(java.util.List list, Graphics g) { Point point = null; Iterator it = list.iterator(); //if the list does not contain the required two points, return. if(list.size()<3) { return; } Polygon p = new Polygon(); for(int i = 0; i < 3; i++) { point = (Point)it.next(); p.addPoint((int)point.getX(), (int)point.getY()); }
g.fillPolygon(p); list.clear(); }//end of draw for Triangle}//Triangleclass PolygonShape extends Shapes{ public void draw(java.util.List list, Graphics g) { Point point = null; Iterator it = list.iterator(); //if the list does not contain the required two points, return. if(list.size()<3) { return; } Polygon p = new Polygon(); for(;it.hasNext();) {
![Page 39: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/39.jpg)
point = (Point)it.next(); p.addPoint((int)point.getX(), (int)point.getY()); } g.fillPolygon(p); list.clear(); }//end of draw for Polygon}//Polygon
import java.awt.Color;import java.awt.Dimension;import java.awt.Frame;import java.awt.Graphics;import java.awt.Insets;import java.awt.Menu;import java.awt.MenuBar;import java.awt.MenuItem;import java.awt.MenuShortcut;import java.awt.Panel;import java.awt.Point;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;
import javax.swing.JOptionPane;
public class SimpleDrawingTool extends Frame{
//constants for menu shortcuts private static final int kControlA = 65; private static final int kControlD = 68; private static final int kControlC = 67; private static final int kControlR = 82; private static final int kControlP = 80; private static final int kControlT = 84; private static final int kControlX = 88;
private RectangleShape rectangle = new RectangleShape(); private OvalShape oval = new OvalShape(); private PolygonShape polygon = new PolygonShape(); private TriangleShape triangle = new TriangleShape();
private DrawingPanel panel;
public SimpleDrawingTool() { //set frame's title super("Simple Drawing Tool"); //add menu addMenu(); //add drawing panel addPanel();
![Page 40: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/40.jpg)
//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() { //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 WindowHandler()); shape.add(new MenuItem("Circle", new MenuShortcut(kControlC))).addActionListener(new WindowHandler()); shape.add(new MenuItem("Triangle", new MenuShortcut(kControlT))).addActionListener(new WindowHandler()); shape.add(new MenuItem("Polygon", new MenuShortcut(kControlP))).addActionListener(new WindowHandler()); shape.add(new MenuItem("Draw Polygon", new MenuShortcut(kControlD))).addActionListener(new 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
![Page 41: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/41.jpg)
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 { 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); }
![Page 42: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/42.jpg)
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++); getMenuBar().getShortcutMenuItem(new MenuShortcut(kControlP)).setEnabled(false); panel.repaint(); } else if(e.getActionCommand().equalsIgnoreCase("About")) { JOptionPane.showMessageDialog(null, "This small paint-like program.", "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)
![Page 43: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/43.jpg)
{ 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) { 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
![Page 44: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/44.jpg)
OUTPUT
![Page 45: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/45.jpg)
![Page 46: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/46.jpg)
AIM
To develop a scientific calculator using even-driven programming paradigm of Java.
ALGORITHM
![Page 47: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/47.jpg)
SOURCE CODE
import java.awt.BorderLayout;import java.awt.Color;import java.awt.Container;import java.awt.FlowLayout;import java.awt.Font;import java.awt.GridLayout;import java.awt.Window;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;
import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JPanel;import javax.swing.JTextArea;import javax.swing.KeyStroke;
![Page 48: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/48.jpg)
public class Calculator extends JFrame implements ActionListener {
// Variablesfinal int MAX_INPUT_LENGTH = 20;final int INPUT_MODE = 0;final int RESULT_MODE = 1;final int ERROR_MODE = 2;int displayMode;
boolean clearOnNextDigit, percent;double lastNumber;String lastOperator;
private JMenu jmenuFile, jmenuHelp;private JMenuItem jmenuitemExit, jmenuitemAbout;
private JLabel jlbOutput;private JButton jbnButtons[];private JPanel jplMaster, jplBackSpace, jplControl;
/* * Font(String name, int style, int size)
Creates a new Font from the specified name, style and point size. */
Font f12 = new Font("Times New Roman", 0, 12);Font f121 = new Font("Times New Roman", 1, 12);
// Constructor public Calculator() {
/* Set Up the JMenuBar. * Have Provided All JMenu's with Mnemonics * Have Provided some JMenuItem components with Keyboard
Accelerators */
jmenuFile = new JMenu("File");jmenuFile.setFont(f121);jmenuFile.setMnemonic(KeyEvent.VK_F);
jmenuitemExit = new JMenuItem("Exit");jmenuitemExit.setFont(f12);
jmenuitemExit.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_X, ActionEvent.CTRL_MASK));
jmenuFile.add(jmenuitemExit);
jmenuHelp = new JMenu("Help");jmenuHelp.setFont(f121);jmenuHelp.setMnemonic(KeyEvent.VK_H);
jmenuitemAbout = new JMenuItem("About Calculator");jmenuitemAbout.setFont(f12);jmenuHelp.add(jmenuitemAbout);
![Page 49: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/49.jpg)
JMenuBar mb = new JMenuBar();mb.add(jmenuFile);mb.add(jmenuHelp);setJMenuBar(mb);
//Set frame layout manager
setBackground(Color.gray);
jplMaster = new JPanel();
jlbOutput = new JLabel("0");jlbOutput.setHorizontalTextPosition(JLabel.RIGHT);jlbOutput.setBackground(Color.WHITE);jlbOutput.setOpaque(true);
// Add components to framegetContentPane().add(jlbOutput, BorderLayout.NORTH);
jbnButtons = new JButton[23];// GridLayout(int rows, int cols, int hgap, int vgap)
JPanel jplButtons = new JPanel(); // container for Jbuttons
// Create numeric Jbuttonsfor (int i=0; i<=9; i++){
// set each Jbutton label to the value of indexjbnButtons[i] = new JButton(String.valueOf(i));
}
// Create operator JbuttonsjbnButtons[10] = new JButton("+/-");jbnButtons[11] = new JButton(".");jbnButtons[12] = new JButton("=");jbnButtons[13] = new JButton("/");jbnButtons[14] = new JButton("*");jbnButtons[15] = new JButton("-");jbnButtons[16] = new JButton("+");jbnButtons[17] = new JButton("sqrt");jbnButtons[18] = new JButton("1/x");jbnButtons[19] = new JButton("%");
jplBackSpace = new JPanel();jplBackSpace.setLayout(new GridLayout(1, 1, 2, 2));
jbnButtons[20] = new JButton("Backspace");jplBackSpace.add(jbnButtons[20]);
jplControl = new JPanel();jplControl.setLayout(new GridLayout(1, 2, 2 ,2));
jbnButtons[21] = new JButton(" CE ");jbnButtons[22] = new JButton("C");
jplControl.add(jbnButtons[21]);jplControl.add(jbnButtons[22]);
![Page 50: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/50.jpg)
// Setting all Numbered JButton's to Blue. The rest to Redfor (int i=0; i<jbnButtons.length; i++) {
jbnButtons[i].setFont(f12);
if (i<10)jbnButtons[i].setForeground(Color.blue);
elsejbnButtons[i].setForeground(Color.red);
}
// Set panel layout manager for a 4 by 5 gridjplButtons.setLayout(new GridLayout(4, 5, 2, 2));
//Add buttons to keypad panel starting at top left// First rowfor(int i=7; i<=9; i++) {
jplButtons.add(jbnButtons[i]);}
// add button / and sqrtjplButtons.add(jbnButtons[13]);jplButtons.add(jbnButtons[17]);
// Second rowfor(int i=4; i<=6; i++){
jplButtons.add(jbnButtons[i]);}
// add button * and x^2jplButtons.add(jbnButtons[14]);jplButtons.add(jbnButtons[18]);
// Third rowfor( int i=1; i<=3; i++){
jplButtons.add(jbnButtons[i]);}
//adds button - and %jplButtons.add(jbnButtons[15]);jplButtons.add(jbnButtons[19]);
//Fourth Row// add 0, +/-, ., +, and =jplButtons.add(jbnButtons[0]);jplButtons.add(jbnButtons[10]);jplButtons.add(jbnButtons[11]);jplButtons.add(jbnButtons[16]);jplButtons.add(jbnButtons[12]);
jplMaster.setLayout(new BorderLayout());jplMaster.add(jplBackSpace, BorderLayout.WEST);jplMaster.add(jplControl, BorderLayout.EAST);jplMaster.add(jplButtons, BorderLayout.SOUTH);
![Page 51: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/51.jpg)
// Add components to framegetContentPane().add(jplMaster, BorderLayout.SOUTH);requestFocus();
//activate ActionListenerfor (int i=0; i<jbnButtons.length; i++){
jbnButtons[i].addActionListener(this);}
jmenuitemAbout.addActionListener(this);jmenuitemExit.addActionListener(this);
clearAll();
//add WindowListener for closing frame and ending programaddWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e){
System.exit(0);}
});
} //End of Contructor Calculator
// Perform actionpublic void actionPerformed(ActionEvent e){
double result = 0;
if(e.getSource() == jmenuitemAbout){ JDialog dlgAbout = new CustomABOUTDialog(this,
"About Java Swing Calculator", true);
dlgAbout.setVisible(true);}else if(e.getSource() == jmenuitemExit){
System.exit(0);}
// Search for the button pressed until end of array or key found
for (int i=0; i<jbnButtons.length; i++){
if(e.getSource() == jbnButtons[i]){
switch(i){
case 0:addDigitToDisplay(i);break;
case 1:addDigitToDisplay(i);break;
case 2:addDigitToDisplay(i);break;
![Page 52: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/52.jpg)
case 3:addDigitToDisplay(i);break;
case 4:addDigitToDisplay(i);break;
case 5:addDigitToDisplay(i);break;
case 6:addDigitToDisplay(i);break;
case 7:addDigitToDisplay(i);break;
case 8:addDigitToDisplay(i);break;
case 9:addDigitToDisplay(i);break;
case 10: // +/-processSignChange();break;
case 11: // decimal pointaddDecimalPoint();break;
case 12: // =processEquals();break;
case 13: // divideprocessOperator("/");break;
case 14: // *processOperator("*");break;
case 15: // -processOperator("-");break;
case 16: // +processOperator("+");break;
case 17: // sqrtif (displayMode != ERROR_MODE)
![Page 53: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/53.jpg)
{ try
{if
(getDisplayString().indexOf("-") == 0) displayError("Invalid
input for function!");
result = Math.sqrt(getNumberInDisplay());
displayResult(result);}
catch(Exception ex){
displayError("Invalid input for function!");
displayMode = ERROR_MODE;}
}break;
case 18: // 1/xif (displayMode != ERROR_MODE){
try{
if (getNumberInDisplay() == 0)
displayError("Cannot divide by zero!");
result = 1 / getNumberInDisplay();
displayResult(result);}
catch(Exception ex) {displayError("Cannot
divide by zero!");displayMode = ERROR_MODE;
}}break;
case 19: // %if (displayMode != ERROR_MODE){
try {result =
getNumberInDisplay() / 100;displayResult(result);
}
catch(Exception ex) {displayError("Invalid
input for function!");displayMode = ERROR_MODE;
}}
![Page 54: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/54.jpg)
break;
case 20: // backspaceif (displayMode != ERROR_MODE){
setDisplayString(getDisplayString().substring(0,
getDisplayString().length() - 1));
if (getDisplayString().length() < 1)
setDisplayString("0");}break;
case 21: // CEclearExisting();break;
case 22: // CclearAll();break;
}}
}}
void setDisplayString(String s){jlbOutput.setText(s);
}
String getDisplayString (){return jlbOutput.getText();
}
void addDigitToDisplay(int digit){if (clearOnNextDigit)
setDisplayString("");
String inputString = getDisplayString();
if (inputString.indexOf("0") == 0){inputString = inputString.substring(1);
}
if ((!inputString.equals("0") || digit > 0) && inputString.length() <
MAX_INPUT_LENGTH){setDisplayString(inputString + digit);
}
displayMode = INPUT_MODE;clearOnNextDigit = false;
}
void addDecimalPoint(){displayMode = INPUT_MODE;
![Page 55: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/55.jpg)
if (clearOnNextDigit)setDisplayString("");
String inputString = getDisplayString();
// If the input string already contains a decimal point, don't
// do anything to it.if (inputString.indexOf(".") < 0)
setDisplayString(new String(inputString + "."));}
void processSignChange(){if (displayMode == INPUT_MODE){
String input = getDisplayString();
if (input.length() > 0 && !input.equals("0")){
if (input.indexOf("-") == 0)setDisplayString(input.substring(1));
elsesetDisplayString("-" + input);
}
}
else if (displayMode == RESULT_MODE){
double numberInDisplay = getNumberInDisplay();
if (numberInDisplay != 0)displayResult(-numberInDisplay);
}}
void clearAll() {setDisplayString("0");lastOperator = "0";lastNumber = 0;displayMode = INPUT_MODE;clearOnNextDigit = true;
}
void clearExisting(){setDisplayString("0");clearOnNextDigit = true;displayMode = INPUT_MODE;
}
double getNumberInDisplay() {String input = jlbOutput.getText();return Double.parseDouble(input);
}
void processOperator(String op) {
![Page 56: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/56.jpg)
if (displayMode != ERROR_MODE){
double numberInDisplay = getNumberInDisplay();
if (!lastOperator.equals("0")){
try{
double result = processLastOperator();displayResult(result);lastNumber = result;
}
catch (DivideByZeroException e){}
}
else{
lastNumber = numberInDisplay;}
clearOnNextDigit = true;lastOperator = op;
}}
void processEquals(){double result = 0;
if (displayMode != ERROR_MODE){try{
result = processLastOperator();displayResult(result);
}
catch (DivideByZeroException e) {displayError("Cannot divide by zero!");
}
lastOperator = "0";}
}
double processLastOperator() throws DivideByZeroException {double result = 0;double numberInDisplay = getNumberInDisplay();
if (lastOperator.equals("/")){
if (numberInDisplay == 0)throw (new DivideByZeroException());
result = lastNumber / numberInDisplay;}
![Page 57: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/57.jpg)
if (lastOperator.equals("*"))result = lastNumber * numberInDisplay;
if (lastOperator.equals("-"))result = lastNumber - numberInDisplay;
if (lastOperator.equals("+"))result = lastNumber + numberInDisplay;
return result;}
void displayResult(double result){setDisplayString(Double.toString(result));lastNumber = result;displayMode = RESULT_MODE;clearOnNextDigit = true;
}
void displayError(String errorMessage){setDisplayString(errorMessage);lastNumber = 0;displayMode = ERROR_MODE;clearOnNextDigit = true;
}
public static void main(String args[]) {Calculator calci = new Calculator();Container contentPane = calci.getContentPane();
// contentPane.setLayout(new BorderLayout());calci.setTitle("Java Swing Calculator");calci.setSize(241, 217);calci.pack();calci.setLocation(400, 250);calci.setVisible(true);calci.setResizable(false);
}
} //End of Swing Calculator Class.
class DivideByZeroException extends Exception{public DivideByZeroException(){
super();}
public DivideByZeroException(String s){
super(s);}
}
class CustomABOUTDialog extends JDialog implements ActionListener {JButton jbnOk;
CustomABOUTDialog(JFrame parent, String title, boolean modal){super(parent, title, modal);setBackground(Color.black);
![Page 58: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/58.jpg)
JPanel p1 = new JPanel(new FlowLayout(FlowLayout.CENTER));
StringBuffer text = new StringBuffer();text.append("Calculator Demo Program\n\n");
JTextArea jtAreaAbout = new JTextArea(5, 21);jtAreaAbout.setText(text.toString());jtAreaAbout.setFont(new Font("Times New Roman", 1, 13));jtAreaAbout.setEditable(false);
p1.add(jtAreaAbout);p1.setBackground(Color.red);getContentPane().add(p1, BorderLayout.CENTER);
JPanel p2 = new JPanel(new FlowLayout(FlowLayout.CENTER));jbnOk = new JButton(" OK ");jbnOk.addActionListener(this);
p2.add(jbnOk);getContentPane().add(p2, BorderLayout.SOUTH);
setLocation(408, 270);setResizable(false);
addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e){
Window aboutDialog = e.getWindow();aboutDialog.dispose();
}}
);
pack();}
public void actionPerformed(ActionEvent e){
if(e.getSource() == jbnOk) {this.dispose();
}}
}
OUTPUT
![Page 59: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/59.jpg)
AIM
To develop a template for linked-list class along with its methods in Java.
ALGORITHM
![Page 60: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/60.jpg)
SOURCE CODE
public class LinkedList {ListNode current; /** * Construct the list */public LinkedList( ) {
header = new ListNode( null );}
/** * Test if the list is logically empty. * @return true if empty, false otherwise. */public boolean isEmpty( ) {
return header.next == null;}
/**
![Page 61: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/61.jpg)
* Make the list logically empty. */public void makeEmpty( ) {
header.next = null;}
/** * Return an iterator representing the header node. */public LinkedListIterator zeroth( ) {
return new LinkedListIterator( header );}
/** * Return an iterator representing the first node in the list. * This operation is valid for empty lists. */public LinkedListIterator first( ) {
return new LinkedListIterator( header.next );}
/** * Insert after p. * @param x the item to insert. * @param p the position prior to the newly inserted item. */public void insert( Object x, LinkedListIterator p ) {
if( p != null && p.current != null )p.current.next = new ListNode( x, p.current.next );
}
/** * Return iterator corresponding to the first node containing an
item. * @param x the item to search for. * @return an iterator; iterator is not valid if item is not
found. */public LinkedListIterator find( Object x ) {
ListNode itr = header.next;
while( itr != null && !itr.element.equals( x ) )itr = itr.next;
return new LinkedListIterator( itr );}
/** * Return iterator prior to the first node containing an item. * @param x the item to search for. * @return appropriate iterator if the item is found. Otherwise,
the * iterator corresponding to the last element in the list is
returned. */public LinkedListIterator findPrevious( Object x ) {
ListNode itr = header;
![Page 62: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/62.jpg)
while( itr.next != null && !itr.next.element.equals( x ) )itr = itr.next;
return new LinkedListIterator( itr );}
/** * Remove the first occurrence of an item. * @param x the item to remove. */public void remove( Object x ) {
LinkedListIterator p = findPrevious( x );
if( p.current.next != null )p.current.next = p.current.next.next; // Bypass
deleted node}
// Simple print methodpublic static void printList( LinkedList theList ) {
if( theList.isEmpty( ) )System.out.print( "Empty list" );
else {LinkedListIterator itr = theList.first( );for( ; itr.isValid( ); itr.advance( ) )
System.out.print( itr.retrieve( ) + " " );}
System.out.println( );}
private ListNode header;
// In this routine, LinkedList and LinkedListIterator are the// classes written in Section 17.2.public static int listSize( LinkedList theList ) {
LinkedListIterator itr;int size = 0;
for( itr = theList.first(); itr.isValid(); itr.advance() )size++;
return size;}
public static void main( String [ ] args ) {LinkedList theList = new LinkedList( );LinkedListIterator theItr;int i;
theItr = theList.zeroth( );printList( theList );
for( i = 0; i < 10; i++ ) {theList.insert( new Integer( i ), theItr );printList( theList );theItr.advance( );
}
![Page 63: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/63.jpg)
System.out.println( "Size was: " + listSize( theList ) );
for( i = 0; i < 10; i += 2 )theList.remove( new Integer( i ) );
for( i = 0; i < 10; i++ )if( ( i % 2 == 0 ) == ( theList.find( new Integer( i )
).isValid( ) ) )System.out.println( "Find fails!" );
System.out.println( "Finished deletions" );printList( theList );
}
}
public class LinkedListIterator {
ListNode current;
/** * Construct the list iterator * @param theNode any node in the linked list. */LinkedListIterator( ListNode theNode ) {
current = theNode;}
/** * Test if the current position is a valid position in the list. * @return true if the current position is valid. */public boolean isValid( ) {
return current != null;}
/** * Return the item stored in the current position. * @return the stored item or null if the current position * is not in the list. */public Object retrieve( ) {
return isValid( ) ? current.element : null;}
/** * Advance the current position to the next node in the list. * If the current position is null, then do nothing. */public void advance( ) {
if( isValid( ) )
![Page 64: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/64.jpg)
current = current.next;}
}
public class ListNode {
public Object element;public ListNode next;
// Constructorspublic ListNode( Object theElement ) {
this( theElement, null );}
public ListNode( Object theElement, ListNode n ) {element = theElement;next = n;
}}
OUTPUT
E:\User\Manikandan\Experiment 9>javac *.java
E:\User\Manikandan\Experiment 9>java LinkedListEmpty list00 10 1 20 1 2 30 1 2 3 40 1 2 3 4 50 1 2 3 4 5 60 1 2 3 4 5 6 70 1 2 3 4 5 6 7 80 1 2 3 4 5 6 7 8 9Size was: 10Finished deletions1 3 5 7 9
![Page 65: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/65.jpg)
E:\User\Manikandan\Experiment 9>
AIM
To design a thread-safe implementation of Queue class. Write a multi-threaded producer-consumer application that uses this Queue class.
ALGORITHM
![Page 66: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/66.jpg)
SOURCE CODE
public class Consumer extends Thread {private CubbyHole cubbyhole;private int number;
public Consumer(CubbyHole c, int number) {cubbyhole = c;this.number = number;
}
public void run() {int value = 0;for (int i = 0; i < 100; i++) {
value = cubbyhole.get();System.out.println("Consumer #" + this.number + " got:
" + value);}
}
}
![Page 67: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/67.jpg)
public class CubbyHole {
private int contents;private boolean available = false;
public synchronized int get() {while (available == false) {
try {wait();
} catch (InterruptedException e) { }}available = false;notifyAll();return contents;
}
public synchronized void put(int value) {while (available == true) {
try {wait();
} catch (InterruptedException e) { }}contents = value;available = true;notifyAll();
}
}
public class Producer extends Thread {
private CubbyHole cubbyhole;private int number;
public Producer(CubbyHole c, int number) {cubbyhole = c;this.number = number;
}
public void run() {for (int i = 0; i < 10; i++) {
cubbyhole.put(i);System.out.println("Producer #" + this.number
+ " put: " + i);try {
sleep((int)(Math.random() * 100));} catch (InterruptedException e) { }
}}
![Page 68: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/68.jpg)
}
public class ProducerConsumerTest {
public static void main(String[] args) {CubbyHole c = new CubbyHole();Producer p1 = new Producer(c, 1);Consumer c1 = new Consumer(c, 1);p1.start();c1.start();
}
}
OUTPUT
E:\User\Manikandan\Experiment 10>java ProducerConsumerTestProducer #1 put: 0Consumer #1 got: 0Producer #1 put: 1Consumer #1 got: 1Producer #1 put: 2Consumer #1 got: 2Consumer #1 got: 3Producer #1 put: 3Producer #1 put: 4Consumer #1 got: 4Producer #1 put: 5Consumer #1 got: 5Producer #1 put: 6Consumer #1 got: 6Producer #1 put: 7Consumer #1 got: 7Producer #1 put: 8Consumer #1 got: 8
![Page 69: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/69.jpg)
Producer #1 put: 9Consumer #1 got: 9
AIM
To write a multi-threaded Java program to print all numbers below 100,000 that are both prime and Fibonacci number (some examples are 2, 3, 5, 13, etc.). Design a thread that generates prime numbers below 100,000 and writes them into a pipe. Design another thread that generates fibonacci numbers and writes them to another pipe. The main thread should read both the pipes to identify numbers common to both.
ALGORITHM
![Page 70: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/70.jpg)
SOURCE CODE
import java.io.DataOutputStream;import java.io.IOException;import java.io.PipedOutputStream;
public class FibonacciNumberGenerator extends Thread {private DataOutputStream dos;
public FibonacciNumberGenerator(ThreadGroup threadGroup ,PipedOutputStream pis, String name){
super(threadGroup, name);dos = new DataOutputStream(pis);
}
@Overridepublic void run() {
try {for(int k=0; k<10000; k++){
long fibonacciNum = fib(k);
![Page 71: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/71.jpg)
if(fibonacciNum > 0L && fibonacciNum < 10000L){dos.writeLong(fibonacciNum);dos.flush();
}}
} catch (IOException e) {}
}
public int fib(int n) {int prev1=0, prev2=1;for(int i=0; i<n; i++) {
int savePrev1 = prev1;prev1 = prev2;prev2 = savePrev1 + prev2;
}return prev1;
}
}
import java.io.DataInputStream;import java.io.IOException;import java.io.PipedInputStream;import java.io.PipedOutputStream;
public class PipedStreamTester extends Thread {
DataInputStream fibonicPis;DataInputStream primePis;
public PipedStreamTester(PipedInputStream fibonicPis, PipedInputStream primePis){
this.fibonicPis = new DataInputStream(fibonicPis);this.primePis = new DataInputStream(primePis);
}
public static void main(String[] args) {try {
PipedOutputStream fibonicPos = new PipedOutputStream();
PipedInputStream fibonicPis = new PipedInputStream(fibonicPos);
PipedOutputStream primePos = new PipedOutputStream();PipedInputStream primePis = new
PipedInputStream(primePos);
ThreadGroup tg = new ThreadGroup("PipedThreads");FibonacciNumberGenerator f = new
FibonacciNumberGenerator(tg, fibonicPos, "FibonacciNumberGenerator");
![Page 72: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/72.jpg)
PrimeNumberGenerator p = new PrimeNumberGenerator(tg, primePos, "PrimeNumberGenerator");
PipedStreamTester mainTester = new PipedStreamTester(fibonicPis, primePis);
mainTester.start();f.start();p.start();
} catch (IOException e) {e.printStackTrace();
}
}
/* (non-Javadoc) * @see java.lang.Thread#run() */@Overridepublic void run() {
boolean canRun = true;boolean canGoPrimeLoop = true;boolean canGoFibonicLoop = true;Long primeNumber = -1L;Long fibonacciNumber = -1L;while(canRun){
if(fibonicPis != null && canGoFibonicLoop){
try {fibonacciNumber = fibonicPis.readLong();System.out.println(" Fibonic Number
#>"+fibonacciNumber);
} catch (IOException e) {//System.err.println("Exception occurred
while reading from fibonacci number, "+e);canGoFibonicLoop = false;
}}
if(primePis != null && canGoPrimeLoop){try {
primeNumber = primePis.readLong();System.out.println(" Prime Number
#>"+primeNumber);
} catch (IOException e) {//System.err.println("Exception occurred
while reading from prime number, "+e);canGoPrimeLoop = false;
}}
}}
![Page 73: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/73.jpg)
}
import java.io.DataOutputStream;import java.io.IOException;import java.io.PipedOutputStream;
public class PrimeNumberGenerator extends Thread {
private DataOutputStream dos;public PrimeNumberGenerator (ThreadGroup threadGroup,
PipedOutputStream pos, String name){super(threadGroup, name);dos = new DataOutputStream(pos);
}
@Overridepublic void run() {
try {int x, y, c = 0;for( x = 2; x < 10000; x++ ){
if( x % 2 != 0 || x == 2 ){for( y = 2; y <= x / 2; y++ ){
if( x % y == 0 ){break;
}}if( y > x / 2 ){
if(x < 10000){dos.writeLong(x);dos.flush();
}}
}}
} catch (IOException e) {}
}}
OUTPUT
E:\User\Manikandan\Experiment 11>javac *.java
E:\User\Manikandan\Experiment 11>java PipedStreamTester Fibonic Number #>1 Prime Number #>2 Fibonic Number #>1
![Page 74: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/74.jpg)
Prime Number #>3 Fibonic Number #>2 Prime Number #>5 Fibonic Number #>3 Prime Number #>7 Fibonic Number #>5 Prime Number #>11 Fibonic Number #>8 Prime Number #>13 Fibonic Number #>13 Prime Number #>17 Fibonic Number #>21 Prime Number #>19 Fibonic Number #>34 Prime Number #>23 Fibonic Number #>55 Prime Number #>29 Fibonic Number #>89 Prime Number #>31 Fibonic Number #>144 Prime Number #>37 Fibonic Number #>233 Prime Number #>41 Fibonic Number #>377 Prime Number #>43 Fibonic Number #>610 Prime Number #>47 Fibonic Number #>987 Prime Number #>53 Fibonic Number #>1597 Prime Number #>59 Fibonic Number #>2584 Prime Number #>61 Fibonic Number #>4181 Prime Number #>67 Fibonic Number #>6765 Prime Number #>71 Prime Number #>73 Prime Number #>79 Prime Number #>83 Prime Number #>89 Prime Number #>97 Prime Number #>101 Prime Number #>103 Prime Number #>107 Prime Number #>109 Prime Number #>113 Prime Number #>127 Prime Number #>131 Prime Number #>137 Prime Number #>139 Prime Number #>149 Prime Number #>151 Prime Number #>157 Prime Number #>163
![Page 75: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/75.jpg)
Prime Number #>167 Prime Number #>173 Prime Number #>179 Prime Number #>181 Prime Number #>191 Prime Number #>193 Prime Number #>197 Prime Number #>199 Prime Number #>211 Prime Number #>223 Prime Number #>227 Prime Number #>229 Prime Number #>233 Prime Number #>239 Prime Number #>241 Prime Number #>251 Prime Number #>257 Prime Number #>263 Prime Number #>269 Prime Number #>271 Prime Number #>277 Prime Number #>281 Prime Number #>283 Prime Number #>293 Prime Number #>307 Prime Number #>311 Prime Number #>313 Prime Number #>317 Prime Number #>331 Prime Number #>337
AIM
To develop a multi-threaded GUI application of your choice.
ALGORITHM
![Page 76: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/76.jpg)
SOURCE CODE
import org.eclipse.swt.SWT;import org.eclipse.swt.events.SelectionEvent;import org.eclipse.swt.events.SelectionListener;import org.eclipse.swt.graphics.Rectangle;import org.eclipse.swt.widgets.Button;import org.eclipse.swt.widgets.Display;import org.eclipse.swt.widgets.Shell;
/** * Illustrates multithread UI programming issues. */public class PICalculator { Display display = new Display(); Shell shell = new Shell(display); Button buttonThread = new Button(shell, SWT.PUSH); Button buttonAsyncExec = new Button(shell, SWT.PUSH);
public PICalculator(boolean asyncExecEnabled) {
![Page 77: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/77.jpg)
final boolean async = asyncExecEnabled;
shell.setText("PI Calculator"); shell.setSize(400, 80);
Rectangle clientArea = shell.getClientArea();
buttonThread.setText( "Click here to calculate PI [Non-UI thread UI Update]"); buttonThread.setBounds( clientArea.x, clientArea.y, clientArea.width, clientArea.height / 2); buttonThread.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { buttonThread.setText("Calculation in progress ..."); getTask(buttonThread).start(); } }); buttonAsyncExec.setText("Click here to calculate PI [asynExec method UI Update]"); buttonAsyncExec.setBounds( clientArea.x, clientArea.y + clientArea.height / 2, clientArea.width, clientArea.height / 2); buttonAsyncExec.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { } public void widgetSelected(SelectionEvent e) { buttonAsyncExec.setText("Calculation in progress ..."); getTask2(buttonAsyncExec).start(); } }); shell.open();
while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } }
display.dispose(); }
public static void main(String[] args) { // new CalculatePI(false); new PICalculator(true); }
public Thread getTask(Button button) { final Button theButton = button; return new Thread() { public void run() {
![Page 78: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/78.jpg)
double pi = calculatePI(9999999); theButton.setText("PI = " + pi); // Update UI. } }; }
public Thread getTask2(Button button) { final Button theButton = button; return new Thread() {
public void run() { final double pi = calculatePI(9999999); display.asyncExec(new Runnable() { public void run() { // Update UI. theButton.setText("PI = " + pi); } }); } }; } /** * Calculate value of PI using Vieta's formula. * @param nestedLevel - * level of nested square roots in Vieta's formula. * @return value of PI */ public static double calculatePI(int nestedLevel) { double product = 1; double lastSqrtValue = 0;
for (int i = 0; i < nestedLevel; i++) { double sqrt = getNextSqrtValue(lastSqrtValue); product *= 0.5 * sqrt;
lastSqrtValue = sqrt; }
return 2 / product; }
/** * Return the square root item value. * * @param lastValue - * last square root item value. * @return */ public static double getNextSqrtValue(double lastValue) { return Math.sqrt(2 + lastValue); }}
![Page 79: Java Lab Manual](https://reader033.vdocument.in/reader033/viewer/2022061108/544f83a8b1af9f37778b48dd/html5/thumbnails/79.jpg)
OUTPUT