You are on page 1of 42

IT2305 JAVA PROGRAMMING LAB

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


public int size() // returns number of items in the stack
{ return top+1; }
}
Queue class:
package pack1;
public class ArrayQueue
{ private int maxSize; // maximum queue size
private Object[] que; // que is an array
private int front;
private int rear;
private int count; // count of items in queue (queue size)
public ArrayQueue(int s) // constructor
{ maxSize = s;
que = new Object[maxSize];
front = rear = -1;
count = 0;
}
public void insert(Object item) // add item at rear of queue
{
if( count == maxSize )
{ System.out.println("Queue is Full"); return; }
if(rear == maxSize-1 || rear == -1)
{ que[0] = item;
rear = 0;
if( front == -1) front = 0;
}
else que[++rear] = item;
count++; // update queue size
}
public Object remove() // delete item from front of queue
{
if( isEmpty() )
{System.out.println("Queue is Empty"); return 0; }
Object tmp = que[front]; // save item to be deleted
que[front] = null; // make deleted items cell empty
if( front == rear )
rear = front = -1;
else if( front == maxSize-1 ) front = 0;
else front++;
count--; // less one item from the queue size
return tmp;
}
public Object peek() // peek at front of the queue

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

q.insert('D'); // insert 3 more items


q.insert('E');
q.insert('F');
q.displayAll();
it = q.remove();
System.out.println(it + " is deleted");
q.displayAll();
System.out.println("peek(): " + q.peek());
q.insert('G');
q.displayAll();
System.out.println("Queue size: " + q.size());
}
}
2. Aim :
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.
Program:
import java.util.*;
import java.io.*;
class Complex {
private double r;
private double i;
static int count=0;
Complex(double rr, double ii)
{
r = rr;
i = ii;
count++;
}
Complex()
{count++;
}
public Complex add(Complex other)
{
return add(this, other);
}
public static Complex add(Complex c1, Complex c2)
{
return new Complex(c1.r+c2.r, c1.i+c2.i);
}

public Complex subtract(Complex other)


{
return subtract(this, other);
}
public static Complex subtract(Complex c1, Complex c2)
{
return new Complex(c1.r-c2.r, c1.i-c2.i);
}
public void show()
{
System.out.println(r+"+"+i+"i");
}
public static void main(String[] args)
{
Complex c = new Complex(5, 1);
Complex d = new Complex(2, 3);
Complex e = new Complex();
Complex f = new Complex();
Complex g = new Complex();
Complex h = new Complex();
System.out.println("Number of Objects created :"+count);
System.out.print("First number:");
c.show();
System.out.print("Second number:");
d.show();
System.out.print("Sum1:");
e = c.add(d);
e.show();
System.out.print("Sum2:");
f = Complex.add(c, d);
f.show();
System.out.print("Difference1:");
g = c.subtract(d);
g.show();
System.out.print("Difference2:");
h = Complex.subtract(c, d);
h.show();
}
}

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

System.out.println(item + " is deleted");


stk.insert('D'); // add three more items to the stack
stk.insert('E');
stk.insert('F');
System.out.println(stk.pop() + " is deleted");
stk.insert('G'); // push one item
item = stk.peek(); // get top item from the stack
System.out.println(item + " is on top of stack");
LinkedStack stk1 = new LinkedStack(); // create stack object
Node item1; // item stores popped node
stk1.push(20); // add 20, 35, 40 to stack
stk1.push(35);
stk1.push(40);
stk1.displayStack(); // print contents of stack
item1 = stk1.pop1(); // remove a node from the top and print it
if( item1 != null )
{
System.out.println("Popped item: " + item1.data);
stk1.displayStack();
}
stk1.push(65); // insert 65, 70, 75
stk1.push(70);
stk1.push(75);
stk1.displayStack(); // display contents of stack
item1 = stk1.pop1(); // remove a node from the top and display it
if( item1 != null )
{
System.out.println("Popped item: " + item1.data);
stk1.displayStack();
}
//System.out.println("peek(): " + stk1.peek());// get top item
stk1.push(90); // insert 90
stk1.displayStack();
}
}
6. Aim:
Write a Java program to read a file that contains DNA sequences of arbitrary length
one per line (note that each DNA sequence is just a String). Your program should sort the
sequences in descending order with respect to the number of 'TATA' subsequences
present. Finally write the sequences in sorted order into another file.
7. Aim:
Develop a simple paint-like program that can draw basic graphical primitives in
different dimensions and colors. Use appropriate menu and buttons.

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

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

