java lab manual(22!8!11)

120
DMI COLLEGE OF ENGINEERING (Affiliated to Anna University Chennai-600025) PALANCHUR, CHENNAI - 602103. DEPARTMENT OF INFORMATION TECHNOLOGY B.Tech Degree Examination IT 2305- JAVA PROGRAMMING LAB LAB MANUAL V - SEMESTER 2011-2012 1

Upload: muthu-krishnan

Post on 05-Mar-2015

1.140 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Java Lab Manual(22!8!11)

DMI COLLEGE OF ENGINEERING

(Affiliated to Anna University Chennai-600025)

PALANCHUR, CHENNAI - 602103.

DEPARTMENT OF INFORMATION TECHNOLOGY

B.Tech Degree Examination

IT 2305- JAVA PROGRAMMING LAB

LAB MANUAL

V - SEMESTER

2011-2012

1

Page 2: Java Lab Manual(22!8!11)

INDEX

EX.NO NAME OF THE EXPERIMENT PAGE NO

1 JAVA PACKAGE WITH SIMPLE STACK AND QUEUE CLASS 3

2 COMPLEX NUMBER MANIPULATION 13

3 DATE CLASS SIMILAR TO JAVA.UTIL PACKAGE 18

4 IMPLEMENTING DYNAMIC POLYMORPHISM IN JAVA 23

5 JAVA INTERFACE FOR ADT STACK 29

6 DNA FILE CREATION 37

7 DEVELOPING A SIMPLE PAINT LIKE PROGRAM USING APPLET

44

8 DEVELOPING A SCIENTIFIC CALCULATOR 55

9 DEVELOPING A TEMPLATE FOR LINKED LIST 82

10 DEVELOP A MULTI THREADED PRODUCER CONSUMER APLICATION

86

11 GENERATING PRIME NUMBERS AND FIBONACCI SERIES 91

12 MULTITHREADED GUI APPLICATION 97

2

Page 3: Java Lab Manual(22!8!11)

Ex.No:1 JAVA PACKAGE WITH SIMPLE STACK AND QUEUE CLASS

AIM:

To write program to develop a java package for the stack and queue classes.

ALGORITHM:

Stack class:

1. Start the program.

2. Create a class with the class name Stack to demonstrate the

application of the stack.

3. Create a constructor to initialize the top value of the stack.

4. Define the method push ().

5. If the top value is equal to 9, print stack is full. Otherwise push the value in to the stack.

6. Define the method pop ().

7. If the top value is less than zero, print stack underflow. Otherwise

decrement the value of the stack.

8. Create a main class with the class name teststack.

9. Create an object for the class Stack to call the methods define

inside that class.

10. Call the methods push () & pop () using the objects.

11. Stop the program.

3

Page 4: Java Lab Manual(22!8!11)

Queue class:

1. Start the program.

2. Create a class with the name queue implement to demonstrate about a application of

queue.

3. Declare a variable str as string and num as integer.

4. Create an object for a class queue implement.

5. Create a constructor to of the Linked List class. This class is used by importing

the java.util. package. This constructor is used for constructing an empty list.

6. Get the value from the command line by using a variable str.

7. Using try and catch block to handle exception using IOException.

8. Print the elements in the queue using the statement.

9. Stop the program.

4

Page 5: Java Lab Manual(22!8!11)

Stack class:

package SQ;

import java.io.*;

/**

* This class demonstrates about the application of Statck

* @author Herbert Schildt

* @version 1.6

*/

class Stack

{

int stck[]=new int[10];

int tos;

/**

* Stack constructor initializes the top of the stack.

* @param tos The value to be initialized to -1.

*/

Stack()

{

tos=-1;

}

/**

* This method push an item on to the stack.

* @param tos If the value is nine the stack is full otherwise array will incremented.

5

Page 6: Java Lab Manual(22!8!11)

*/

void push(int item)

{

if(tos==9)

System.out.println("Stack is full");

else

stck[++tos]=item;

}

/**

* This method pop an item on to the stack.

* @param tos If the value is negative the stack is undeflow otherwise array will decremented.

* @return stck[tos--] the stack array will return

*/

int pop()

{

if(tos<0)

{

System.out.println("Stack underflow");

return 0;

}

else

return stck[tos--];

}

}

6

Page 7: Java Lab Manual(22!8!11)

class TestStack

{

public static void main(String args[])

{

/**

* Two objects will be created to push and pop the items.

* @param mystack1 The object of the class stack.

* @param mystack2 The object of the class stack.

*/

Stack mystack1=new Stack();

Stack mystack2=new Stack();

for(int i=0;i<10;i++)

mystack1.push(i);

for(int i=10;i<20;i++)

mystack2.push(i);

System.out.println("Stack in mystack1:");

for(int i=0;i<10;i++)

System.out.println(mystack1.pop());

System.out.println("Stack im mystack2");

for(int i=0;i<10;i++)

System.out.println(mystack2.pop());

}

}

7

Page 8: Java Lab Manual(22!8!11)

Queue class:

package SQ;

import java.io.*;

/**

* This class demonstrates about the application of Queue

* @author Herbert Schildt

* @version 1.6

*/

import java.io.*;

import java.util.*;

public class QueueImplement{

LinkedList<Integer> list;

String str;

int num;

public static void main(String[] args){

QueueImplement q = new QueueImplement();

}

/**

* This constructor demonstrates the queue application

* @param str the value get from commandline is stored.

* @exception IOException on input error.

* @see IOException

*/

8

Page 9: Java Lab Manual(22!8!11)

public QueueImplement(){

try{

list = new LinkedList<Integer>();

InputStreamReader ir = new InputStreamReader(System.in);

BufferedReader bf = new BufferedReader(ir);

System.out.println("Enter number of elements : ");

str = bf.readLine();

if((num = Integer.parseInt(str)) == 0){

System.out.println("You have entered either zero/null.");

System.exit(0);

}

else{

System.out.println("Enter elements : ");

for(int i = 0; i < num; i++){

str = bf.readLine();

int n = Integer.parseInt(str);

list.add(n);

}

}

System.out.println("First element :" + list.removeFirst());

System.out.println("Last element :" + list.removeLast());

System.out.println("Rest elements in the list :");

while(!list.isEmpty()){

System.out.print(list.remove() + "\t");

}

9

Page 10: Java Lab Manual(22!8!11)

}

catch(IOException e){

System.out.println(e.getMessage() + " is not a legal entry.");

System.exit(0);

}

}

}

10

Page 11: Java Lab Manual(22!8!11)

OUTPUT:

Stack class:

E:\SQ>path=C:\Program Files\Java\jdk1.5.0\bin

E:\SQ>set path=.;E:\;

E:\SQ>javac TestStack.java

E:\SQ>java SQ.TestStack

Stack in mystack1:

9

8

7

6

5

4

3

2

1

0

Stack in mystack2

19

18

17

16

15

14

11

Page 12: Java Lab Manual(22!8!11)

13

12

11

10

Queue class:

E:\SQ>javac QueueImplement.java

E:\SQ>java SQ.QueueImplement

Enter number of elements :

4

Enter elements :

2

4

6

8

First element :2

Last element :8

Rest elements in the list :

4 6

Result:

Thus the Stack and queue program was compiled and executed successfuly.

12

Page 13: Java Lab Manual(22!8!11)

Ex.No:2 COMPLEX NUMBER MANIPULATION

AIM:

To write a program to perform addition, subtraction, multiplication in complex numbers using constructors.

ALGORITHM:

1: Start the program.

2: Create a class with a class name Complex Number.

3: Create a constructor with the arguments a and b with integer data type.

