Professional Documents
Culture Documents
: 1
AIM:
To develop a simple program to implement the concept of stack and queues in Java.
ALGORITHM:
PROGRAM:
import java.util.Iterator;
import java.util.Stack;
sk.push("a");
sk.push("c");
sk.push("e");
sk.push("d");
Iterator it=sk.iterator();
while(it.hasNext())
{
String iValue=(String)it.next();
System.out.println("Iterator value :"+iValue);
}
System.out.println("value :"+value);
1
}
EXPECTED OUTPUT:
RESULT:
Thus a simple program to implement the concept of stack and queues in Java is
implemented and executed.
Exp. No.: 2
2
COMPLEX NUMBERS
AIM:
ALGORITHM:
PROGRAM:
import java.awt.*;
import java.awt.event.*;
4
// sample client for testing
public static void main(String[] args) {
Complex a = new Complex(5.0, 6.0);
Complex b = new Complex(-3.0, 4.0);
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("Re(a) = " + a.re());
System.out.println("Im(a) = " + a.im());
System.out.println("b + a = " + b.plus(a));
System.out.println("a - b = " + a.minus(b));
System.out.println("a * b = " + a.times(b));
System.out.println("b * a = " + b.times(a));
System.out.println("a / b = " + a.divides(b));
System.out.println("(a / b) * b = " + a.divides(b).times(b));
System.out.println("conj(a) = " + a.conjugate());
System.out.println("|a| = " + a.abs());
System.out.println("tan(a) = " + a.tan());
}
EXPECTED OUTPUT:
a = 5.0 + 6.0i
b = -3.0 + 4.0i
Re(a) = 5.0
Im(a) = 6.0
b+a = 2.0 + 10.0i
a-b = 8.0 + 2.0i
a*b = -39.0 + 2.0i
b*a = -39.0 + 2.0i
a/b = 0.36 - 1.52i
(a / b) * b = 5.0 + 6.0i
conj(a) = 5.0 - 6.0i
|a| = 7.810249675906654
tan(a) = -6.685231390246571E-6 + 1.0000103108981198i
RESULT:
Thus the program to implement complex numbers is created and executed in Java.
Exp. No.: 3
AIM:
5
To develop a java Date class similar to the one provided in the java.util package.
ALGORITHM:
PROGRAM:
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
7
prt("COMPARE DATES USING: before(), after(), equals()");
prt("=======================================================");
8
prt(" Number of milliseconds since 1/1/1970 (GMT) : " + n);
prt("=================================================================");
Date newDate;
String inputDate = "1994-02-14";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
System.out.print(" " + inputDate + " parses as ");
try {
newDate = formatter.parse(inputDate);
prt(newDate + ".");
} catch (ParseException e) {
prt("Unparseable using " + formatter + ".");
}
prt();
}
public static void main(String[] args) {
prt();
try {
doDateExample();
} catch (Exception e) {
e.printStackTrace();
}
}
}
EXPECTED OUTPUT:
Thu Jan 01 00:00:00 EST 1971
RESULT:
Thus a java Date class similar to the one provided in the java.util package is created.
Exp. No.: 4
AIM:
9
ALGORITHM:
PROGRAM:
import java.awt.*;
import java.awt.event.*;
10
RESULT:
Thus a simple java program that implements dynamic polymorphism is developed and
executed.
Exp. No.: 5
AIM:
ALGORITHM:
11
Step 1: Declare the main class.
Step 2: Create an object for the linked list class.
Step 3: Write code for performing various operations like adding and removing object.
Step 4: This class extends AbstractSequentialList and implements List, Cloneable,
Serializable.
Step 5: LinkedList class provides methods get, insert and remove an element at the
beginning and end of the list.
Step 6: Compile and run the program.
PROGRAM:
import java.util.*;
public class LinkedListDemo{
public static void main(String[] args){
LinkedList link=new LinkedList();
link.add("a");
link.add("b");
link.add(new Integer(10));
System.out.println("The contents of array is" + link);
System.out.println("The size of an linkedlist is" + link.size());
link.addFirst(new Integer(20));
System.out.println("The contents of array is" + link);
System.out.println("The size of an linkedlist is" + link.size());
link.addLast("c");
System.out.println("The contents of array is" + link);
System.out.println("The size of an linkedlist is" + link.size());
link.add(2,"j");
System.out.println("The contents of array is" + link);
System.out.println("The size of an linkedlist is" + link.size());
link.add(1,"t");
System.out.println("The contents of array is" + link);
System.out.println("The size of an linkedlist is" + link.size());
link.remove(3);
System.out.println("The contents of array is" + link);
System.out.println("The size of an linkedlist is" + link.size());
}
}
EXPECTED OUTPUT:
RESULT:
Thus a simple java program that implements arrays and linked list is created and
executed.
Exp. No.: 6
SORTING
AIM:
ALGORITHM:
PROGRAM:
EXPECTED OUTPUT:
Array Before Bubble Sort
5 90 35 45 150 3
Array After Bubble Sort
150 90 45 35 5 3
RESULT:
Thus a simple program to sort a given string in descending order is implemented in Java.
Exp. No.: 7
AIM:
ALGORITHM:
PROGRAM:
package graph;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
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);
}
/**
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();
17
private class WindowHandler extends WindowAdapter implements ActionListener
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
else if(e.getActionCommand().equalsIgnoreCase("Circle"))
{
Menu menu = getMenuBar().getMenu(1);
for(int i = 0;i <
menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
getMenuBar().getShortcutMenuItem(new
MenuShortcut(kControlC)).setEnabled(false);
panel.drawShape(oval);
}
else if(e.getActionCommand().equalsIgnoreCase("Triangle"))
{
Menu menu = getMenuBar().getMenu(1);
for(int i = 0;i <
menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
getMenuBar().getShortcutMenuItem(new
MenuShortcut(kControlT)).setEnabled(false);
panel.drawShape(triangle);
}
else if(e.getActionCommand().equalsIgnoreCase("Polygon"))
{
Menu menu = getMenuBar().getMenu(1);
for(int i = 0;i <
menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
getMenuBar().getShortcutMenuItem(new
MenuShortcut(kControlP)).setEnabled(false);
panel.drawShape(polygon);
}
else if(e.getActionCommand().equalsIgnoreCase("Draw Polygon"))
{
Menu menu = getMenuBar().getMenu(1);
for(int i = 0;i <
menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
18
getMenuBar().getShortcutMenuItem(new
MenuShortcut(kControlP)).setEnabled(false);
panel.repaint();
}
else if(e.getActionCommand().equalsIgnoreCase("About"))
{
JOptionPane.showMessageDialog(null, "This small freeware program is
written by Yasir Feroze Minhas.", "About", JOptionPane.PLAIN_MESSAGE);
}
}//actionPerformed()
19
ePoint = e.getPoint();
if(ePoint.getX() < sPoint.getX())
{
Point temp = ePoint;
ePoint = sPoint;
sPoint = temp;
}
if(ePoint.getY() < sPoint.getY())
{
int temp = (int)ePoint.getY();
ePoint.y = (int)sPoint.getY();
sPoint.y = temp;
}
if(shape instanceof RectangleShape || shape instanceof OvalShape)
{
list.clear();
list.add(sPoint);
list.add(ePoint);
repaint();
}
}//mouseReleased
}//DrawingPanel
EXPECTED OUTPUT:
20
RESULT:
Thus a simple paint application program is implemented using the menus and buttons in
Java.
Exp. No.: 8
21
SCIENTIFIC CALCULATOR
AIM:
ALGORITHM:
PROGRAM:
import java.awt.*;
import java.awt.event.*;
// class CalcFrame for creating a calcul
// ator frame and added windolistener to
// close the calculator
class CalcFrame extends Frame {
CalcFrame( String str) {
// call to superclass
super(str);
// to close the calculator(Frame)
addWindowListener(new WindowAdapter() {
public void windowClosing (WindowEvent we) {
System.exit(0);
}
});
}
}
22
// main class Calculator implemnets two interfaces ActionListener and
ItemListener
23
scientific.addItemListener(this);
// create instance of object for font me
// nu
bold = new MenuItem("Arial Bold");
bold.addActionListener(this);
regular = new MenuItem("Arial Regular");
regular.addActionListener(this);
// for about menu
author = new MenuItem("Author");
author.addActionListener(this);
// add the items in the menu
view.add(basic);
view.add(scientific);
font.add(bold);
font.add(regular);
about.add(author);
// add the menus in the menubar
mb.add(view);
mb.add(font);
mb.add(about);
// add menubar to the frame
fr.setMenuBar(mb);
// override the layout manager
fr.setLayout(null);
// set the initial numbers that is 1 to 9
24
fr.add(key[11]);
//multiply
key[12] = new Button("*");
key[12].addActionListener(this);
key[12].setBounds(120,120,BWIDTH,BHEIGHT);
key[12].setBackground(Color.yellow);
fr.add(key[12]);
//divide
key[13] = new Button("/");
key[13].addActionListener(this);
key[13].setBounds(120,150,BWIDTH,BHEIGHT);
key[13].setBackground(Color.yellow);
fr.add(key[13]);
//addition
key[14] = new Button("+");
key[14].addActionListener(this);
key[14].setBounds(120,180,BWIDTH,BHEIGHT);
key[14].setBackground(Color.yellow);
fr.add(key[14]);
//subtract
key[15] = new Button("-");
key[15].addActionListener(this);
key[15].setBounds(120,210,BWIDTH,BHEIGHT);
key[15].setBackground(Color.yellow);
fr.add(key[15]);
//reciprocal
key[16] = new Button("1/x");
key[16].addActionListener(this);
key[16].setBounds(150,120,BWIDTH,BHEIGHT);
key[16].setBackground(Color.yellow);
fr.add(key[16]);
//power
key[17] = new Button("x^n");
key[17].addActionListener(this);
key[17].setBounds(150,150,BWIDTH,BHEIGHT);
key[17].setBackground(Color.yellow);
fr.add(key[17]);
//change sign
key[18] = new Button("+/-");
key[18].addActionListener(this);
key[18].setBounds(150,180,BWIDTH,BHEIGHT);
key[18].setBackground(Color.yellow);
fr.add(key[18]);
//factorial
key[19] = new Button("x!");
key[19].addActionListener(this);
key[19].setBounds(150,210,BWIDTH,BHEIGHT);
key[19].setBackground(Color.yellow);
fr.add(key[19]);
// CA
clearAll = new Button("CA");
clearAll.addActionListener(this);
clearAll.setBounds(30, 240, BWIDTH+20, BHEIGHT);
clearAll.setBackground(Color.yellow);
fr.add(clearAll);
// CE
25
clearEntry = new Button("CE");
clearEntry.addActionListener(this);
clearEntry.setBounds(80, 240, BWIDTH+20, BHEIGHT);
clearEntry.setBackground(Color.yellow);
fr.add(clearEntry);
// round
round = new Button("Round");
round.addActionListener(this);
round.setBounds(130, 240, BWIDTH+20, BHEIGHT);
round.setBackground(Color.yellow);
fr.add(round);
// set display area
display = new TextField("0");
display.setBounds(30,90,150,20);
display.setBackground(Color.white);
// key for scientific calculator
// Sine
scientificKey[0] = new Button("Sin");
scientificKey[0].addActionListener(this);
scientificKey[0].setBounds(180, 120, BWIDTH + 10, BHEIGHT);
scientificKey[0].setVisible(false);
scientificKey[0].setBackground(Color.yellow);
fr.add(scientificKey[0]);
// cosine
scientificKey[1] = new Button("Cos");
scientificKey[1].addActionListener(this);
scientificKey[1].setBounds(180, 150, BWIDTH + 10, BHEIGHT);
scientificKey[1].setBackground(Color.yellow);
scientificKey[1].setVisible(false);
fr.add(scientificKey[1]);
// Tan
scientificKey[2] = new Button("Tan");
scientificKey[2].addActionListener(this);
scientificKey[2].setBounds(180, 180, BWIDTH + 10, BHEIGHT);
scientificKey[2].setBackground(Color.yellow);
scientificKey[2].setVisible(false);
fr.add(scientificKey[2]);
// PI
scientificKey[3] = new Button("Pi");
scientificKey[3].addActionListener(this);
scientificKey[3].setBounds(180, 210, BWIDTH + 10, BHEIGHT);
scientificKey[3].setBackground(Color.yellow);
scientificKey[3].setVisible(false);
fr.add(scientificKey[3]);
// aSine
scientificKey[4] = new Button("aSin");
scientificKey[4].addActionListener(this);
scientificKey[4].setBounds(220, 120, BWIDTH + 10, BHEIGHT);
scientificKey[4].setBackground(Color.yellow);
scientificKey[4].setVisible(false);
fr.add(scientificKey[4]);
// aCos
scientificKey[5] = new Button("aCos");
scientificKey[5].addActionListener(this);
scientificKey[5].setBounds(220, 150, BWIDTH + 10, BHEIGHT);
scientificKey[5].setBackground(Color.yellow);
26
scientificKey[5].setVisible(false);
fr.add(scientificKey[5]);
// aTan
scientificKey[6] = new Button("aTan");
scientificKey[6].addActionListener(this);
scientificKey[6].setBounds(220, 180, BWIDTH + 10, BHEIGHT);
scientificKey[6].setBackground(Color.yellow);
scientificKey[6].setVisible(false);
fr.add(scientificKey[6]);
// E
scientificKey[7] = new Button("E");
scientificKey[7].addActionListener(this);
scientificKey[7].setBounds(220, 210, BWIDTH + 10, BHEIGHT);
scientificKey[7].setBackground(Color.yellow);
scientificKey[7].setVisible(false);
fr.add(scientificKey[7]);
// to degrees
scientificKey[8] = new Button("todeg");
scientificKey[8].addActionListener(this);
scientificKey[8].setBounds(180, 240, BWIDTH + 10, BHEIGHT);
scientificKey[8].setBackground(Color.yellow);
scientificKey[8].setVisible(false);
fr.add(scientificKey[8]);
// to radians
scientificKey[9] = new Button("torad");
scientificKey[9].addActionListener(this);
scientificKey[9].setBounds(220, 240, BWIDTH + 10, BHEIGHT);
scientificKey[9].setBackground(Color.yellow);
scientificKey[9].setVisible(false);
fr.add(scientificKey[9]);
cbg = new CheckboxGroup();
degrees = new Checkbox("Degrees", cbg, true);
radians = new Checkbox("Radians", cbg, false);
degrees.addItemListener(this);
radians.addItemListener(this);
degrees.setBounds(185, 75, 3 * BWIDTH, BHEIGHT);
radians.setBounds(185, 95, 3 * BWIDTH, BHEIGHT);
degrees.setVisible(false);
radians.setVisible(false);
fr.add(degrees);
fr.add(radians);
fr.add(display);
fr.setVisible(true);
} // end of makeCalculator
27
currentNumber /=10;
}
++decimalPlaces;
display.setText(Double.toString(currentNumber));
}
else if (roundButtonPressed) {
int decPlaces = (int)buttonText.charAt(0) - (int)'0';
for (int i=0; i< decPlaces; ++i)
displayNumber *=10;
displayNumber = Math.round(displayNumber);
for (int i = 0; i < decPlaces; ++i) {
displayNumber /=10;
}
display.setText(Double.toString(displayNumber));
roundButtonPressed = false;
}
else {
currentNumber = currentNumber * 10 +
(int)buttonText.charAt(0)-(int)'0';
display.setText(Integer.toString((int)currentNumber));
}
}
// if button pressed is addition
if(buttonText == "+") {
addButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}
// if button pressed is subtract
if (buttonText == "-") {
subtractButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}
// if button pressed is divide
if (buttonText == "/") {
divideButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}
// if button pressed is multiply
if (buttonText == "*") {
multiplyButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}
// if button pressed is reciprocal
if (buttonText == "1/x") {
// call reciprocal method
display.setText(reciprocal(displayNumber));
currentNumber = 0;
decimalPointPressed = false;
28
}
// if button is pressed to change a sign
if (buttonText == "+/-") {
// call changesign meyhod to change the sign
display.setText(changeSign(displayNumber));
currentNumber = 0;
decimalPointPressed = false;
}
// factorial button
if (buttonText == "x!") {
display.setText(factorial(displayNumber));
currentNumber = 0;
decimalPointPressed = false;
}
// power button
if (buttonText == "x^n") {
powerButtonPressed = true;
initialNumber = displayNumber;
currentNumber = 0;
decimalPointPressed = false;
}
// now for scientific buttons
if (buttonText == "Sin") {
if (degrees.getState())
display.setText(Double.toString(Math.sin(Math.PI *
displayNumber/180)));
else
{ display.setText(Double.toString(Math.sin(displayNumber)));
currentNumber = 0;
decimalPointPressed = false;
}
}
if (buttonText == "Cos") {
if (degrees.getState())
display.setText(Double.toString(Math.cos(Math.PI *
displayNumber/180)));
else{ display.setText(Double.toString(Math.cos(displayNumbe
r)));
currentNumber = 0;
decimalPointPressed = false;
}
}
if (buttonText == "Tan") {
if (degrees.getState())
display.setText(Double.toString(Math.tan(Math.PI *
displayNumber/180)));
else
{ display.setText(Double.toString(Math.tan(displayNumber)));
currentNumber = 0;
decimalPointPressed = false;
}
}
if (buttonText == "aSin") {
if (degrees.getState())
29
display.setText(Double.toString(Math.asin(displayNumber)*
180/Math.PI ));
else {
display.setText(Double.toString(Math.asin(displayNumber)));
currentNumber = 0;
decimalPointPressed = false;
}
}
if (buttonText == "aCos") {
if (degrees.getState())
display.setText(Double.toString(Math.acos(displayNumber)*
180/Math.PI ));
else {
display.setText(Double.toString(Math.acos(displayNumber)));
currentNumber = 0;
decimalPointPressed = false;
}
}
if (buttonText == "aTan") {
if (degrees.getState())
display.setText(Double.toString(Math.atan(displayNumber)*
180/Math.PI ));
else {
display.setText(Double.toString(Math.atan(displayNumber)));
currentNumber = 0;
decimalPointPressed = false;
}
}
if (buttonText == "todeg")
display.setText(Double.toString(Math.toDegrees(displayNumber)));
// this will convert the numbers display
// ed to radians
if (buttonText == "torad")
display.setText(Double.toString(Math.toRadians(displayNumber)));
if (buttonText == "Pi") {
display.setText(Double.toString(Math.PI));
currentNumber =0;
decimalPointPressed = false;
}
if (buttonText == "Round")
roundButtonPressed = true;
// check if decimal point is pressed
if (buttonText == ".") {
String displayedNumber = display.getText();
boolean decimalPointFound = false;
int i;
decimalPointPressed = true;
// check for decimal point
for (i =0; i < displayedNumber.length(); ++i) {
if(displayedNumber.charAt(i) == '.') {
decimalPointFound = true;
continue;
}
}
if (!decimalPointFound)
decimalPlaces = 1;
30
}
if(buttonText == "CA"){
// set all buttons to false
resetAllButtons();
display.setText("0");
currentNumber = 0;
}
if (buttonText == "CE") {
display.setText("0");
currentNumber = 0;
decimalPointPressed = false;
}
if (buttonText == "E") {
display.setText(Double.toString(Math.E));
currentNumber = 0;
decimalPointPressed = false;
}
// the main action
if (buttonText == "=") {
currentNumber = 0;
// if add button is pressed
if(addButtonPressed)
display.setText(Double.toString(initialNumber +
displayNumber));
// if subtract button is pressed
if(subtractButtonPressed)
display.setText(Double.toString(initialNumber -
displayNumber));
// if divide button is pressed
if (divideButtonPressed) {
// check if the divisor is zero
if(displayNumber == 0) {
MessageBox mb = new MessageBox ( fr, "Error ", true,
"Cannot divide by zero.");
mb.show();
}
else
display.setText(Double.toString(initialNumber/displayNumber));
}
// if multiply button is pressed
if(multiplyButtonPressed)
display.setText(Double.toString(initialNumber *
displayNumber));
// if power button is pressed
if (powerButtonPressed)
display.setText(power(initialNumber, displayNumber));
// set all the buttons to false
resetAllButtons();
}
if (buttonText == "Arial Regular") {
for (int i =0; i < 10; ++i)
key[i].setFont(new Font("Arial", Font.PLAIN, 12));
}
if (buttonText == "Arial Bold") {
for (int i =0; i < 10; ++i)
key[i].setFont(new Font("Arial", Font.BOLD, 12));
31
}
if (buttonText == "Author") {
MessageBox mb = new MessageBox ( fr, "Calculator ver 1.0 beta
", true, "Author: Inder Mohan Singh.");
mb.show();
}
32
else {
for (int i=(theNum -1); i > 1; --i)
theNum *= i;
return Integer.toString(theNum);
}
}
public String reciprocal(double num) {
if (num ==0) {
MessageBox mb = new MessageBox(fr,"Reciprocal Error", true,
"Cannot find the reciprocal of 0");
mb.show();
}
else
num = 1/num;
return Double.toString(num);
}
public String power (double base, double index) {
return Double.toString(Math.pow(base, index));
}
public String changeSign(double num) {
return Double.toString(-num);
}
}
class MessageBox extends Dialog implements ActionListener {
Button ok;
MessageBox(Frame f, String title, boolean mode, String message) {
super(f, title, mode);
Panel centrePanel = new Panel();
Label lbl = new Label(message);
centrePanel.add(lbl);
add(centrePanel, "Center");
Panel southPanel = new Panel();
ok = new Button ("OK");
ok.addActionListener(this);
southPanel.add(ok);
add(southPanel, "South");
pack();
addWindowListener (new WindowAdapter() {
public void windowClosing (WindowEvent we) {
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae) {
dispose();
}
}
33
EXPECTED OUTPUT:
34
RESULT:
Exp. No.: 9
ALGORITHM:
PROGRAM:
import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Collections;
import java.util.Random;
public class LinkedListExample
{ public void doLinkedListExample() {
final int MAX = 10;
int counter = 0;
System.out.println("+---------------------------------------------------------
------------+");
System.out.println("| Create/Store objects in an LinkedList
container. |");
System.out.println("+---------------------------------------------------------
------------+");
System.out.println();
List listA = new LinkedList();
List listB = new LinkedList();
for (int i = 0; i < MAX; i++) {
System.out.println(" - Storing Integer(" + i + ")");
listA.add(new Integer(i));
}
System.out.println(" - Storing String(Alex)");
listA.add("Alex");
System.out.println(" - Storing String(Melody)");
listA.add("Melody");
System.out.println(" - Storing String(Jeff)");
listA.add("Jeff");
System.out.println(" - Storing String(Alex)");
listA.add("Alex");
System.out.println();
System.out.println("+---------------------------------------------------------
------------+");
36
System.out.println("| Retrieve objects in an LinkedList container
using an Iterator. |");
System.out.println("+---------------------------------------------------------
------------+");
System.out.println();
Iterator i = listA.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
System.out.println();
System.out.println("+---------------------------------------------------------
------------+");
System.out.println("| Retrieve objects in an LinkedList container
using a ListIterator. |");
System.out.println("+---------------------------------------------------------
------------+");
System.out.println();
counter = 0;
ListIterator li = listA.listIterator();
while (li.hasNext()) {
System.out.println("Element [" + counter + "] = " + li.next());
System.out.println(" - hasPrevious = " + li.hasPrevious());
System.out.println(" - hasNext = " + li.hasNext());
System.out.println(" - previousIndex = " + li.previousIndex());
System.out.println(" - nextIndex = " + li.nextIndex());
System.out.println();
counter++;
}
System.out.println();
System.out.println("+---------------------------------------------------------
------------+");
System.out.println("| Retrieve objects in an LinkedList container
using index. |");
System.out.println("+---------------------------------------------------------
------------+");
System.out.println();
for (int j=0; j < listA.size(); j++) {
System.out.println("[" + j + "] - " + listA.get(j));
}
System.out.println();
System.out.println("+---------------------------------------------------------
------------+");
System.out.println("| Search for a particular Object and return its
index location. |");
System.out.println("+---------------------------------------------------------
------------+");
System.out.println();
int locationIndex = listA.indexOf("Jeff");
System.out.println("Index location of the String \"Jeff\" is: " +
37
locationIndex);
System.out.println();
System.out.println("+---------------------------------------------------------
------------+");
System.out.println("| Search for an object and return the first and
last (highest) index. |");
System.out.println("+---------------------------------------------------------
------------+");
System.out.println();
System.out.println("First occurance search for String \"Alex\". Index
= " + listA.indexOf("Alex"));
System.out.println("Last Index search for String \"Alex\". Index
= " + listA.lastIndexOf("Alex"));
System.out.println();
System.out.println("+---------------------------------------------------------
------------+");
System.out.println("| Extract a sublist from the main list, then print
the new List. |");
System.out.println("+---------------------------------------------------------
------------+");
System.out.println();
List listSub = listA.subList(10, listA.size());
System.out.println("New Sub-List from index 10 to " + listA.size() +
": " + listSub);
System.out.println();
System.out.println("+---------------------------------------------------------
------------+");
System.out.println("| Sort the Sub-List created above.
|");
System.out.println("+---------------------------------------------------------
------------+");
System.out.println();
System.out.println("Original List : " + listSub);
Collections.sort(listSub);
System.out.println("New Sorted List : " + listSub);
System.out.println();
System.out.println();
System.out.println("+---------------------------------------------------------
------------+");
System.out.println("| Reverse the Sub-List created above.
|");
System.out.println("+---------------------------------------------------------
------------+");
System.out.println();
System.out.println("Original List : " + listSub);
Collections.reverse(listSub);
System.out.println("New Reversed List : " + listSub);
System.out.println();
38
System.out.println();
System.out.println("+---------------------------------------------------------
------------+");
System.out.println("| Check to see if the Lists are empty.
|");
System.out.println("+---------------------------------------------------------
------------+");
System.out.println();
System.out.println("Is List A empty? " + listA.isEmpty());
System.out.println("Is List B empty? " + listB.isEmpty());
System.out.println("Is Sub-List empty? " + listSub.isEmpty());
System.out.println();
System.out.println("+---------------------------------------------------------
------------+");
System.out.println("| Clone the initial List.
|");
System.out.println("| NOTE: The contents of the List are object
references, so both |");
System.out.println("| of the List's contain the same exact
object reference's. |");
System.out.println("+---------------------------------------------------------
------------+");
System.out.println();
System.out.println("List A (before) : " + listA);
System.out.println("List B (before) : " + listB);
System.out.println("Sub-List (before) : " + listSub);
System.out.println();
System.out.println("Are List's A and B equal? " +
listA.equals(listB));
System.out.println();
listB = new LinkedList(listA);
System.out.println("List A (after) : " + listA);
System.out.println("List B (after) : " + listB);
System.out.println("Sub-List (after) : " + listSub);
System.out.println();
System.out.println("Are List's A and B equal? " +
listA.equals(listB));
System.out.println();
System.out.println("+---------------------------------------------------------
------------+");
System.out.println("| Shuffle the elements around in some Random order
for List A. |");
System.out.println("+---------------------------------------------------------
------------+");
System.out.println();
System.out.println("List A (before) : " + listA);
System.out.println("List B (before) : " + listB);
System.out.println("Sub-List (before) : " + listSub);
39
System.out.println();
System.out.println("Are List's A and B equal? " +
listA.equals(listB));
System.out.println();
Collections.shuffle(listA, new Random());
System.out.println("List A (after) : " + listA);
System.out.println("List B (after) : " + listB);
System.out.println("Sub-List (after) : " + listSub);
System.out.println();
System.out.println("Are List's A and B equal? " +
listA.equals(listB));
System.out.println();
System.out.println("+---------------------------------------------------------
------------+");
System.out.println("| Convert a List to an Array.
|");
System.out.println("+---------------------------------------------------------
------------+");
System.out.println();
Object[] objArray = listA.toArray();
for (int j=0; j < objArray.length; j++) {
System.out.println("Array Element [" + j + "] = " + objArray[j]);
}
System.out.println();
System.out.println("+---------------------------------------------------------
------------+");
System.out.println("| Remove (clear) Elements from List A.
|");
System.out.println("+---------------------------------------------------------
------------+");
System.out.println();
System.out.println("List A (before) : " + listA);
System.out.println("List B (before) : " + listB);
System.out.println();
listA.clear();
System.out.println("List A (after) : " + listA);
System.out.println("List B (after) : " + listB);
System.out.println();
}
public static void main(String[] args) {
LinkedListExample listExample = new LinkedListExample();
listExample.doLinkedListExample();
}
}
40
EXPECTED OUTPUT:
+---------------------------------------------------------------------+
| Convert a List to an Array. |
+---------------------------------------------------------------------+
Array Element [0] = Melody
Array Element [1] = 4
Array Element [2] = 5
Array Element [3] = 8
Array Element [4] = Jeff
Array Element [5] = Alex
Array Element [6] = 0
Array Element [7] = 1
Array Element [8] = Alex
Array Element [9] = 3
Array Element [10] = 9
Array Element [11] = 6
Array Element [12] = 2
Array Element [13] = 7
+---------------------------------------------------------------------+
| Remove (clear) Elements from List A. |
+---------------------------------------------------------------------+
List A (before) : [Melody, 4, 5, 8, Jeff, Alex, 0, 1, Alex, 3, 9, 6, 2, 7]
List B (before) : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, Melody, Jeff, Alex, Alex]
List A (after) : []
List B (after) : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, Melody, Jeff, Alex, Alex]
41
RESULT:
Thus a simple program to sort a given string in descending order is implemented in Java.
Exp. No.: 10
AIM:
ALGORITHM:
PROGRAM:
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args) {
Godown godown = new Godown(30);
Consumer c1 = new Consumer(50, godown);
Consumer c2 = new Consumer(20, godown);
Consumer c3 = new Consumer(30, godown);
Producer p1 = new Producer(10, godown);
Producer p2 = new Producer(10, godown);
Producer p3 = new Producer(10, godown);
Producer p4 = new Producer(10, godown);
Producer p5 = new Producer(10, godown);
42
Producer p6 = new Producer(10, godown);
Producer p7 = new Producer(80, godown);
c1.start();
c2.start();
c3.start();
p1.start();
p2.start();
p3.start();
p4.start();
p5.start();
p6.start();
p7.start();
}
}
/**
* Warehouse
*/
class Godown {
public static final int max_size = 100; // Maximum inventory
public int curnum; // Current inventory
Godown() {
}
Godown(int curnum) {
this.curnum = curnum;
}
/**
* Specify the quantity of product production
*
* @param neednum
*/
public synchronized void produce(int neednum) {
// Tests whether the necessary production
while (neednum + curnum > max_size) {
System.out.println(" The number of products to be
produced " + neednum + " Over the remaining inventory " + (max_size -
curnum) + " For the time being, the production tasks cannot be performed !");
try {
// The current thread to wait for the
production
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Meet production conditions for production, this is a simple
change to the current inventory
curnum += neednum;
System.out.println(" Produced " + neednum + " Products,
warehousing capacity " + curnum);
// Wake up in the object monitor all threads waiting on
notifyAll();
}
/**
* The consumer specifies the number of products
*
43
* @param neednum
*/
public synchronized void consume(int neednum) {
// Test that you can consumption
while (curnum < neednum) {
try {
// The current thread to wait for the
production
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Matching criteria, the consumer, this is a simple change to
the current inventory
curnum -= neednum;
System.out.println(" Already consumed " + neednum + "
Products, warehousing capacity " + curnum);
// Wake up in the object monitor all threads waiting on
notifyAll();
}
}
/**
* Producer
*/
class Producer extends Thread {
private int neednum; // The production number of the
product
private Godown godown; // Warehouse
44
EXPECTED OUTPUT:
45
RESULT:
AIM:
To write a java program for generating prime and Fibnoacci numbers from 1 to 1000.
ALGORITHM:
Step 1: pick a random number and check some formula involving the witness and the
potential prime N.
Step 2: After several iterations, they declare N to be "definitely composite" or "probably
prime".
Step 3: For a given test, there may be some composite numbers that will be declared
"probably prime" no matter what witness is chosen.
Step 4: The characteristic of every field is either zero or a prime number.
Step 5: Compile and run the program
PROGRAM:
EXPECTED OUTPUT:
47
RESULT:
Thus a simple program to sort a given string in descending order is implemented in Java.
Exp. No.: 12
AIM:
ALGORITHM:
PROGRAM:
package proj4;
import java.net.*;
import java.io.*;
public class Server implements Runnable {
ServerSocket serverSocket = null;
Socket clientSocket = null;
ObjectOutputStream out = null;
ObjectInputStream in = null;
int port;
static int defaultPort = 30000;
boolean isConnected = false;
Thread thread;
DataPacket packet = null;
public Server(int _port) {
try {
serverSocket = new ServerSocket(_port);
serverSocket.setSoTimeout(1000*120); //2 minutes time out
isConnected = true;
System.out.println("server started successfully");
thread = new Thread(this);
thread.setDaemon(true);
//thread.run();
} catch (IOException e) {
System.err.print("Could not listen on port: " + port);
System.exit(1);
}
try {
System.out.println("Waiting for Client");
48
clientSocket = serverSocket.accept();
System.out.println("Client Connected");
thread.run();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
try {
out = new ObjectOutputStream(clientSocket.getOutputStream());
System.out.println("output stream created successfully");
} catch (IOException e) {
e.printStackTrace();
}
try {
in = new ObjectInputStream(clientSocket.getInputStream());
System.out.println("input stream created successfully");
} catch (IOException e) {
e.printStackTrace();
}
}
public Server() {
this(defaultPort); //server listens to port 30000 as default
}
public void run() {
System.out.println("Thread running, listening for
clients");//debugging purposes
while (isConnected) {
try {
packet = this.getData();
Thread.sleep(0);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
public DataPacket getData() {
try {
packet = (DataPacket)in.readObject();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
return packet;
}
public void sendData(DataPacket dp) {
try {
out.writeObject(dp);
} catch (IOException e) {
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void closeConnection() throws IOException {
49
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
EXPECTED OUTPUT:
RESULT:
50
Thus a multi-threaded GUI application is implemented in Java.
References:
Exp. No.: 3
http://www.idevelopment.info/data/Programming/java/date/DateExample.java
Exp. No.: 7
http://www.developer.com/net/vb/article.php/874351/A-Simple-Java-Drawing-Tool.htm
Exp. No.: 8
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=2056&lngWId=2
51