private Shapes shape = null;


private java.util.ArrayList list = new java.util.ArrayList();
//override panel paint method to draw shapes
public void paint(Graphics g)
{
g.setColor(Color.green);
shape.draw(list, g);
}
public void drawShape(Shapes shape)
{
this.shape = shape;
}
//define mouse handler
public void mouseClicked(MouseEvent e)
{
//if user wants to draw triangle, call repaint after 3 clicks
if(shape instanceof TriangleShape)
{
list.add(e.getPoint());
if(list.size() > 2)
{
repaint();
}
}
else if(shape instanceof PolygonShape)
{
list.add(e.getPoint());
}
}//mouseClicked
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e)
{
sPoint = e.getPoint();
}//mousePressed
public void mouseReleased(MouseEvent e)
{
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
8. Aim:
Develop a scientific calculator using even-driven programming paradigm of Java.
Program:
Code :
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

/*
/*

25Oct2005: Designed and programmed by jfernandez.ph */


13Nov2005: Designed and programmed by jfernandez.ph */

public class Calculator implements ActionListener{


char o;
int ctr=0;
String value="", cv="", oBtn;
Double answer, v1, v2;
Double NumberConverted;
Frame f;
Panel p1, p2, p3, p4, p5, p6;
private TextField tField;
private Menu EditMenu;

private MenuBar menuBar;


private MenuItem fmi1, fmi2, fmi3;
private Button num0, num1, num2, num3, num4, num5, num6, num7, num8,
num9;
private Button bAdd, bSub, bMul, bDiv, bPer, bSqrt, bFrac, bInt, bDot,
bCE, equals, backspace, clear;

/*
/*

25Oct2005: Designed and programmed by jfernandez.ph */


13Nov2005: Designed and programmed by jfernandez.ph
Calculator(){
f = new Frame("Calculator");
menuBar = new MenuBar();
EditMenu = new Menu ("Edit");
fmi1 = new MenuItem(" Copy ");
fmi2 = new MenuItem(" Paste ");
fmi3 = new MenuItem(" Quit ");
EditMenu.add(fmi1);
EditMenu.add(fmi2);
EditMenu.addSeparator();
EditMenu.add(fmi3);
p1 = new Panel();
p2 = new Panel();
p3 = new Panel();
p4 = new Panel();
p5 = new Panel();
p6 = new Panel();
tField = new TextField(35);
num0 = new Button
num1 = new Button
num2 = new Button
num3 = new Button
num4 = new Button
num5 = new Button
num6 = new Button
num7 = new Button
num8 = new Button

("0");
("1");
("2");
("3");
("4");
("5");
("6");
("7");
("8");

*/

num9 = new Button ("9");


bAdd = new Button ("+");
bSub = new Button ("-");
bMul = new Button ("x");
bDiv = new Button ("/");
bPer = new Button ("%");
bSqrt = new Button ("sqrt");
bFrac = new Button ("1/x");
bInt = new Button
("+/-");
bDot = new Button (".");
bCE = new Button
("CE");
equals = new Button ("=");
backspace = new Button
("Backspace");
clear = new Button ("C");
}

/*
/*

25Oct2005: Designed and programmed by jfernandez.ph


13Nov2005: Designed and programmed by jfernandez.ph

public void launchFrame(){


tField.setText("0.");
tField.setEnabled(false);
menuBar.add(EditMenu);
p2.add(backspace);
p2.add(bCE);
p2.add(clear);
p3.add(num7);
p3.add(num8);
p3.add(num9);
p3.add(bDiv);
p3.add(bSqrt);
p4.add(num4);
p4.add(num5);
p4.add(num6);
p4.add(bMul);
p4.add(bPer);

*/
*/

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

/*
/*

25Oct2005: Designed and programmed by jfernandez.ph */


13Nov2005: Designed and programmed by jfernandez.ph

/* |------------ START OF ACTION EVENTS ------------| */


public void actionPerformed(ActionEvent a){
try{
/* |-------- Handling Exceptions ---------| */
if(a.getSource()==num0){
value+=0;
tField.setText(value);
}
if(a.getSource()==num1){
value+=1;
tField.setText(value);
}
if(a.getSource()==num2){

*/

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

/*
/*

25Oct2005: Designed and programmed by jfernandez.ph


13Nov2005: Designed and programmed by jfernandez.ph

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

/*
/*

25Oct2005: Designed and programmed by jfernandez.ph */


13Nov2005: Designed and programmed by jfernandez.ph

*/

/* |-- EQUALS ACTION --| */


if(a.getSource()==equals){
value="";
v2 = Double.parseDouble(tField.getText());

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

/*
/*

25Oct2005: Designed and programmed by jfernandez.ph */


13Nov2005: Designed and programmed by jfernandez.ph

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

/* |-- Back Space --| */


if(a.getSource() == backspace){
value = value.substring(0, value.length()-1 );
tField.setText("" +value);
}

/* |-- Square Root --| */


if(a.getSource() == bSqrt){
ctr=0;
value = "";
v1 = Math.sqrt( Double.parseDouble( tField.getText() ) );
tField.setText("" +v1);
}

/* |-- Integer --| */


if(a.getSource() == bInt){
ctr=0;
NumberConverted =
( Double.parseDouble(tField.getText()) * -1 );
value = "";
tField.setText("" +NumberConverted);
}

/* |-- Reciprocal --| */


if(a.getSource() == bFrac){
ctr=0;
value = "";
Double NumberContainer = ( 1 / Double.parseDouble(
tField.getText() ) );
tField.setText("" +NumberContainer);
}
// ------------ Menu Item Actions ------------ //
if(a.getSource() == fmi1){
cv = tField.getText();
}
if(a.getSource() == fmi2){
tField.setText("" +cv);
}
if(a.getSource() == fmi3){
System.exit(0);
}
}

// End of Try

/* |-------- Attempting To Catch Runtime Errors ---------| */


catch(StringIndexOutOfBoundsException str){}
catch(NumberFormatException nfe){}
catch(NullPointerException npe){}
}

// END OF ACTION EVENTS

/*
/*

25Oct2005: Designed and programmed by jfernandez.ph


13Nov2005: Designed and programmed by jfernandez.ph

*/
*/

public static void main (String args[]){


Calculator s = new Calculator();
s.launchFrame();
}
}
9. Aim:
Develop a template for linked-list class along with its methods in Java.
Program:

What is a Linked List?


What is a Linked List? It is a self-referential class that contains a reference member and
that member contains the address to a class object of the same class type. In real life,
there are many instances where we use addresses. For example, we use addresses

To designate where we live.


To designate where mail is to be sent.
To designate our email address.

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

Figure 1: Linked list class Node

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

Figure 2: Chain of nodes

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 ;

Figure 4: Declaring, allocating and filling an array

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,

The data is stored in contiguous physical memory.


The contiguous memory is addressed using a reference to the first location.

By using the name of the array and an index, the data is accessed. For example,
ar[ 1 ] = 5 ;

The location of the array is resolved at compile time.


The array's size cannot be changed at run time.

The organization of data in an array is physical. A linked list

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.

Requirements for a Linked List


This program is intended to be an introduction to linked lists. As such, the requirements
are:
1. Write this program as an application.
2. The linked list node should be added to the linked list in a LIFO manner
o All new nodes should be added at the head of the linked list
3. Create an Add method to add new nodes to the linked list
4. Create an Remove method to delete/remove nodes from the linked list
5. Create an DisplayLL method to show the contents of the nodes
6. These functions should be displayed using a JOptionPane menu.
Linked List Options
1 - Add an integer
2 - Delete an integer from the of list
3 - Display the list
4 - Exit
Select one of the options from above

Figure 5: Linked List Options screen

A Possible Approach to Building an Application


When we look at the requirements (clues), a few items jump out at us.

1. application - a program with a main() method


2. Create an Insert method
o All new nodes should be added at the head of the linked list
This means that items will be added as though they were being
pushed on a stack
3. Create an Remove method
4. Create an DisplayLL method
o Start at the head of the linked list and walk the list until all of the node
data has been displayed
Over the years, I have seen various approaches to building an application. I will use the
following simple top-down approach of using templates. Templates allow us to solve this
problem from a top down view.
/** this is a template for an application */
public Linkedlist {
class level variables
public Linkedlist() {
...
}
public static void main( String args[] ) {
...
}
}

Figure 6: Simple top-down approach of using templates

Logic for adding nodes


We will use dynamic allocation to get the space for each node at run time. To accomplish
this, we will use the Java new operator to allocate space for the linked list object. This is
called creating an instance of the object. An example looks like:
LinkedList head = null ;
head = LinkedList(num, head);
^
^
|
|
The number to be ->+
+--- The current beginning of the
added
linked list

Figure 6: Logic for adding nodes

We will update our template so that it looks like:


/** this is a template for an application */
public Linkedlist {
class level variables
// constructor
public Linkedlist() {
...
}
// constructor
public LinkedList(int n, LinkedList ln) {
...
}
public void Add( int num ) {
...
}
public static void main( String args[] ) {
...
}
}

Figure 6: Updated template

Logic for removing nodes


To remove a node from the Linked List, we will do the following:
1. Check to see if the Linked list has entries.
o If the Linked list is empty, then there is no further processing required.
2. Check if the value we are seeking is in the first node in the Linked list.
o Delete that node by making the value of next the new head.
3. Start iterating through the Linked list until the value we are seeking is found.
o Delete that node by removing its reference from the link.
We will update our template so that it looks like:
/** this is a template for an application */

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(
...
}

) {

public static void main( String args[] ) {


...
}
}

Figure 7: Second Updated template

Logic for creating a JOptionPane menu


To create a JOptionPane menu we need to understand the JOptionPane class. The
JOptionPane class makes it easy to pop up a standard dialog box that prompts users for a
value or informs them of something. For example, the following code snippet allows the
program to request and get a number.
// read a number from user as a string
number =
JOptionPane.showInputDialog( "Enter an integer:" );

The following code allows the program to display a menu.


menu
menu
menu
menu

=
= menu
= menu
= menu

"
+ "
+ "
+ "

Linked List Options


1 - Add an integer

\n"
\n"
\n"
\n"

;
;
;
;

menu
menu
menu
menu
menu
menu

=
=
=
=
=
=

menu
menu
menu
menu
menu
menu

+
+
+
+
+
+

" 2 - Delete an integer from the of list


" 3 - Display the list
"
" 4 - Exit
"
" Select one of the options from above

ret = JOptionPane.showInputDialog( null ,


menu ,
"Linked List Menu" ,
JOptionPane.PLAIN_MESSAGE ) ;

Figure 8: JOptionPane menu

ret contains the option the user entered.


We will update our template so that it looks like:
/** this is a template for an application */
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(
...
}
public boolean
...
}

) {

checkDigit( String strVal ) {

\n"
\n"
\n"
\n"
\n"
\n"

;
;
;
;
;
;

public String showIn( String mess , String title ) {


...
}
public void menu()
...
}

public static void main( String args[] ) {


...
}
}