4: Define a method getcomplexvalue( ) to get the values of a and b.

5: Define static method named as addition, subtraction,multiplication to perform particular function defined inside the method.

6: Create an object for the class Complex Number and pass the values in the argument list.

7: Call the method by using object to get the values.

8: Print the result.

9: Stop the program.

13

Page 14: Java Lab Manual(22!8!11)

COMPLEX NUMBER MANIPULATION

public class ComplexNumber

{

private int a;

private int b;

public ComplexNumber(){

}

public ComplexNumber(int a, int b){

this.a =a;

this.b=b;

}

public String getComplexValue(){

if(this.b < 0){

return a+""+b+"i";

}

else{

return a+"+"+b+"i";

}

}

public static String addition(ComplexNumber num1, ComplexNumber num2){

int a1= num1.a+num2.a;

int b1= num1.b+num2.b;

if(b1<0){

14

Page 15: Java Lab Manual(22!8!11)

return a1+""+b1+"i";

} else {

return a1+"+"+b1+"i";

}

}

public static String substraction(ComplexNumber num1, ComplexNumber num2){

int a1= num1.a-num2.a;

int b1= num1.b-num2.b;

if(b1<0){

return a1+""+b1+"i";

} else {

return a1+"+"+b1+"i";

}

}

public static String multiplication(ComplexNumber num1, ComplexNumber num2){

int a1= num1.a*num2.a;

int b1= num1.b*num2.b;

int vi1 = num1.a * num2.b;

int vi2 = num2.a * num1.b;

int vi;

vi=vi1+vi2;

if(vi<0){

return a1-b1+""+vi+"i";

} else {

return a1-b1+"+"+vi+"i";

15

Page 16: Java Lab Manual(22!8!11)

}

}

public static void main(String args[]){

ComplexNumber com1 = new ComplexNumber(-2,-3);

ComplexNumber com2 = new ComplexNumber(-4,-5);

System.out.println(com1.getComplexValue());

System.out.println(com2.getComplexValue());

System.out.println("Addition of both Complex Numbers are :" +ComplexNumber.addition(com1,com2));

System.out.println("Substraction of both Complex Numbers are :" +ComplexNumber.substraction(com1,com2));

System.out.println("Multiplication of both Complex Numbers are :" +ComplexNumber.multiplication(com1,com2));

}

}

16

Page 17: Java Lab Manual(22!8!11)

OUTPUT:

E:\Javaexecute>javac ComplexNumber.java

E:\Javaexecute>java ComplexNumber

-2-3i

-4-5i

Addition of both Complex Numbers are :-6-8i

Substraction of both Complex Numbers are :2+2i

Multiplication of both Complex Numbers are :-7+22i

Result:

Thus the complex number program was executed and compiled successfuly.

17

Page 18: Java Lab Manual(22!8!11)

Ex.No:3 DATE CLASS SIMILAR TO JAVA.UTIL PACKAGE

AIM:

To write a java program to display the dates of before and after days for a given date.

ALGORITHM:

1. Start the program.

2. Create a class with name Date

3. Declare the variables month, day, year as private and create constructor with arguments.

4. Check the condition for exception. If the date is valid, It will proceed the program otherwise display the exception “Invalid”.

5. Use Boolean type for method to return the values as either true or false.

6. Check the values for month and values for day using if loops.

7. Check the year using if loop whether it is leap year or not.

8. Define methods isAfter() and isBefore() in program.

9. Define method compareTo() to compare the date.

10. In main() create object today and give current date as value for constructor fields

11. Call the all methods to display the dates.

18

Page 19: Java Lab Manual(22!8!11)

DATE CLASS SIMILAR TO JAVA.UTIL PACKAGE

public class Date {

private final int month;

private final int day;

private final int year;

public Date(int m, int d, int y) {

if (!isValid(m, d, y))

throw new RuntimeException("Invalid");

month = m;

day = d;

year = y;

}

private static boolean isValid(int m, int d, int y) {

int[] DAYS = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

if (m < 1 || m > 12)

return false;

if (d < 1 || d > DAYS[m])

return false;

if (m == 2 && d == 29 && !isLeapYear(y))

return false;

return true;19

Page 20: Java Lab Manual(22!8!11)

}

private static boolean isLeapYear(int y) {

if (y % 400 == 0)

return true;

if (y % 100 == 0)

return false;

return (y % 4 == 0);

}

public Date next() {

if (isValid(month, day + 1, year))

return new Date(month, day + 1, year);

else if (isValid(month + 1, 1, year))

return new Date(month + 1, 1, year);

else

return new Date(1, 1, year + 1);

}

public boolean isAfter(Date b) {

return compareTo(b) > 0;

}

public boolean isBefore(Date b) {

return compareTo(b) < 0;

}

20

Page 21: Java Lab Manual(22!8!11)

public int compareTo(Date b) {

if (year != b.year)

return year - b.year;

if (month != b.month)

return month - b.month;

return day - b.day;

}

public String toString() {

return day + "-" + month + "-" + year;

}

public static void main(String[] args) {

Date today = new Date(7, 12, 2010);

System.out.println(today);

Date nextDate = today.next();

System.out.println(nextDate);

System.out.println(today.isAfter(nextDate));

System.out.println(today.next().isAfter(today));

System.out.println(today.isBefore(nextDate));

System.out.println(nextDate.compareTo(today));

}

}

21

Page 22: Java Lab Manual(22!8!11)

Output:

20-7-2011

21-7-2011

false

true

true

1

Result:

Thus the Date class program was compiled and executed successfuly.

22

Page 23: Java Lab Manual(22!8!11)

Ex.No:4 IMPLEMENTING DYNAMIC POLYMORPHISM IN JAVA

AIM:

To write a java program for abstract class to find areas of different shapes.

ALGORITHM:

1. Start the program.

2. Create an abstract class with class name Shape.

3. Create a constructor with arguments and declare variables dim1, dim2 and PI.

4. Declare an abstract method area() inside the class.

5. Create the classes Rectangle, Triangle, Circle, and Ellipse to find the area.

6. Define abstract method area() inside the subclasses and call the constructor of class Shape using super keyword.

7. In main(), create the objects for all classes and pass values to fields of constructors.

8. Create a reference variable figuref for abstract class.

9. Using reference variable of class Shape, call the method area() of all subclasses

10. Print the areas for all shapes.

11. Stop the program.

23

Page 24: Java Lab Manual(22!8!11)

IMPLEMENTING DYNAMIC POLYMORPHISM IN JAVA

abstract class Shape

{

double dim1;

double dim2;

double PI=3.14;

Shape(double a, double b)

{

dim1 = a;

dim2 = b;

}

// area is now an abstract method

abstract double area();

}

class Rectangle extends Shape

{

Rectangle(double a, double b)

{

super(a, b);

}

// override area for rectangle

double area()

24

Page 25: Java Lab Manual(22!8!11)

{

System.out.println("Inside Area for Rectangle.");

return dim1 * dim2;

}

}

class Triangle extends Shape

{

Triangle(double a, double b)

{

super(a, b);

}

// override area for right triangle

double area()

{

System.out.println("Inside Area for Triangle.");

return dim1 * dim2 / 2;

}

}

class Circle extends Shape

{

Circle(double a, double b)

{

super(a, b);

}

25

Page 26: Java Lab Manual(22!8!11)

double area()

{

System.out.println("Inside Area for Circle.");

return PI * dim1 * dim1;

}

}

class Ellipse extends Shape

{

Ellipse(double a, double b)

{

super(a, b);

}

double area() {

System.out.println("Inside Area for Ellipse.");

return PI * dim1 * dim2;

}

}

class Square extends Shape

