Professional Documents
Culture Documents
1. Aim:
To Develop a Java package with simple Stack and Queue classes using JavaDoc
coments for documentation.
Program:
Package pack1:
Stack class:
package pack1;
public class ArrayStack
{
private Object a[];
private int top; // stack top
public ArrayStack(int n) // constructor
{ a = new Object[n]; // create stack array
top = -1; // no items in the stack
}
public void push(Object item) // add an item on top of stack
{
if(top == a.length-1)
{ System.out.println("Stack is full");
return;
}
top++; // increment top
a[top] = item; // insert an item
}
public Object pop() // remove an item from top of stack
{
if( isEmpty() )
{ System.out.println("Stack is empty");
return null;
}
Object item = a[top]; // access top item
top--; // decrement top
return item;
}
public Object peek() // get top item of stack
{ if( isEmpty() ) return null;
return a[top];
}
public boolean isEmpty() // true if stack is empty
{ return que[front]; }
public boolean isEmpty() // true if the queue is empty
{ return (count == 0); }
public int size() // current number of items in the queue
{ return count; }
public void displayAll()
{
System.out.print("Queue: ");
for( int i = 0; i < maxSize; i++ )
System.out.print( que[i] + " ");
System.out.println();
}
}
Implementation:
import pack1.*;
class StackQueueDemo
{
public static void main(String[] args)
{
ArrayStack stk = new ArrayStack(4); // create stack of size 4
Object item;
stk.push('A'); // push 3 items onto stack
stk.push('B');
stk.push('C');
System.out.println("size(): "+ stk.size());
item = stk.pop(); // delete item
System.out.println(item + " is deleted");
stk.push('D'); // add three more items to the stack
stk.push('E');
stk.push('F');
System.out.println(stk.pop() + " is deleted");
stk.push('G'); // push one item
item = stk.peek(); // get top item from the stack
System.out.println(item + " is on top of stack");
/* queue holds a max of 5 items */
ArrayQueue q = new ArrayQueue(5);
Object it;
q.insert('A'); q.insert('B'); q.insert('C'); q.displayAll();
it = q.remove(); // delete item
System.out.println(it + " is deleted");
it = q.remove();
System.out.println(it + " is deleted");
q.displayAll();
3. Aim:
Design a Date class similar to the one provided in the java.util package.
4. Aim:
Develop with suitable hierarchy, classes for Point, Shape, Rectangle, Square, Circle,
Ellipse, Triangle, Polygon, etc. Design a simple test application to demonstrate
dynamic polymorphism.
Program:
class point
{
void show()
{
System.out.println("This is the Point Base class");
}
}
class shape extends point
{
void display()
{
System.out.println("Different shapes can be developed with different number of
points");
}
}
class rectangle extends shape
{
int l,b;
void getdata(int x,int y)
{
l=x;b=y;
}
void rarea()
{
System.out.println("Length:"+l);
System.out.println("Breadth:"+b);
System.out.println("Area:"+(l*b));
}
}
class square extends shape
{
int a;
void gdata(int x)
{
a=x;
}
void sarea()
{
System.out.println("Side:"+a);
System.out.println("Area:"+(a*a));
}
}
class circle extends shape
{
int r;
void get(int x)
{
r=x;
}
void carea()
{
System.out.println("Radius:"+r);
System.out.println("Area:"+(3.14*r*r));
}
}
class triangle extends shape
{
int b,h;
void tdata(int x,int y)
{
b=x;h=y;
}
void tarea()
{
System.out.println("Base:"+b);
System.out.println("Height:"+h);
System.out.println("Area:"+(0.5*b*h));
}
}
class shapetest
{
public static void main(String args[])
{
rectangle r = new rectangle();
square s = new square();
circle c = new circle();
triangle t = new triangle();
r.show();
s.display();
System.out.println("");
System.out.println("Rectangle:");
System.out.println("~~~~~~~~~~");
r.getdata(12,6);
r.rarea();
System.out.println("");
System.out.println("Square:");
System.out.println("~~~~~~~");
s.gdata(7);
s.sarea();
System.out.println("");
System.out.println("Circle:");
System.out.println("~~~~~~~");
c.get(5);
c.carea();
System.out.println("");
System.out.println("Triangle:");
System.out.println("~~~~~~~~~");
t.tdata(4,7);
t.tarea();
}
}
5. Aim:
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.
Program:
interface Stack
{
void insert(Object ob);
Object pop();
void push(int item);
Node pop1();
}
class ArrayStack implements Stack
{
private Object a[];
private int top; // stack top
public ArrayStack(int n) // constructor
{ a = new Object[n]; // create stack array
top = -1; // no items in the stack
}
public void insert(Object item) // add an item on top of stack
{
if(top == a.length-1)
{ System.out.println("Stack is full");
return;
}
top++; // increment top
a[top] = item; // insert an item
}
public Object pop() // remove an item from top of stack
{
if( isEmpty() )
{ System.out.println("Stack is empty");
return null;
}
Object item = a[top]; // access top item
top--; // decrement top
return item;
}
public Object peek() // get top item of stack
{ if( isEmpty() ) return null;
return a[top];
}
public boolean isEmpty() // true if stack is empty
{ return (top == -1); }
public int size() // returns number of items in the stack
{ return top+1; }
}
class Node
{ int data; // data item
Node next; // next node in linked-stack
Node( int d ) // constructor
{ data = d; } // next is automatically set to null
}
class LinkedStack implements Stack
{
Node top; // top refers to top-node
Node p; // p refers to current node
public void push(int item) // add item onto stack
{
p = new Node(item); // create new node
p.next = top; // new node refers to old top
top = p; // top refers to new node
}
public Node pop1() // remove a node from the stack
{
if(isEmpty())
{ System.out.println("Stack is empty");
return null;
}
Node tmp = top; // tmp saves reference to top node
top = tmp.next; // now, top refers to next node of old top
return tmp; // return the popped item
}
public Node peek1() // get top node from the stack, without deleting
{
if(isEmpty())
{ System.out.println("Stack is empty");
return null;
}
return top;
}
public void displayStack()
{
p = top; // p refers to top
System.out.print("\nContents of Stack: [ ");
while( p != null ) // start printing from top of stack to bottom of stack
{
System.out.print(p.data + " "); // print data
p = p.next; // move to next node
}
System.out.println("]");
}
public boolean isEmpty() // true if stack is empty
{ return (top == null); }
}
class StackDemo
{
public static void main(String[] args)
{
ArrayStack stk = new ArrayStack(4); // create stack of size 4
Object item;
stk.insert('A'); // push 3 items onto stack
stk.insert('B');
stk.insert('C');
System.out.println("size(): "+ stk.size());
item = stk.pop(); // delete item
Program:
//Title:
A Simple Drawing Tool
//Version:
1.0
//Copyright: Copyright (c) 2001
//Author:
Yasir Feroze Minhas
//Company:
KAPS Computing (pvt) Ltd.
//Description: This is a simple tool written using AWT for drawing basic shapes.
package graph;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
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();
//add window listener
this.addWindowListener(new WindowHandler());
//set frame size
this.setSize(400, 400);
/**
This method adds a panel to SimpleDrawingTool for drawing shapes.
*/
private void addPanel()
{
panel = new DrawingPanel();
//get size of SimpleDrawingTool frame
Dimension d = this.getSize();
//get insets of frame
Insets ins = this.insets();
//exclude insets from the size of the panel
d.height = d.height - ins.top - ins.bottom;
d.width = d.width - ins.left - ins.right;
panel.setSize(d);
panel.setLocation(ins.left, ins.top);
panel.setBackground(Color.white);
//add mouse listener. Panel itself will be handling mouse events
panel.addMouseListener(panel);
this.add(panel);
}//end of addPanel();
//Inner class to handle events
private class WindowHandler extends WindowAdapter implements ActionListener
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
public void actionPerformed(ActionEvent e)
{
//check to see if the action command is equal to exit
if(e.getActionCommand().equalsIgnoreCase("exit"))
{
System.exit(0);
}
else if(e.getActionCommand().equalsIgnoreCase("Rectangle"))
{
Menu menu = getMenuBar().getMenu(1);
for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
getMenuBar().getShortcutMenuItem(new
MenuShortcut(kControlR)).setEnabled(false);
panel.drawShape(rectangle);
}
else if(e.getActionCommand().equalsIgnoreCase("Circle"))
{
Menu menu = getMenuBar().getMenu(1);
for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
getMenuBar().getShortcutMenuItem(new
MenuShortcut(kControlC)).setEnabled(false);
panel.drawShape(oval);
}
else if(e.getActionCommand().equalsIgnoreCase("Triangle"))
{
Menu menu = getMenuBar().getMenu(1);
for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
getMenuBar().getShortcutMenuItem(new
MenuShortcut(kControlT)).setEnabled(false);
panel.drawShape(triangle);
}
else if(e.getActionCommand().equalsIgnoreCase("Polygon"))
{
Menu menu = getMenuBar().getMenu(1);
for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
getMenuBar().getShortcutMenuItem(new
MenuShortcut(kControlP)).setEnabled(false);
panel.drawShape(polygon);
}
else if(e.getActionCommand().equalsIgnoreCase("Draw Polygon"))
{
Menu menu = getMenuBar().getMenu(1);
for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
getMenuBar().getShortcutMenuItem(new
MenuShortcut(kControlP)).setEnabled(false);
panel.repaint();
}
else if(e.getActionCommand().equalsIgnoreCase("About"))
{
JOptionPane.showMessageDialog(null, "This small freeware program is written by
Yasir Feroze Minhas.", "About", JOptionPane.PLAIN_MESSAGE);
}
}//actionPerformed()
}//windowHandler - Inner Class ends here
}//SimpleDrawingTool
class DrawingPanel extends Panel implements MouseListener
{
private Point sPoint = null;
private Point ePoint = null;
/*
/*
/*
/*
("0");
("1");
("2");
("3");
("4");
("5");
("6");
("7");
("8");
*/
/*
/*
*/
*/
p5.add(num1);
p5.add(num2);
p5.add(num3);
p5.add(bSub);
p5.add(bFrac);
p6.add(num0);
p6.add(bInt);
p6.add(bDot);
p6.add(bAdd);
p6.add(equals);
p2.setLayout(new GridLayout (1, 3, 2, 2) );
p3.setLayout(new GridLayout (1, 3, 2, 2) );
p4.setLayout(new GridLayout (1, 3, 2, 2) );
p5.setLayout(new GridLayout (1, 3, 2, 2) );
p6.setLayout(new GridLayout (1, 3, 2, 2) );
f.setLayout(new GridLayout (6, 1) );
f.setResizable(false);
f.setSize(300,250);
f.add(tField);
f.add(p2);
f.add(p3);
f.add(p4);
f.add(p5);
f.add(p6);
f.setVisible(true);
f.setMenuBar(menuBar);
f.pack();
// ACTION LISTENERS
clear.addActionListener(this);
bCE.addActionListener(this);
num0.addActionListener(this);
num1.addActionListener(this);
num2.addActionListener(this);
num3.addActionListener(this);
num4.addActionListener(this);
num5.addActionListener(this);
num6.addActionListener(this);
num7.addActionListener(this);
num8.addActionListener(this);
num9.addActionListener(this);
bAdd.addActionListener(this);
bSub.addActionListener(this);
bMul.addActionListener(this);
bDiv.addActionListener(this);
bPer.addActionListener(this);
bInt.addActionListener(this);
bSqrt.addActionListener(this);
bFrac.addActionListener(this);
bDot.addActionListener(this);
equals.addActionListener(this);
backspace.addActionListener(this);
fmi1.addActionListener(this);
fmi2.addActionListener(this);
fmi3.addActionListener(this);
}
/*
/*
*/
value+=2;
tField.setText(value);
}
if(a.getSource()==num3){
value+=3;
tField.setText(value);
}
if(a.getSource()==num4){
value+=4;
tField.setText(value);
}
if(a.getSource()==num5){
value+=5;
tField.setText(value);
}
if(a.getSource()==num6){
value+=6;
tField.setText(value);
}
if(a.getSource()==num7){
value+=7;
tField.setText(value);
}
if(a.getSource()==num8){
value+=8;
tField.setText(value);
}
if(a.getSource()==num9){
value+=9;
tField.setText(value);
}
/*
/*
if (a.getSource() == bAdd){
v1 = Double.parseDouble( tField.getText() );
ctr=0;
o = '+';
value="";
tField.setText("" +value);
}
*/
*/
if (a.getSource() == bSub){
v1 = Double.parseDouble( tField.getText() );
ctr=0;
o = '-';
value="";
tField.setText("" +value);
}
if (a.getSource() == bMul){
v1 = Double.parseDouble( tField.getText() );
ctr=0;
o = 'x';
value="";
tField.setText("" +value);
}
if (a.getSource() == bDiv){
v1 = Double.parseDouble( tField.getText() );
ctr=0;
o = '/';
value="";
tField.setText("" +value);
}
if (a.getSource() == bPer){
v1 = Double.parseDouble( tField.getText() );
ctr=0;
value="";
answer = (v1/100);
tField.setText("" +answer);
}
/*
/*
*/
if(o=='+'){
ctr=0;
answer = v1 + v2;
tField.setText("" +answer);
value=""; v1=null; v2=null;
}
else if(o=='-'){
ctr=0;
answer = v1 - v2;
tField.setText("" +answer);
value=""; v1=null; v2=null;
}
else if(o=='x'){
ctr=0;
answer = v1 * v2;
tField.setText("" +answer);
value=""; v1=null; v2=null;
}
else if(o=='/'){
ctr=0;
answer = v1 / v2;
tField.setText("" +answer);
value=""; v1=null; v2=null;
}
else if(o=='%'){
ctr=0;
answer = v1 % v2;
tField.setText("" +answer);
value=""; v1=null; v2=null;
}
else{}
}
/* |-- EQUALS ACTION --| */
/*
/*
/*
|-- Clear --| */
if(a.getSource()==clear){
ctr=0;
v1=null;
*/
v2=null;
value="";
answer=0.;
tField.setText("0.");
}
if(a.getSource()==bCE){
ctr=0;
value="";
tField.setText("0.");
}
/*
|-- Point --| */
if(a.getSource() == bDot){
if(ctr==0){
value+=".";
ctr+=1;
tField.setText("" +value);
}
else{
System.out.print("");
}
}
// End of Try
/*
/*
*/
*/
A Linked List is like a chain where each link in the chain contains the address to the next
link in the chain. A class of this type might look like:
class node {
private int data;
private next refA;
public node() {}
void setData( int ) {}
int getData( int ) {}
void setNextRef( node ref ) {}
node getNextRef( ) {}
void init( ) {}
void AppendNode( int ) {}
void InsertNode( int ) {}
void DeleteNode( int ) {}
void DisplayList( int ) {}
After the above class is run and data is inserted into the linked list, the chain might look
something like the following:
HEAD
+-----------+
| reference | <-- contains the address to the start
+-----+-----+
of the linked list
|
V
+-----+-----+
+-----------+
+-----------+
|
data
| +-->|
data
| +-->|
data
|
+-----------+ |
+-----------+ |
+-----------+
| reference |--+
| reference | |
| reference |
+-----------+
+-----+-----+ |
+-----+-----+
|
|
+------------------+
|
|
|
V
|
+-----+-----+
+-----------+ |
|
data
| +-->|
data
| |
+-----------+ |
+-----------+ |
| reference |--+
| reference |--+
+-----------+
+-----------+
In an array, data is stored in contiguous memory and can be accessed by using a reference
and an index. For example,
int ar[] = new int[ 12] ;
for ( int i = 0 ; i < ar.length ; i++ )
ar[ i ] = i ;
The above code segment loads the value of i in each succeeding location of the array
named ar.
An array is different than a linked list in many ways. In an array,
By using the name of the array and an index, the data is accessed. For example,
ar[ 1 ] = 5 ;
Stores data based on the logical order of the data and not the physical order.
o In other words, a linked list gives the appearance that the data in the list is
stored in contiguous memory.
Instead of an index, all stored data records are assigned a physical address in
memory that the link list algorithm/logic uses to locate the information.
A linked list logically organizes the data, rather than by physical address.
The memory for each node in the linked list is dynamically allocated at run time.
The linked list's size can be changed at run time.
o This is good if the size required is not known at compile time.
public Linkedlist {
class level variables
// constructor
public Linkedlist() {
...
}
// constructor
public LinkedList(int n, LinkedList ln) {
...
}
public boolean Remove(int num) {
...
}
public void Add( int num ) {
...
}
public void DisplayLL(
...
}
) {
=
= menu
= menu
= menu
"
+ "
+ "
+ "
\n"
\n"
\n"
\n"
;
;
;
;
menu
menu
menu
menu
menu
menu
=
=
=
=
=
=
menu
menu
menu
menu
menu
menu
+
+
+
+
+
+
) {
\n"
\n"
\n"
\n"
\n"
\n"
;
;
;
;
;
;
// value of element
// reference to next
*/
}
/** constructor
*/
public LinkedList(int n, LinkedList ln) {
value = n;
next = ln;
}
public void Add( int num ) {
head = new LinkedList(num, head);
}
*/
/** *********************************************
* Link the previous node to the node after
* NodeRef, then delete NodeRef.
*********************************************** */
PreviousNode.next = NodeRef.next;
System.out.println("\nThe number " + num +
" sought has been found.\n") ;
break ;
}
}
/** End of if-then-else
*/
}
public static void main(String args[]) {
LinkedList pp = new LinkedList() ;
// add some entries to list
pp.Add(0);
pp.Add(9);
pp.Add(2);
pp.Add(7);
pp.Add(1);
pp.Add(10);
pp.Add(15);
pp.Add(3);
pp.Add(8);
pp.Add(4);
pp.Add(5);
pp.Add(6);
pp.Add(11);
pp.DisplayLL() ;
pp.Remove( 15 ) ;
pp.DisplayLL() ;
}
10. Aim:
Design a thread-safe implementation of Queue class. Write a multi-threaded
producer-consumer application that uses this Queue class.
Program:
Main class-
}
}
Producer classpublic class Producer implements Runnable
{
public Producer()
{
Thread producer = new Thread(this);
producer.start();
}
{
Queue<Object> queue;
while(true)
{
//add to the queue some sort of unique object
queue.enqueue(new Object());
}
}
}
Queue class//the extended Queue class is a thread safe (written in house) class
public class QueueHandler extends Queue<Object>
{
public QueueHandler(int size)
{
super(size); //All I'm thinking about now is McDonalds.
}
11. Aim:
Develop a multi-threaded GUI application of your choice.