Figure 9: Updated template

Putting It All Together


When we put it all together we get code that looks like:
/**************************************************************
* File: LinkedList.java
*
*
***********************************************************************/
public class LinkedList {
public int value;
public LinkedList next;
private LinkedList head ;
/** constructor
*/
public LinkedList() {
/** initialize list head
head = null;

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

public void DisplayLL( ) {


LinkedList NodeRef ;
NodeRef = head;
/** list all entries */
while (NodeRef != null) {
System.out.println(NodeRef.value);
NodeRef = NodeRef.next;
}
}
/** **********************************************
* The Remove function searches for a node
* with Num as its value. The node, if found, is
* deleted from the list and from memory.
* 1. Check to see if the Linked list has entries.
*
- If the Linked list is empty, then there is no
*
further processing required.
* 2. Check if the value we are seeking is in the first
*
node in the Linked list.
*
- Delete that node by making the value of next the
*
new head.
* 3. Start iterating through the Linked list until the
*
value we are seeking is found.
*
- Delete that node by removing its reference from
*
the link.
*
************************************************ */
void Remove(int num) {
LinkedList NodeRef, PreviousNode = null;
/** If the list is empty, do nothing.
if ( !(head == null) ) {
NodeRef = head ;

*/

/** Determine if the first node is the one. */


if (NodeRef.value == num) {
head = NodeRef.next;
}
else {
/** Initialize NodeRef to head of list */
NodeRef = head;
/** *************************************
* Skip all nodes whose value member is
* not equal to num.
* *************************************** */
while (NodeRef != null ) {
if ( NodeRef.value != num ) {
PreviousNode = NodeRef;
NodeRef = NodeRef.next;
}
else {

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

public class SomeApp


{
private Consumer consumer;
private Producer producer;

public static void main (String args[])


{
consumer = new Consumer();
producer = new Producer();
}
}
Consumer classpublic class Consumer implements Runnable
{
public Consumer()
{
Thread consumer = new Thread(this);
consumer.start();
}

public void run()


{
while(true)
{
//get an object off the queue
Object object = QueueHandler.dequeue();
//do some stuff with the object
}

}
}
Producer classpublic class Producer implements Runnable
{
public Producer()
{
Thread producer = new Thread(this);
producer.start();
}

public void run()


{
while(true)
{
//add to the queue some sort of unique object
QueueHandler.enqueue(new Object());
}
}
}
Queue classpublic class QueueHandler
{
//This Queue class is a thread safe (written in house) class
public static Queue<Object> readQ = new Queue<Object>(100);

public static void enqueue(Object object)


{

//do some stuff


readQ.add(object);
}

public static Object dequeue()


{
//do some stuff
return readQ.get();
}
}
OR
Main classpublic class SomeApp
{
Queue<Object> readQ;
private Consumer consumer;
private Producer producer;

public static void main (String args[])


{
readQ = new Queue<Object>(100);
consumer = new Consumer(readQ);
producer = new Producer(readQ);
}
}
Consumer classpublic class Consumer implements Runnable

{
Queue<Object> queue;

public Consumer(Queue<Object> readQ)


{
readQ = queue;
Thread consumer = new Thread(this);
consumer.start();
}

public void run()


{
while(true)
{
//get an object off the queue
Object object = queue.dequeue();
//do some stuff with the object
}
}
}
Producer classpublic class Producer implements Runnable
{
Queue<Object> queue;

public Producer(Queue<Object> readQ)


{
readQ = queue;

Thread producer = new Thread(this);


producer.start();
}

public void run()


{

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

public void enqueue(Object object)


{
//do some stuff
readQ.add();
}

public Object dequeue()


{
//do some stuff
return readQ.get();
}
}

11. Aim:
Develop a multi-threaded GUI application of your choice.

You might also like