{

Square(double a, double b)

{

super(a, b);

}

double area() {

26

Page 27: Java Lab Manual(22!8!11)

System.out.println("Inside Area for Square.");

return dim1 * dim1;

}

}

class AbstractAreas {

public static void main(String args[]) {

// Figure f = new Figure(10, 10); // illegal now

Rectangle r = new Rectangle(9, 5);

Triangle t = new Triangle(10, 8);

Circle c=new Circle(5,5);

Ellipse e=new Ellipse(7,7);

Square s=new Square(6,6);

Shape figref; // this is OK, no object is created

figref = r;

System.out.println("Area is " + figref.area());

figref = t;

System.out.println("Area is " + figref.area());

figref = c;

System.out.println("Area is " + figref.area());

figref = e;

System.out.println("Area is " + figref.area());

figref = s;

System.out.println("Area is " + figref.area());

}

}

27

Page 28: Java Lab Manual(22!8!11)

OUTPUT:

E:\SQ>java AbstractAreas

Inside Area for Rectangle.

Area is 45.0

Inside Area for Triangle.

Area is 40.0

Inside Area for Circle.

Area is 78.5

Inside Area for Ellipse.

Area is 153.86

Inside Area for Square.

Area is 36.0

Result:

Thus the Dynamic polymorphism was compiled and executed successfuly.

28

Page 29: Java Lab Manual(22!8!11)

Ex.No:5 JAVA INTERFACE FOR ADT STACK

AIM:

To write the java program for ADT stack using interface.

ALGORITHM:

1: Start the program

2: Create an interface which consists of three methods namely PUSH, POP and DISPLAY

3: Create a class which implements the above interface to implement the concept of stack through Array

4: Define all the methods of the interface to push any element, to pop the to element and to display the elements present in the stack.

5: Create another class which implements the same interface to implement the concept of stack through linked list.

6: Repeat STEP 4 for the above said class also.

7: In the main class, get the choice from the user to choose whether array implementation or linked list implementation of the stack.

8: Call the methods appropriately according to the choices madeby the user in the previous step.

9: Repeat step 6 and step 7 until the user stops his/her execution

10: Stop the program

29

Page 30: Java Lab Manual(22!8!11)

JAVA INTERFACE FOR ADT STACK

import java.lang.*;

import java.io.*;

import java.util.*;

interface Mystack

{

int n=10;

public void pop();

public void push();

public void peek();

public void display();

}

class Stackimp implements Mystack

{

int stack[]=new int[n];

int top=-1;

public void push()

{

try{

DataInputStream dis=new DataInputStream(System.in);

if(top==(n-1))

{

System.out.println("overflow");

30

Page 31: Java Lab Manual(22!8!11)

return;

}

else

{

System.out.println("enter element");

int ele=Integer.parseInt(dis.readLine());

stack[++top]=ele;

}

}

catch(Exception e)

{

System.out.println("e");

}

}

public void pop()

{

if(top<0)

{

System.out.println("underflow");

return;

}

else

{

int popper=stack[top];

top--;

31

Page 32: Java Lab Manual(22!8!11)

System.out.println("popped element" +popper);

}

}

public void peek()

{

if(top<0)

{

System.out.println("underflow");

return;

}

else

{

int popper=stack[top];

System.out.println("popped element" +popper);

}

}

public void display()

{

if(top<0)

{

System.out.println("empty");

return;

}

else

{

32

Page 33: Java Lab Manual(22!8!11)

String str=" ";

for(int i=0;i<=top;i++)

str=str+" "+stack[i];

System.out.println("elements are"+str);

}

}

}

class Stackadt

{

public static void main(String arg[])throws IOException

{

DataInputStream dis=new DataInputStream(System.in);

Stackimp stk=new Stackimp();

int ch=0;

do{

System.out.println("enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit");

ch=Integer.parseInt(dis.readLine());

switch(ch){

case 1:stk.push();

break;

case 2:stk.pop();

break;

case 3:stk.peek();

break;

case 4:stk.display();

33

Page 34: Java Lab Manual(22!8!11)

break;

case 5:System.exit(0);

}

}while(ch<=5);

}

}

34

Page 35: Java Lab Manual(22!8!11)

OUTPUT:

E:\SQ>java Stackadt

enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit

1

enter element

4

enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit

1

enter element

5

enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit

1

enter element

7

enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit

4

elements are 4 5 7

enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit

1

enter element

8

enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit

2

35

Page 36: Java Lab Manual(22!8!11)

popped element8

enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit

4

elements are 4 5 7

enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit

3

popped element7

enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit

4

elements are 4 5 7

enter ur choice for 1.push 2.pop 3.peek 4.display 5.exit

5

Result:

Thus the Interface for ADT stack program was compiled and executed successfuly.

36

Page 37: Java Lab Manual(22!8!11)

Ex. No: 6 DNA File Creation

Aim:

To write a Java program to read a file that contains DNA sequences of arbitrary length

one per line ,sort the sequences in descending order with respect to the number of 'TATA'

subsequences present and finally write the sequences in sorted order into another file.

Algorithm:

1. Start 2. Create an input text file “DNA.txt” and add the sequence as needed.3. Read each line from the file to a string array.4. Count the number of TATA sequence in each line and store the count in another array.5. Arrange the data in the count array in descending order and also arrange the data in the

string array in parallel with the count array. 6. Write the sorted DNA sequence to the output file “File.txt”7. View the output file.8. Stop.

37

Page 38: Java Lab Manual(22!8!11)

DNA File creation:

import java.util.*;

import java.io.*;

import java.util.Arrays;

import java.util.Collections;

class FileDemo

{

public static void main(String args[])throws IOException

{

String fileLine[] = new String[6];

BufferedReader br = new BufferedReader(new FileReader("dna.txt"));

int i=0,z=0,k=0;;

int[] count =new int[6];

int[] order =new int[6];

int result=0;

String searchFor = "tata";

int len = searchFor.length();

System.out.println ("Reading data from DNA file............. ");

while ((fileLine[k]=br.readLine()) != null )

{

result=0;

if (len > 0)

38

Page 39: Java Lab Manual(22!8!11)

{

int start = fileLine[k].indexOf(searchFor);

while (start != -1)

{

result++;

start = fileLine[k].indexOf(searchFor, start+len);

count[k]=result;

z++;

}

}

if(k<5)

k++;

else

break;

}

int temp,j;

String temps;

System.out.println ("Swapping data from DNA file............. ");

for(i=0;i<(count.length-1);i++)

{

for(j=i;j<=(count.length-1);j++)

{

if(count[i]<count[j])

39

Page 40: Java Lab Manual(22!8!11)

{

temp=count[i];

count[i]=count[j];

count[j]=temp;

temps=fileLine[i];

fileLine[i]=fileLine[j];

fileLine[j]=temps;

}

}

}

System.out.println ("Writing Sorted DNA sequence to Output file................. ");

try {

BufferedWriter writer=new BufferedWriter(new FileWriter("file1.txt"));

for(i=0;i<6;i++)

{

writer.write(fileLine[i]);

writer.newLine();

}

writer.close();

System.out.println ("Writing of Sorted DNA sequence to Output file has been completed................. ");

}

catch(IOException ex)

{

40

Page 41: Java Lab Manual(22!8!11)

ex.printStackTrace();

}

}

}

41

Page 42: Java Lab Manual(22!8!11)

Input:

/*dna.txt*/

attaaattaaaaaaaattata

taaattaataaattagaattaaa

aaaaaaacatcgtaaa

tcaatatatataat

ctaaaataaac

gataaaaacaaataa

Output:

C:\Program Files\Java\jdk1.6.0\bin>javac FileDemo.java

C:\Program Files\Java\jdk1.6.0\bin>java FileDemo

Reading data from DNA file.............

Swapping data from DNA file.............

Writing Sorted DNA sequence to Output file.................

Writing of Sorted DNA sequence to Output file has been completed................

/*File.txt*/

42

Page 43: Java Lab Manual(22!8!11)

tcaatatatataat

attaaattaaaaaaaattata

aaaaaaacatcgtaaa

taaattaataaattagaattaaa

ctaaaataaac

gataaaaacaaataa

Result:

Thus the DNA sequences were read sorted and output was given to an output file.

43

Page 44: Java Lab Manual(22!8!11)

Ex.No:7 DEVELOPING A SIMPLE PAINT LIKE PROGRAM USING APPLET

Aim:

To develop a simple paint like program using applet in java.

Algorithm:

1. Import the required class and packages.

2. Create a class Drawtest for creating an applet.

3. Initialize panles and controls in the init() method.

4. Define the destroy() method to destroy the same.

5. Create an instance for draw test class and call the init(0 and start() methods in the main method.

6. Add a new frame to the applet window and resize it to 300x300.

7. Declare a method get applet infor to display the applet information.

8. Declare two constants LINES,POINTS which are going to be the modes.

9. Define the paint method and perfoem the required operations.

10. Display the result according to the mode selected.

44

Page 45: Java Lab Manual(22!8!11)

DEVELOPING A SIMPLE PAINT LIKE PROGRAM USING APPLET

import java.awt.event.*;

import java.awt.*;

import java.applet.*;

import java.util.Vector;

public class DrawTest extends Applet{

DrawPanel panel;

DrawControls controls;

public void init() {

setLayout(new BorderLayout());

panel = new DrawPanel();

controls = new DrawControls(panel);

add("Center", panel);

add("South",controls);

}

public void destroy() {

remove(panel);

remove(controls);

45

Page 46: Java Lab Manual(22!8!11)

}

public static void main(String args[]) {

Frame f = new Frame("DrawTest");

DrawTest drawTest = new DrawTest();

drawTest.init();

drawTest.start();

f.add("Center", drawTest);

f.setSize(300, 300);

f.show();

}

public String getAppletInfo() {

return "A simple drawing program.";

}

}

class DrawPanel extends Panel implements MouseListener, MouseMotionListener {

public static final int LINES = 0;

public static final int POINTS = 1;

int mode = LINES;

Vector lines = new Vector();

Vector colors = new Vector();

int x1,y1;

int x2,y2;

46

Page 47: Java Lab Manual(22!8!11)

public DrawPanel() {

setBackground(Color.white);

addMouseMotionListener(this);

addMouseListener(this);

}

public void setDrawMode(int mode) {

switch (mode) {

case LINES:

case POINTS:

this.mode = mode;

break;

default:

throw new IllegalArgumentException();

}

}

public void mouseDragged(MouseEvent e) {

e.consume();

switch (mode) {

case LINES:

x2 = e.getX();

y2 = e.getY();

break;

47

Page 48: Java Lab Manual(22!8!11)

case POINTS:

default:

colors.addElement(getForeground());

lines.addElement(new Rectangle(x1, y1, e.getX(), e.getY()));

x1 = e.getX();

y1 = e.getY();

break;

}

repaint();

}

public void mouseMoved(MouseEvent e) {

}

public void mousePressed(MouseEvent e) {

e.consume();

switch (mode) {

case LINES:

x1 = e.getX();

y1 = e.getY();

x2 = -1;

break;

case POINTS:

default:

colors.addElement(getForeground());

lines.addElement(new Rectangle(e.getX(), e.getY(), -1, -1));

48

Page 49: Java Lab Manual(22!8!11)

x1 = e.getX();

y1 = e.getY();

repaint();

break;

}

}

public void mouseReleased(MouseEvent e) {

e.consume();

switch (mode) {

case LINES:

colors.addElement(getForeground());

lines.addElement(new Rectangle(x1, y1, e.getX(), e.getY()));

x2 = -1;

break;

case POINTS:

default:

break;

}

repaint();

}

public void mouseEntered(MouseEvent e) {

}

49

Page 50: Java Lab Manual(22!8!11)

public void mouseExited(MouseEvent e) {

}

public void mouseClicked(MouseEvent e) {

}

public void paint(Graphics g) {

int np = lines.size();

/* draw the current lines */

g.setColor(getForeground());

for (int i=0; i < np; i++) {

Rectangle p = (Rectangle)lines.elementAt(i);

g.setColor((Color)colors.elementAt(i));

if (p.width != -1) {

g.drawLine(p.x, p.y, p.width, p.height);

} else {

g.drawLine(p.x, p.y, p.x, p.y);

}

}

if (mode == LINES) {

g.setColor(getForeground());

if (x2 != -1) {

g.drawLine(x1, y1, x2, y2);

}

50

Page 51: Java Lab Manual(22!8!11)

}

}

}

class DrawControls extends Panel implements ItemListener {

DrawPanel target;

public DrawControls(DrawPanel target) {

this.target = target;

setLayout(new FlowLayout());

setBackground(Color.lightGray);

target.setForeground(Color.red);

CheckboxGroup group = new CheckboxGroup();

Checkbox b;

add(b = new Checkbox(null, group, false));

b.addItemListener(this);

b.setForeground(Color.red);

add(b = new Checkbox(null, group, false));

b.addItemListener(this);

b.setForeground(Color.green);

add(b = new Checkbox(null, group, false));

b.addItemListener(this);

b.setForeground(Color.blue);

add(b = new Checkbox(null, group, false));

51

Page 52: Java Lab Manual(22!8!11)

b.addItemListener(this);

b.setForeground(Color.pink);

add(b = new Checkbox(null, group, false));

b.addItemListener(this);

b.setForeground(Color.orange);

add(b = new Checkbox(null, group, true));

b.addItemListener(this);

b.setForeground(Color.black);

target.setForeground(b.getForeground());

Choice shapes = new Choice();

shapes.addItemListener(this);

shapes.addItem("Lines");

shapes.addItem("Points");

shapes.setBackground(Color.lightGray);

add(shapes);

}

public void paint(Graphics g) {

Rectangle r = getBounds();

g.setColor(Color.lightGray);

g.draw3DRect(0, 0, r.width, r.height, false);

int n = getComponentCount();

for(int i=0; i<n; i++) {

Component comp = getComponent(i);

52

Page 53: Java Lab Manual(22!8!11)

if (comp instanceof Checkbox) {

Point loc = comp.getLocation();

Dimension d = comp.getSize();

g.setColor(comp.getForeground());

g.drawRect(loc.x-1, loc.y-1, d.width+1, d.height+1);

}

}

}

public void itemStateChanged(ItemEvent e) {

if (e.getSource() instanceof Checkbox) {

target.setForeground(((Component)e.getSource()).getForeground());

} else if (e.getSource() instanceof Choice) {

String choice = (String) e.getItem();

if (choice.equals("Lines")) {

target.setDrawMode(DrawPanel.LINES);

} else if (choice.equals("Points")) {

target.setDrawMode(DrawPanel.POINTS);

}

}

}

}

53

Page 54: Java Lab Manual(22!8!11)

OUTPUT:

Result:

Thus the Applet-Paint program was compiled and executed successfuly.

54

Page 55: Java Lab Manual(22!8!11)

.

Ex.No:8 DEVELOPING A SCIENTIFIC CALCULATOR

Aim:

To develop a scientific calculator in java.

Algorithm:

1. Import the necessary packages.

2. Create a class calculator JFrame class and ActionListener interface.

3. Create a new font using String name,int style,int size).

4. Set up the JMenu bar and add Mnemenics to them by using setMnemonic() method.

5. Set the frame layout for the applet and set the background color to gray using setBackground() method .

6. Create a container using JPanel().

7. Create numeric JButtons for operators and numbers using JButtons().

8. Set all the Numbered JButtons to blue .the rest to red usig setForeGround() method.

9. Declare the method getNumberInDisplay() to get by the calculator.

10. Use display result to display the method.

11. Declare the main function and create the instance for calculator and set the attributes setTitle(),setSize(),setResizable().

12. Stop the program.

55

Page 56: Java Lab Manual(22!8!11)

DEVELOPING A SCIENTIFIC CALCULATOR

import java.awt.event.*;

import java.awt.*;

import javax.swing.*;

public class Calculator extends JFrame implements ActionListener{

// Variables

final int MAX_INPUT_LENGTH = 20;

final int INPUT_MODE = 0;

final int RESULT_MODE = 1;

final int ERROR_MODE = 2;

int displayMode;

boolean clearOnNextDigit, percent;

double lastNumber;

String lastOperator;

private JMenu jmenuFile, jmenuHelp;

private JMenuItem jmenuitemExit, jmenuitemAbout;

private JLabel jlbOutput;

private JButton jbnButtons[];

private JPanel jplMaster, jplBackSpace, jplControl;

56

Page 57: Java Lab Manual(22!8!11)

/*

* Font(String name, int style, int size)

Creates a new Font from the specified name, style and point size.

*/

Font f12 = new Font("Times New Roman", 0, 12);

Font f121 = new Font("Times New Roman", 1, 12);

// Constructor

public Calculator()

{

/* Set Up the JMenuBar.

* Have Provided All JMenu's with Mnemonics

* Have Provided some JMenuItem components with Keyboard Accelerators

*/

jmenuFile = new JMenu("File");

jmenuFile.setFont(f121);

jmenuFile.setMnemonic(KeyEvent.VK_F);

jmenuitemExit = new JMenuItem("Exit");

jmenuitemExit.setFont(f12);

jmenuitemExit.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_X,

ActionEvent.CTRL_MASK));

57

Page 58: Java Lab Manual(22!8!11)

jmenuFile.add(jmenuitemExit);

jmenuHelp = new JMenu("Help");

jmenuHelp.setFont(f121);

jmenuHelp.setMnemonic(KeyEvent.VK_H);

jmenuitemAbout = new JMenuItem("About Calculator");

jmenuitemAbout.setFont(f12);

jmenuHelp.add(jmenuitemAbout);

JMenuBar mb = new JMenuBar();

mb.add(jmenuFile);

mb.add(jmenuHelp);

setJMenuBar(mb);

//Set frame layout manager

setBackground(Color.gray);

jplMaster = new JPanel();

jlbOutput = new JLabel("0");

jlbOutput.setHorizontalTextPosition(JLabel.RIGHT);

jlbOutput.setBackground(Color.WHITE);

jlbOutput.setOpaque(true);

58

Page 59: Java Lab Manual(22!8!11)

// Add components to frame

getContentPane().add(jlbOutput, BorderLayout.NORTH);

jbnButtons = new JButton[23];

// GridLayout(int rows, int cols, int hgap, int vgap)

JPanel jplButtons = new JPanel(); // container for Jbuttons

// Create numeric Jbuttons

for (int i=0; i<=9; i++)

{

// set each Jbutton label to the value of index

jbnButtons[i] = new JButton(String.valueOf(i));

}

// Create operator Jbuttons

jbnButtons[10] = new JButton("+/-");

jbnButtons[11] = new JButton(".");

jbnButtons[12] = new JButton("=");

jbnButtons[13] = new JButton("/");

jbnButtons[14] = new JButton("*");

jbnButtons[15] = new JButton("-");

jbnButtons[16] = new JButton("+");

jbnButtons[17] = new JButton("sqrt");

59

Page 60: Java Lab Manual(22!8!11)

jbnButtons[18] = new JButton("1/x");

jbnButtons[19] = new JButton("%");

jplBackSpace = new JPanel();

jplBackSpace.setLayout(new GridLayout(1, 1, 2, 2));

jbnButtons[20] = new JButton("Backspace");

jplBackSpace.add(jbnButtons[20]);

jplControl = new JPanel();

jplControl.setLayout(new GridLayout(1, 2, 2 ,2));

jbnButtons[21] = new JButton(" CE ");

jbnButtons[22] = new JButton("C");

jplControl.add(jbnButtons[21]);

jplControl.add(jbnButtons[22]);

// Setting all Numbered JButton's to Blue. The rest to Red

for (int i=0; i<jbnButtons.length; i++) {

jbnButtons[i].setFont(f12);

if (i<10)

jbnButtons[i].setForeground(Color.blue);

60

Page 61: Java Lab Manual(22!8!11)

else

jbnButtons[i].setForeground(Color.red);

}

// Set panel layout manager for a 4 by 5 grid

jplButtons.setLayout(new GridLayout(4, 5, 2, 2));

//Add buttons to keypad panel starting at top left

// First row

for(int i=7; i<=9; i++) {

jplButtons.add(jbnButtons[i]);

}

// add button / and sqrt

jplButtons.add(jbnButtons[13]);

jplButtons.add(jbnButtons[17]);

// Second row

for(int i=4; i<=6; i++)

{

jplButtons.add(jbnButtons[i]);

}

// add button * and x^2

jplButtons.add(jbnButtons[14]);

61

Page 62: Java Lab Manual(22!8!11)

jplButtons.add(jbnButtons[18]);

// Third row

for( int i=1; i<=3; i++)

{

jplButtons.add(jbnButtons[i]);

}

//adds button - and %

jplButtons.add(jbnButtons[15]);

jplButtons.add(jbnButtons[19]);

//Fourth Row

// add 0, +/-, ., +, and =

jplButtons.add(jbnButtons[0]);

jplButtons.add(jbnButtons[10]);

jplButtons.add(jbnButtons[11]);

jplButtons.add(jbnButtons[16]);

jplButtons.add(jbnButtons[12]);

jplMaster.setLayout(new BorderLayout());

jplMaster.add(jplBackSpace, BorderLayout.WEST);

jplMaster.add(jplControl, BorderLayout.EAST);

jplMaster.add(jplButtons, BorderLayout.SOUTH);

62

Page 63: Java Lab Manual(22!8!11)

// Add components to frame

getContentPane().add(jplMaster, BorderLayout.SOUTH);

requestFocus();

//activate ActionListener

for (int i=0; i<jbnButtons.length; i++){

jbnButtons[i].addActionListener(this);

}

jmenuitemAbout.addActionListener(this);

jmenuitemExit.addActionListener(this);

clearAll();

//add WindowListener for closing frame and ending program

addWindowListener(new WindowAdapter() {

public void windowClosed(WindowEvent e)

{

System.exit(0);

}

}

);

} //End of Contructor Calculator

63

Page 64: Java Lab Manual(22!8!11)

// Perform action

public void actionPerformed(ActionEvent e){

double result = 0;

if(e.getSource() == jmenuitemAbout){

JDialog dlgAbout = new CustomABOUTDialog(this,

"About Java Swing Calculator", true);

dlgAbout.setVisible(true);

}else if(e.getSource() == jmenuitemExit){

System.exit(0);

}

// Search for the button pressed until end of array or key found

for (int i=0; i<jbnButtons.length; i++)

{

if(e.getSource() == jbnButtons[i])

{

switch(i)

{

case 0:

addDigitToDisplay(i);

break;

case 1:

addDigitToDisplay(i);

64

Page 65: Java Lab Manual(22!8!11)

break;

case 2:

addDigitToDisplay(i);

break;

case 3:

addDigitToDisplay(i);

break;

case 4:

addDigitToDisplay(i);

break;

case 5:

addDigitToDisplay(i);

break;

case 6:

addDigitToDisplay(i);

break;

case 7:

addDigitToDisplay(i);

break;

65

Page 66: Java Lab Manual(22!8!11)

case 8:

addDigitToDisplay(i);

break;

case 9:

addDigitToDisplay(i);

break;

case 10: // +/-

processSignChange();

break;

case 11: // decimal point

addDecimalPoint();

break;

case 12: // =

processEquals();

break;

case 13: // divide

processOperator("/");

break;

66

Page 67: Java Lab Manual(22!8!11)

case 14: // *

processOperator("*");

break;

case 15: // -

processOperator("-");

break;

case 16: // +

processOperator("+");

break;

case 17: // sqrt

if (displayMode != ERROR_MODE)

{

try

{

if (getDisplayString().indexOf("-") == 0)

displayError("Invalid input for function!");

result = Math.sqrt(getNumberInDisplay());

displayResult(result);

}

67

Page 68: Java Lab Manual(22!8!11)

catch(Exception ex)

{

displayError("Invalid input for function!");

displayMode = ERROR_MODE;

}

}

break;

case 18: // 1/x

if (displayMode != ERROR_MODE){

try

{

if (getNumberInDisplay() == 0)

displayError("Cannot divide by zero!");

result = 1 / getNumberInDisplay();

displayResult(result);

}

catch(Exception ex) {

displayError("Cannot divide by zero!");

displayMode = ERROR_MODE;

}

}

68

Page 69: Java Lab Manual(22!8!11)

break;

case 19: // %

if (displayMode != ERROR_MODE){

try {

result = getNumberInDisplay() / 100;

displayResult(result);

}

catch(Exception ex) {

displayError("Invalid input for function!");

displayMode = ERROR_MODE;

}

}

break;

case 20: // backspace

if (displayMode != ERROR_MODE){

setDisplayString(getDisplayString().substring(0,getDisplayString().length() - 1));

if (getDisplayString().length() < 1)

setDisplayString("0");

}

break;

69

Page 70: Java Lab Manual(22!8!11)

case 21: // CE

clearExisting();

break;

case 22: // C

clearAll();

break;

}

}

}

}

void setDisplayString(String s){

jlbOutput.setText(s);

}

String getDisplayString (){

return jlbOutput.getText();

}

void addDigitToDisplay(int digit){

if (clearOnNextDigit)

setDisplayString("");

70

Page 71: Java Lab Manual(22!8!11)

String inputString = getDisplayString();

if (inputString.indexOf("0") == 0){

inputString = inputString.substring(1);

}

if ((!inputString.equals("0") || digit > 0) && inputString.length() < MAX_INPUT_LENGTH)

{

setDisplayString(inputString + digit);

}

displayMode = INPUT_MODE;

clearOnNextDigit = false;

}

void addDecimalPoint(){

displayMode = INPUT_MODE;

if (clearOnNextDigit)

setDisplayString("");

String inputString = getDisplayString();

// If the input string already contains a decimal point, don't

71

Page 72: Java Lab Manual(22!8!11)

// do anything to it.

if (inputString.indexOf(".") < 0)

setDisplayString(new String(inputString + "."));

}

void processSignChange(){

if (displayMode == INPUT_MODE)

{

String input = getDisplayString();

if (input.length() > 0 && !input.equals("0"))

{

if (input.indexOf("-") == 0)

setDisplayString(input.substring(1));

else

setDisplayString("-" + input);

}

}

else if (displayMode == RESULT_MODE)

{

double numberInDisplay = getNumberInDisplay();

72

Page 73: Java Lab Manual(22!8!11)

if (numberInDisplay != 0)

displayResult(-numberInDisplay);

}

}

void clearAll() {

setDisplayString("0");

lastOperator = "0";

lastNumber = 0;

displayMode = INPUT_MODE;

clearOnNextDigit = true;

}

void clearExisting(){

setDisplayString("0");

clearOnNextDigit = true;

displayMode = INPUT_MODE;

}

double getNumberInDisplay() {

String input = jlbOutput.getText();

return Double.parseDouble(input);

}

void processOperator(String op) {

73

Page 74: Java Lab Manual(22!8!11)

if (displayMode != ERROR_MODE)

{

double numberInDisplay = getNumberInDisplay();

if (!lastOperator.equals("0"))

{

try

{

double result = processLastOperator();

displayResult(result);

lastNumber = result;

}

catch (DivideByZeroException e)

{

}

}

else

{

lastNumber = numberInDisplay;

}

clearOnNextDigit = true;

lastOperator = op;

74

Page 75: Java Lab Manual(22!8!11)

}

}

void processEquals(){

double result = 0;

if (displayMode != ERROR_MODE){

try

{

result = processLastOperator();

displayResult(result);

}

catch (DivideByZeroException e) {

displayError("Cannot divide by zero!");

}

lastOperator = "0";

}

}

double processLastOperator() throws DivideByZeroException {

double result = 0;

double numberInDisplay = getNumberInDisplay();

75

Page 76: Java Lab Manual(22!8!11)

if (lastOperator.equals("/"))

{

if (numberInDisplay == 0)

throw (new DivideByZeroException());

result = lastNumber / numberInDisplay;

}

if (lastOperator.equals("*"))

result = lastNumber * numberInDisplay;

if (lastOperator.equals("-"))

result = lastNumber - numberInDisplay;

if (lastOperator.equals("+"))

result = lastNumber + numberInDisplay;

return result;

}

void displayResult(double result){

setDisplayString(Double.toString(result));

lastNumber = result;

displayMode = RESULT_MODE;

clearOnNextDigit = true;

76

Page 77: Java Lab Manual(22!8!11)

}

void displayError(String errorMessage){

setDisplayString(errorMessage);

lastNumber = 0;

displayMode = ERROR_MODE;

clearOnNextDigit = true;

}

public static void main(String args[]) {

Calculator calci = new Calculator();

Container contentPane = calci.getContentPane();

// contentPane.setLayout(new BorderLayout());

calci.setTitle("Java Swing Calculator");

calci.setSize(241, 217);

calci.pack();

calci.setLocation(400, 250);

calci.setVisible(true);

calci.setResizable(false);

}

} //End of Swing Calculator Class.

class DivideByZeroException extends Exception{

public DivideByZeroException()

77

Page 78: Java Lab Manual(22!8!11)

{

super();

}

public DivideByZeroException(String s)

{

super(s);

}

}

class CustomABOUTDialog extends JDialog implements ActionListener {

JButton jbnOk;

CustomABOUTDialog(JFrame parent, String title, boolean modal){

super(parent, title, modal);

setBackground(Color.black);

JPanel p1 = new JPanel(new FlowLayout(FlowLayout.CENTER));

StringBuffer text = new StringBuffer();

text.append("Calculator Information\n\n");

text.append("Developer: Hemanth\n");

text.append("Version: 1.0");

JTextArea jtAreaAbout = new JTextArea(5, 21);

78

Page 79: Java Lab Manual(22!8!11)

jtAreaAbout.setText(text.toString());

jtAreaAbout.setFont(new Font("Times New Roman", 1, 13));

jtAreaAbout.setEditable(false);

p1.add(jtAreaAbout);

p1.setBackground(Color.red);

getContentPane().add(p1, BorderLayout.CENTER);

JPanel p2 = new JPanel(new FlowLayout(FlowLayout.CENTER));

jbnOk = new JButton(" OK ");

jbnOk.addActionListener(this);

p2.add(jbnOk);

getContentPane().add(p2, BorderLayout.SOUTH);

setLocation(408, 270);

setResizable(false);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e)

{

Window aboutDialog = e.getWindow();

aboutDialog.dispose();

}

}

79

Page 80: Java Lab Manual(22!8!11)

);

pack();

}

public void actionPerformed(ActionEvent e)

{

if(e.getSource() == jbnOk) {

this.dispose();

}

}

}

80

Page 81: Java Lab Manual(22!8!11)

OUTPUT:

Result:

Thus the Scientific calculator program was compiled and executed successfuly.

81

Page 82: Java Lab Manual(22!8!11)

Ex.No:9 DEVELOPING A TEMPLATE FOR LINKED LIST

Aim:

To develop a template for linked list in java.

Algorithm:

1. Import the necessary packages.

2. Declare the main function within the class Linked list demo.

3. Insert items in to the list using add() method use addLast() to isert at the end.

4. Display the contents of the lists.

5. Use remove() method to declare a specific element.

6. Use remove() first(0,removeLast() to delete the element at the first and at the last.

7. Display the lsit and hadle the exceptions .

82

Page 83: Java Lab Manual(22!8!11)

DEVELOPING A TEMPLATE FOR LINKED LIST

import java.util.*;

class LinkedListDemo

{

public static void main(String args[])

{

LinkedList<String> l1=new LinkedList<String>();

l1.add("F");

l1.add("B");

l1.add("D");

l1.add("E");

l1.add("C");

l1.addLast("Z");

l1.addLast("A");

l1.add(1,"A2");

System.out.println("Original contents of l1:" + l1);

l1.remove("F");

l1.remove(2);

System.out.println("Contents of l1 after deflection: " + l1);

l1.removeFirst();

l1.removeLast();

System.out.println("l1 after deleting first and last: " + l1);

83

Page 84: Java Lab Manual(22!8!11)

String val=l1.get(2);

l1.set(2, val + "Changed");

System.out.println("l1 after change: " + l1); } }

84

Page 85: Java Lab Manual(22!8!11)

OUTPUT:

E:\SQ>java LinkedListDemo

Original contents of l1:[F, A2, B, D, E, C, Z, A]

Contents of l1 after deflection: [A2, B, E, C, Z, A]

l1 after deleting first and last: [B, E, C, Z]

l1 after change: [B, E, CChanged, Z]

Result:

Thus the Linked list program was compiled and executed successfuly.

85

Page 86: Java Lab Manual(22!8!11)

.

Ex.No:10 DEVELOP A MULTI THREADED PRODUCER CONSUMER APPLICATION

Aim:

To develop a multithreaded producer and consumer application in java.

Algorithm:

1. Import the necessary packages.

2. Create two threads producer and consumer.

3. Declare a constant MAXQUEUE in producer thread.

4. Create an instance for vector named messages to implement a queue.

5. In the run() method of producer thread put the messages on the queue using putmessages() and suspend the thread for one sec using sleep(1000).

6. Declare the getmessage() method and ceck whether there is any message if no wait for one.

7. After receiving the message remove the message and return it.

8. Create a constructor to assign values to them.

9. In the run method of consumer class call the getmessage() method of producer thread and print the message.

10. Suspend the thread for 2 sec using sleep(2000).

11. Create two instances with different name for consumer thread.

12. Display the message.

86

Page 87: Java Lab Manual(22!8!11)

DEVELOP A MULTI THREADED PRODUCER CONSUMER APLICATION

import java.util.Vector;

class Producer extends Thread {

static final int MAXQUEUE = 5;

private Vector messages = new Vector();

public void run() {

try {

while ( true ) {

putMessage();

sleep( 1000 );

}

}

catch( InterruptedException e ) { }

}

private synchronized void putMessage()

throws InterruptedException {

while ( messages.size() == MAXQUEUE )

wait();

87

Page 88: Java Lab Manual(22!8!11)

messages.addElement( new java.util.Date().toString() );

notify();

}

// Called by Consumer

public synchronized String getMessage()

throws InterruptedException {

notify();

while ( messages.size() == 0 )

wait();

String message = (String)messages.firstElement();

messages.removeElement( message );

return message;

}

}

class Consumer extends Thread {

Producer producer;

String name;

Consumer(String name, Producer producer) {

this.producer = producer;

this.name = name;

}

88

Page 89: Java Lab Manual(22!8!11)

public void run() {

try {

while ( true ) {

String message = producer.getMessage();

System.out.println(name + " got message: " + message);

sleep( 2000 );

}

}

catch( InterruptedException e ) { }

}

public static void main(String args[]) {

Producer producer = new Producer();

producer.start();

// Start two this time

new Consumer( "One", producer ).start();

new Consumer( "Two", producer ).start();

}

}

89

Page 90: Java Lab Manual(22!8!11)

OUTPUT:

E:\SQ>java Consumer

Two got message: Wed Sep 01 11:57:54 GMT+05:30 2010

One got message: Wed Sep 01 11:57:55 GMT+05:30 2010

Two got message: Wed Sep 01 11:57:56 GMT+05:30 2010

One got message: Wed Sep 01 11:57:57 GMT+05:30 2010

Two got message: Wed Sep 01 11:57:58 GMT+05:30 2010

One got message: Wed Sep 01 11:57:59 GMT+05:30 2010

Two got message: Wed Sep 01 11:58:00 GMT+05:30 2010

One got message: Wed Sep 01 11:58:01 GMT+05:30 2010

Two got message: Wed Sep 01 11:58:02 GMT+05:30 2010

One got message: Wed Sep 01 11:58:03 GMT+05:30 2010

One got message: Wed Sep 01 11:58:04 GMT+05:30 2010

Two got message: Wed Sep 01 11:58:18 GMT+05:30 2010

One got message: Wed Sep 01 11:58:19 GMT+05:30 2010

Two got message: Wed Sep 01 11:58:20 GMT+05:30 2010

One got message: Wed Sep 01 11:58:21 GMT+05:30 2010

Two got message: Wed Sep 01 11:58:22 GMT+05:30 2010

Result:

Thus the Multithreaded program was compiled and executed successfuly.

.

90

Page 91: Java Lab Manual(22!8!11)

Ex.No:11 GENERATING PRIME NUMBERS AND FIBONACCI SERIES

Aim:

To generate prime numbers and fibonacci series using java.

Algorithm:

1. Import the necessary packages.

2. Create tow threads MyThread1 and MyThread2.

3. In MyThread1 create instances for piped reader and piped writer.

4. Create a constructor and assign values to them.

5. In mythread2 create instances for pipedreader and piped writer.

6. Create a constructor and assign values to them.

7. Declare a class Multithreaded programming and create two list using ArrayList.

8. Create instances for pipedreader and pipedwriter prl and pwl respectively.

9. Get the Fibonacci series from the stream pr2 and store them in lsit2 by using retainAll() method and print them.

91

Page 92: Java Lab Manual(22!8!11)

GENERATING PRIME NUMBERS AND FIBONACCI SERIES

import java.io.*;

import java.util.*;

class MyThread1 extends Thread {

private PipedReader pr;

private PipedWriter pw;

MyThread1(PipedReader pr, PipedWriter pw) {

this.pr = pr;

this.pw = pw;

}

public void run() {

try {

int i;

for (i=1;i<10;i++)

{

int j;

for (j=2; j<i; j++)

{

int n = i%j;

if (n==0)

{

break;

}

}

92

Page 93: Java Lab Manual(22!8!11)

if(i == j)

{

pw.write(i+"\n");

}

}

pw.close();

} catch (IOException e) {

}

}

}

class MyThread2 extends Thread {

private PipedReader pr;

private PipedWriter pw;

MyThread2(PipedReader pr, PipedWriter pw) {

this.pr = pr;

this.pw = pw;

}

public void run() {

try {

int f1, f2 = 1, f3 = 1;

for (int i = 1; i <10; i++) {

pw.write(f3+"\n");

f1 = f2;

93

Page 94: Java Lab Manual(22!8!11)

f2 = f3;

f3 = f1 + f2;

}

pw.close();

} catch (IOException e) {

}

}

}

class MultithreadedProgram {

public static void main(String[] args) throws Exception {

ArrayList list1=new ArrayList();

ArrayList list2=new ArrayList();

PipedWriter pw1 = new PipedWriter();

PipedReader pr1 = new PipedReader(pw1);

MyThread1 mt1 = new MyThread1(pr1, pw1);

System.out.println("Prime Numbers: ");

mt1.start();

int item1;

while ((item1 = pr1.read()) != -1){

char ch1=((char) item1);

System.out.print(Character.toString(ch1));

list1.add(Character.toString(ch1));

}

pr1.close();

PipedWriter pw2 = new PipedWriter();

94

Page 95: Java Lab Manual(22!8!11)

PipedReader pr2 = new PipedReader(pw2);

MyThread2 mt2 = new MyThread2(pr2, pw2);

System.out.println("Fibonacci Numbers: ");

mt2.start();

int item2;

while ((item2 = pr2.read()) != -1){

char ch2=((char) item2);

System.out.print(Character.toString(ch2));

list2.add(Character.toString(ch2));

}

pr2.close();

System.out.println("Elements common to both lists are:");

list1.retainAll(list2);

for(int i=0;i<list1.size();i++){

System.out.print(list1.get(i));

}

}

}

95

Page 96: Java Lab Manual(22!8!11)

OUTPUT:

E:\SQ>java MultithreadedProgram

Prime Numbers:

2

3

5

7

Fibonacci Numbers:

1

2

3

5

8

13

21

34

55

Elements common to both lists are:

2

3

5

Result:

Thus the program was compiled and executed successfuly.

.

96

Page 97: Java Lab Manual(22!8!11)

Ex.No:12 MULTITHREADED GUI APPLICATION

Aim:

To develop a multithreaded GUI application in java.

Algorithm:

1. Create the class ball which implements a ball which moves and bounces of the edges of a rectangle.

2. Using the move() method move the ball to the nect postion by reversing the direction if it bits one of the edges.

3. Get the shapes of the ball at its current position.

4. Invoke the runnable() method to show the animated bouncing balls.

5. Using the sleep() method assign the time for ball to bounce in a given interval of time.

6. Construct the frame with the component for showing bouncing ball and start and close buttons.

7. Add the thread to the frame and button to the container.

8. Create a constructor to assign values to them.

9. Add a bouncing ball to the canvas and starts a thread to make it bounce.

10. Display the output.

97

Page 98: Java Lab Manual(22!8!11)

MULTITHREADED GUI APPLICATION

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.util.*;

import java.awt.geom.*;

/**

A ball that moves and bounces off the edges of a

rectangle

* @version 1.33 2007-05-17

* @author Cay Horstmann

*/

class Ball

{

/**

Moves the ball to the next position, reversing direction

if it hits one of the edges

*/

public void move(Rectangle2D bounds)

{

x += dx;

y += dy;

if (x < bounds.getMinX())

98

Page 99: Java Lab Manual(22!8!11)

{

x = bounds.getMinX();

dx = -dx;

}

if (x + XSIZE >= bounds.getMaxX())

{

x = bounds.getMaxX() - XSIZE;

dx = -dx;

}

if (y < bounds.getMinY())

{

y = bounds.getMinY();

dy = -dy;

}

if (y + YSIZE >= bounds.getMaxY())

{

y = bounds.getMaxY() - YSIZE;

dy = -dy;

}

}

/**

Gets the shape of the ball at its current position.

*/

public Ellipse2D getShape()

99

Page 100: Java Lab Manual(22!8!11)

{

return new Ellipse2D.Double(x, y, XSIZE, YSIZE);

}

private static final int XSIZE = 15;

private static final int YSIZE = 15;

private double x = 0;

private double y = 0;

private double dx = 1;

private double dy = 1;

}

class BallComponent extends JComponent

{

/**

* Add a ball to the panel.

* @param b the ball to add

*/

public void add(Ball b)

{

balls.add(b);

}

public void paintComponent(Graphics g)

{

Graphics2D g2 = (Graphics2D) g;

for (Ball b : balls)

100

Page 101: Java Lab Manual(22!8!11)

{

g2.fill(b.getShape());

}

}

private ArrayList<Ball> balls = new ArrayList<Ball>();

}

/**

* Shows animated bouncing balls.

* @version 1.33 2007-05-17

* @author Cay Horstmann

*/

public class BounceThread

{

public static void main(String[] args)

{

EventQueue.invokeLater(new Runnable()

{

public void run()

{

JFrame frame = new BounceFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

}

});

}

101

Page 102: Java Lab Manual(22!8!11)

}

/**

* A runnable that animates a bouncing ball.

*/

class BallRunnable implements Runnable

{

/**

* Constructs the runnable.

* @aBall the ball to bounce

* @aPanel the component in which the ball bounces

*/

public BallRunnable(Ball aBall, Component aComponent)

{

ball = aBall;

component = aComponent;

}

public void run()

{

try

{

for (int i = 1; i <= STEPS; i++)

{

ball.move(component.getBounds());

102

Page 103: Java Lab Manual(22!8!11)

component.repaint();

Thread.sleep(DELAY);

}

}

catch (InterruptedException e)

{

}

}

private Ball ball;

private Component component;

public static final int STEPS = 1000;

public static final int DELAY = 5;

}

/**

* The frame with panel and buttons.

*/

class BounceFrame extends JFrame

{

/**

* Constructs the frame with the component for showing the bouncing ball and Start and Close

* buttons

*/

public BounceFrame()

103

Page 104: Java Lab Manual(22!8!11)

{

setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

setTitle("BounceThread");

comp = new BallComponent();

add(comp, BorderLayout.CENTER);

JPanel buttonPanel = new JPanel();

addButton(buttonPanel, "Start", new ActionListener()

{

public void actionPerformed(ActionEvent event)

{

addBall();

}

});

addButton(buttonPanel, "Close", new ActionListener()

{

public void actionPerformed(ActionEvent event)

{

System.exit(0);

}

});

add(buttonPanel, BorderLayout.SOUTH);

}

104

Page 105: Java Lab Manual(22!8!11)

/**

* Adds a button to a container.

* @param c the container

* @param title the button title

* @param listener the action listener for the button

*/

public void addButton(Container c, String title, ActionListener listener)

{

JButton button = new JButton(title);

c.add(button);

button.addActionListener(listener);

}

/**

* Adds a bouncing ball to the canvas and starts a thread to make it bounce

*/

public void addBall()

{

Ball b = new Ball();

comp.add(b);

Runnable r = new BallRunnable(b, comp);

Thread t = new Thread(r);

t.start();

}

105

Page 106: Java Lab Manual(22!8!11)

private BallComponent comp;

public static final int DEFAULT_WIDTH = 450;

public static final int DEFAULT_HEIGHT = 350;

public static final int STEPS = 1000;

public static final int DELAY = 3;

}

106

Page 107: Java Lab Manual(22!8!11)

OUTPUT:

Result:

Thus the Multithreaded GUI application was compiled and executed successfuly.

107