67
Ex No1: Rational Numbers AIM To write a Java Program to develop a class for Rational numbers. ALGORITHM: Step 1:-Declare a class called Rational and invoke a function called gcd(a,b). Step 2:-Find out the reminder when a is divided by b and pass it as a parameter to the function. Step 3:-Create an object for the class and declare the required string and integer variables. Step 4:-Create an object of class DataInputStream .Read the numbers through the ReadLine() method into the object. Step 5:-Convert the input accepted into Integers through the parseInt method and store them in variables a and b. Step 6:-store the value returned by the function GCD in variable l. Step 7:-Divide a by l and b by l and store them in variables x and y.

(674335607) Cs2309-Java-Lab-Manual

  • Upload
    preetha

  • View
    18

  • Download
    0

Embed Size (px)

DESCRIPTION

Java lab manual

Citation preview

Page 1: (674335607) Cs2309-Java-Lab-Manual

Ex No1: Rational Numbers

AIM To write a Java Program to develop a class for Rational numbers.

ALGORITHM:

Step 1:-Declare a class called Rational and invoke a function called gcd(a,b).

Step 2:-Find out the reminder when a is divided by b and pass it as a parameter to the function.

Step 3:-Create an object for the class and declare the required string and integer variables.

Step 4:-Create an object of class DataInputStream .Read the numbers through the ReadLine() method into the object.

Step 5:-Convert the input accepted into Integers through the parseInt method and store them in variables a and b.

Step 6:-store the value returned by the function GCD in variable l.

Step 7:-Divide a by l and b by l and store them in variables x and y.

Page 2: (674335607) Cs2309-Java-Lab-Manual

Program:-

import java.io.*;class rational1{

public rational1(){}

public long gcd(long a,long b){

if(b==0)return a;

elsereturn gcd(b,a%b);

}}public class rational{

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

rational1 r=new rational1();long a,b,x,y; String str;DataInputStream in= new DataInputStream(System.in); System.out.println("Enter the value for A"); str=in.readLine();a=Integer.parseInt(str);System.out.println("Enter the value for B");str=in.readLine();b=Integer.parseInt(str);

long l=r.gcd(a,b); System.out.println();System.out.println("The GCD of the number is:"+l);x=a/l;y=b/l; System.out.println();System.out.println("The resultant value is: "+x+"/"+y);

}}

Output

Enter the value for A500Enter the value for B1000

The GCD of the number is:500

Page 3: (674335607) Cs2309-Java-Lab-Manual

The resultant value is: 1/2Ex No 2: Date Class in Java

AIM

To design a Date class in Java .

ALGORITHM:-

Step 1:Declare a class called Dateexample and create an object called date.

Step 2:-Display the Date and Time through these objects with theMethods in Date Class.

Step 3:-Declare two objects called starttime and endtime for this class .

Step 4:-Create another object called changed object and display the changed time with the calculation 24L*60L*60L*1000L.

Step 5:-In the main function create object for the class Date and display the time and date accordingly.

Page 4: (674335607) Cs2309-Java-Lab-Manual

SOURCE CODE

import java.util.Date;import java.text.ParseException; import java.text.SimpleDateFormat; public class DateExample {

private static void DateExample() {

Date date = new Date();System.out.println("Current Date and Time is : " + date); System.out.println();

me");

te1);

te2);

System.out.println("Date object showing specific date and ti

Date particulardate1 = new Date(24L*60L*60L*1000L); Date particulardate2 = new Date(0L); System.out.println();System.out.println("First Particular date : " + particularda

System.out.println("Second Particular date: " + particularda

System.out.println();

System.out.println("Demo of getTime() method returning milli seconds");

System.out.println();Date strtime = new Date(); System.out.println("Start Time: " + strtime); Date endtime = new Date(); System.out.println("End Time is: " + endtime);long elapsed_time = endtime.getTime() - strtime.getTime(); System.out.println("Elapsed Time is:" + elapsed_time + " mil

liseconds"); System.out.println();

od");

}

System.out.println("Changed date object using setTime() meth

System.out.println();Date chngdate = new Date();System.out.println("Date before change is: " + chngdate);chngdate.setTime(24L*60L*60L*1000L);System.out.println("Now the Changed date is: " + chngdate); System.out.println();

public static void main(String[] args) { System.out.println();DateExample();

}

Page 5: (674335607) Cs2309-Java-Lab-Manual

}

OUTPUT

Current Date and Time is : Mon Dec 10 18:39:27 GMT+05:302007

Date object showing specific date and time

First Particular date : Fri Jan 02 05:30:00 GMT+05:30 1970Second Particular date: Thu Jan 01 05:30:00 GMT+05:30 1970

Demo of getTime() method returning milliseconds

Start Time: Mon Dec 10 18:39:28 GMT+05:30 2007End Time is: Mon Dec 10 18:39:28 GMT+05:30 2007Elapsed Time is:0 milliseconds

Changed date object using setTime() method

Date before change is: Mon Dec 10 18:39:28 GMT+05:30 2007Now the Changed date is: Fri Jan 02 05:30:00 GMT+05:30 1970

Page 6: (674335607) Cs2309-Java-Lab-Manual

Ex4 : Implementation of Stack ADT

AIM

To write a Java Program to design an interface for StackADT.and implement Stack ADT using both Array and Linked List.

ALGORITHM

Step 1:Declare an array for storing the stack elements and initialise the capacity of the array.

Step 2:-Declare functions makeempty(),isempty() to check whether the stack is empty to insert an element.

Step 3:After inserting an element,increment the counter by 1 to increase the number of elements in stack.

Step 4:Initiate another array to extend the size of the array when the number of elements exceed beyond the limit.

Step 5:-Invoke methods and constructors to implement the stack using linked list.

Step 6:-Test if the stack is logically empty.then return true or else false.

Step 7:To delete an element from stack,check if stack is empty,if so throw an exception or else move to the next element in the stack.

Step 8:To return the most recently inserted element use the method topOfStack() and then move the pointer to the next element.

Step 9:Declare a stack Interface to push and pop elements from stack.

Step 10:create two objects one for array and other for linked list implementation of stack.

Step 11:Insert characters and numbers into the stack using the methods and display the inserted elements with exception blocks.

Page 7: (674335607) Cs2309-Java-Lab-Manual

SOURCE CODE

/*** Array-based implementation of the stack.

*/public class ArrayStack implements Stack {

private Object [ ] theArray;private int topOfStack;private static final int DEFAULT_CAPACITY = 10;

/*** Construct the stack.*/public ArrayStack( ) {

theArray = new Object[ DEFAULT_CAPACITY ];topOfStack = -1;

}

/*** Test if the stack is logically empty.* @return true if empty, false otherwise.*/public boolean isEmpty( ) {

return topOfStack == -1;}

/*** Make the stack logically empty.*/public void makeEmpty( ) {

topOfStack = -1;}

/*** Get the most recently inserted item in the stack.* Does not alter the stack.* @return the most recently inserted item in the stack.* @throws UnderflowException if the stack is empty.*/public Object top( ) {

if( isEmpty( ) )throw new UnderflowException( "ArrayStack top" );

return theArray[ topOfStack ];}

/*** Remove the most recently inserted item from the stack.* @throws UnderflowException if the stack is empty.*/public void pop( ) {

Page 8: (674335607) Cs2309-Java-Lab-Manual

if( isEmpty( ) )throw new UnderflowException( "ArrayStack pop" );

topOfStack--;}

/*** Return and remove the most recently inserted item* from the stack.* @return the most recently inserted item in the stack.* @throws Underflow if the stack is empty.*/public Object topAndPop( ) {

if( isEmpty( ) )throw new UnderflowException( "ArrayStack topAndPop" );return theArray[ topOfStack-- ];

}

/*** Insert a new item into the stack.* @param x the item to insert.*/public void push( Object x ) {

if( topOfStack + 1 == theArray.length )doubleArray( );

theArray[ ++topOfStack ] = x;}

/*** Internal method to extend theArray.*/private void doubleArray( ) {

Object [ ] newArray;

newArray = new Object[ theArray.length * 2 ];for( int i = 0; i < theArray.length; i++ )

newArray[ i ] = theArray[ i ];theArray = newArray;

}

}

Page 9: (674335607) Cs2309-Java-Lab-Manual

//ListStack class//// CONSTRUCTION: with no initializer//// ******************PUBLIC OPERATIONS*********************// void push( x ) --> Insert x// void pop( ) --> Remove most recently inserted item// Object top( ) --> Return most recently inserted item// Object topAndPop( ) --> Return and remove most recent item// boolean isEmpty( ) --> Return true if empty; else false// void makeEmpty( ) --> Remove all items// ******************ERRORS********************************// top, pop, or topAndPop on empty stack

/*** List-based implementation of the stack.

*/public class LinkedListStack implements Stack {

/*** Construct the stack.*/

public LinkedListStack( ) {topOfStack = null;

}

/*** Test if the stack is logically empty.* @return true if empty, false otherwise.*/

public boolean isEmpty( ) {return topOfStack == null;

}

/*** Make the stack logically empty.*/

public void makeEmpty( ) {topOfStack = null;

}

/*** Insert a new item into the stack.* @param x the item to insert.*/

public void push( Object x ) {topOfStack = new ListNode( x, topOfStack );

}

/*** Remove the most recently inserted item from the stack.* @throws UnderflowException if the stack is empty.

Page 10: (674335607) Cs2309-Java-Lab-Manual

*/public void pop( ) {

if( isEmpty( ) )throw new UnderflowException( "ListStack pop" );

topOfStack = topOfStack.next;}

/*** Get the most recently inserted item in the stack.* Does not alter the stack.* @return the most recently inserted item in the stack.* @throws UnderflowException if the stack is empty.*/

public Object top( ) {if( isEmpty( ) )

throw new UnderflowException( "ListStack top" );return topOfStack.element;

}

/*** Return and remove the most recently inserted item* from the stack.* @return the most recently inserted item in the stack.* @throws UnderflowException if the stack is empty.*/

public Object topAndPop( ) {if( isEmpty( ) )

throw new UnderflowException( "ListStack topAndPop");

Object topItem = topOfStack.element;topOfStack = topOfStack.next;return topItem;

}

private ListNode topOfStack;

}

public class ListNode {public Object element;public ListNode next;

// Constructorspublic ListNode( Object theElement ) {

this( theElement, null );}

public ListNode( Object theElement, ListNode n ) {element = theElement;

Page 11: (674335607) Cs2309-Java-Lab-Manual

next = n;}

}

public interface Stack {/*** Insert a new item into the stack.* @param x the item to insert.*/

void push( Object x );

/*** Remove the most recently inserted item from the stack.* @exception UnderflowException if the stack is empty.*/

void pop( );

/*** Get the most recently inserted item in the stack.* Does not alter the stack.* @return the most recently inserted item in the stack.* @exception UnderflowException if the stack is empty.*/

Object top( );

/*** Return and remove the most recently inserted item* from the stack.* @return the most recently inserted item in the stack.* @exception UnderflowException if the stack is empty.*/

Object topAndPop( );

/*** Test if the stack is logically empty.* @return true if empty, false otherwise.*/

boolean isEmpty( );

/*** Make the stack logically empty.*/

void makeEmpty( );

}

public class StackTester {

Page 12: (674335607) Cs2309-Java-Lab-Manual

public static void main(String[] args) {

System.out.println("******************************************"); System.out.println("Stack using Array & Linked List

example");

System.out.println("******************************************");

c");

ArrayStack arrayStack = new ArrayStack(); arrayStack.push(new String("a")); arrayStack.push(new String("b")); arrayStack.push(new String("c"));System.out.println("Stack[using array] elements -> a, b,

System.out.println("Stack LIFO and POP ->"+arrayStack.topAndPop());

System.out.println("Stack LIFO -> "+arrayStack.top());arrayStack.pop();try{

arrayStack.pop();arrayStack.topAndPop();

}catch(RuntimeException rte){ System.err.println("Exception occured while POP

operation is happened on Stack[by using array]");} System.out.println("\n\n******************************"); System.out.println("Stack using Linked List example"); System.out.println("******************************");

LinkedListStack linkedListStack = new LinkedListStack(); linkedListStack.push(new Integer(10)); linkedListStack.push(new Integer(20)); linkedListStack.push(new Integer(30)); linkedListStack.push(new Integer(40)); System.out.println("Stack[using linked list] elements ->

10, 20, 30, 40");System.out.println("Stack TOP ->"+linkedListStack.top());linkedListStack.pop(); System.out.println("Stack TOP after POP

->"+linkedListStack.top()); linkedListStack.pop(); linkedListStack.pop(); linkedListStack.pop(); try{

linkedListStack.pop();}catch(RuntimeException rte)

{ System.err.println("Exception occured while POP

operation is happened on Stack[by using linked list]");}

Page 13: (674335607) Cs2309-Java-Lab-Manual

}}

/*** Exception class for access in empty containers* such as stacks, queues, and priority queues.* @author Ramkumar*/

public class UnderflowException extends RuntimeException {/*** Construct this exception object.* @param message the error message.*/

public UnderflowException( String message ) {super( message );

}}

OUTPUT

Stack using Array & Linked List example****************************************** Stack[using array] elements -> a, b, c Stack LIFO and POP -> cStack LIFO -> bException occured while POP operation is happened on Stack[by using array]

****************************** Stack using Linked List example******************************Stack[using linked list] elements -> 10, 20, 30, 40Stack TOP ->40Stack TOP after POP ->30Exception occured while POP operation is happened on Stack[by using linked list]

Page 14: (674335607) Cs2309-Java-Lab-Manual

Ex no:5 Polymorphism

Aim:- To develop a vehicle class hierarchy in Java to demonstrate the concept of polymorphism.

Algorithm:-

Step 1:-Declare a super class called vehicle with data elements doors,wheels and seats.

Step 2:-Derive another class called car and invoke a function tostring() to display the variables.

Step 3:-Derive another class called motorcycle with same data and method called setseats() .

Step 4:-Declare another sub class called Truck with 2 constructors and finally assign values to variables.

Step 5:-In the main function, create an object for class motorcycle and display all details of sub classes through object.

Sourcecode:-

//This is the class that will be inherited public class Vehicle{

public int doors; public int seats; public int wheels; Vehicle(){

wheels=4; doors=4; seats=4;

}}//This class inherits Vehicle.java public class Car extends Vehicle{

public String toString()

Page 15: (674335607) Cs2309-Java-Lab-Manual

{return "This car has "+seats+" Seats, "+doors+" Doors "+

"and "+wheels+" wheels.";}

}//This class inherits Vehicle.java public class MotorCycle extends Vehicle{

MotorCycle(){

wheels=2; doors=0; seats=1;

}void setSeats(int num){

seats=num;}public String toString(){

return "This motorcycle has "+seats+" Seats, "+doors+" Doors "+ "and "+wheels+" wheels.";

}}//This class inherits Vehicle.java public class Truck extends Vehicle{

boolean isPickup; Truck(){

isPickup=true;}Truck(boolean aPickup){

this();isPickup=aPickup;

}Truck(int doors, int seats, int inWheels, boolean isPickup){

this.doors=doors; this.seats=seats; wheels=inWheels; this.isPickup=isPickup;

}public String toString(){

return "This "+(isPickup?"pickup":"truck")+" has "+seats+" Seats, "+doors+" Doors "+"and "+wheels+"

wheels.";}

}//This class tests the classes that inherit Vehicle.javapublic class VehiclesTest{

public static void main(String args[]){

MotorCycle mine = new MotorCycle();

Page 16: (674335607) Cs2309-Java-Lab-Manual

System.out.println(mine); Car mine2 = new Car(); System.out.println(mine2); mine2.doors=2; System.out.println(mine2); Truck mine3 = new Truck(); System.out.println(mine3);Truck mine4 = new Truck(false);mine4.doors=2; System.out.println(mine4);

}}

Output

This motorcycle has 1 Seats, 0 Doors and 2 wheelsThis car has 4 Seats, 4 Doors and 4 wheels This car has 4 Seats, 2 Doors and 4 wheels This pickup has 4 Seats, 4 Doors and 4 wheels This truck has 4 Seats, 2 Doors and 4 wheels

Ex No:-6 Object Serialization

Aim:-To write a Java Program to randomly generate objects and write them into a file using concept of Object Serialization.

Algorithm:-

Step 1:Declare a class called Currency .Open a file in output mode with a name.

Step 2:-Write new data into the object using writeobject() method.

Step 3:-Similarly create an input stream object .Read it both in terms of Dollars andRupees.close the output object.

Step 4:-derive a class called Dollar which implements serializable interface.Invoke a constructor and function to display the data.

Step 5:Similarly declare a class called Rupee with private variables and use print function to display the variables.

Page 17: (674335607) Cs2309-Java-Lab-Manual

Step 6:terminate the execution.The output is displayed as dollar to rupee conversion and vice versa.

Sourcecode:-

// Currency conversion import java.io.*;public class Currency{

public static void main(String args[]){

Dollar dr=new Dollar('$',40);dr.printDollar();Rupee re=new Rupee("Rs.",50);re.printRupee();try{File f=new File("rd.txt");FileOutputStream fos=new FileOutputStream(f); ObjectOutputStream oos=new ObjectOutputStream(fos); oos.writeObject(dr);oos.writeObject(re); oos.flush(); oos.close();ObjectInputStream ois=new ObjectInputStream(new FileInputStream("rd.txt")); Dollar d1;d1=(Dollar)ois.readObject();d1.printDollar(); Rupee r1; r1=(Rupee)ois.readObject(); r1.printRupee();ois.close();}catch(Exception e){}

}

}class Dollar implements Serializable{

private float dol;private char sym;

Page 18: (674335607) Cs2309-Java-Lab-Manual

public Dollar(char sm,float doll){

sym=sm;dol=doll;

}void printDollar(){

System.out.print(sym); System.out.println(dol);

}}class Rupee implements Serializable{

private String sym;private float rs;public Rupee(String sm,float rup){

sym=sm;rs=rup;

}void printRupee(){

System.out.print(sym); System.out.println(rs);

}

}

Output:-

E:\java>java Currency$40.0Rs.50.0$40.0Rs.50.0

Page 19: (674335607) Cs2309-Java-Lab-Manual

Ex No:7 Event-Driven Programming

AIM

To develop a scientific calculator using even-driven programming paradigm of Java.

ALGORITHM:

Step 1:-Import all the packages required for designing the graphical elements in the applet window.

Step 2:-Implement the Listener files for Keyboard, mouse events in the class defined.

Step 3:-Import the swing package in the program for using swing components for thr gridLayout design for menu,Frame,Dialog,TextArea,Label and other components for alignment in the appletwindow.

Step 4:-Create objects from the main classes forJLabel,Jtextbox,JPanel ,Font and Menu items.

Step 5:Assign the font items to all the menu items and add them to the panel.

Step 6:-Create the GridBagLayout and add all the buttons to it using the swing class.

Step 7:-Add all the JButtons to the panel and also the colour components to the GUI controls.

Step 8:-Call adddighitstodisplay() to activate the required arithmetic operations when the buttons are pressed.

Step 9:Invoke the function displayresult() to store the result of the values computed.

Step 10:-Handle the divide by zero exception outside the class definition. And create an object for the class created.

Step 11:-Add all the methods,properties and layout to the panel window and display the result in the textarea created.

Page 20: (674335607) Cs2309-Java-Lab-Manual

Step 12:-Invoke the actionPerformed() method through the ActionEvent class and write code for each operator or number being pressed.

SOURCE CODE:=-

import java.awt.BorderLayout;import java.awt.Color; import java.awt.Container; import java.awt.FlowLayout; import java.awt.Font;import java.awt.GridLayout;import java.awt.Window;import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;

import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.KeyStroke;

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[];

Page 21: (674335607) Cs2309-Java-Lab-Manual

private JPanel jplMaster, jplBackSpace, jplControl;

size.

/** Font(String name, int style, int size)Creates a new Font from the specified name, style and point

*/

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

// Constructor public Calculator(){

/* Set Up the JMenuBar.* Have Provided All JMenu's with Mnemonics* Have Provided some JMenuItem components with Keyboard

Accelerators*/

jmenuFile = new JMenu("File"); jmenuFile.setFont(f121); jmenuFile.setMnemonic(KeyEvent.VK_F);

jmenuitemExit = new JMenuItem("Exit");jmenuitemExit.setFont(f12);

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

ActionEvent.CTRL_MASK));jmenuFile.add(jmenuitemExit);

jmenuHelp = new JMenu("Help"); jmenuHelp.setFont(f121); jmenuHelp.setMnemonic(KeyEvent.VK_H);

jmenuitemAbout = new JMenuItem("About Calculator"); jmenuitemAbout.setFont(f12); jmenuHelp.add(jmenuitemAbout);

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

Page 22: (674335607) Cs2309-Java-Lab-Manual

jlbOutput.setBackground(Color.WHITE);jlbOutput.setOpaque(true);

// Add components to frame getContentPane().add(jlbOutput, BorderLayout.NORTH);

jbnButtons = new JButton[23];// GridLayout(int rows, int cols, int hgap, int vgap)

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

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

else

Page 23: (674335607) Cs2309-Java-Lab-Manual

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 rowfor(int i=7; i<=9; i++) {

jplButtons.add(jbnButtons[i]);}

// add button / and sqrt jplButtons.add(jbnButtons[13]); jplButtons.add(jbnButtons[17]);

// Second rowfor(int i=4; i<=6; i++){

jplButtons.add(jbnButtons[i]);}

// add button * and x^2 jplButtons.add(jbnButtons[14]); jplButtons.add(jbnButtons[18]);

// Third rowfor( int i=1; i<=3; i++){

jplButtons.add(jbnButtons[i]);}

//adds button - and % jplButtons.add(jbnButtons[15]); jplButtons.add(jbnButtons[19]);

//Fourth Row// add 0, +/-, ., +, and = jplButtons.add(jbnButtons[0]); jplButtons.add(jbnButtons[10]); jplButtons.add(jbnButtons[11]); jplButtons.add(jbnButtons[16]); jplButtons.add(jbnButtons[12]);

jplMaster.setLayout(new BorderLayout()); jplMaster.add(jplBackSpace, BorderLayout.WEST); jplMaster.add(jplControl, BorderLayout.EAST); jplMaster.add(jplButtons, BorderLayout.SOUTH);

// Add components to frame getContentPane().add(jplMaster, BorderLayout.SOUTH); requestFocus();

//activate ActionListener

Page 24: (674335607) Cs2309-Java-Lab-Manual

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

// Perform actionpublic void actionPerformed(ActionEvent e){

double result = 0;

if(e.getSource() == jmenuitemAbout){JDialog dlgAbout = new CustomABOUTDialog(this,

"About Java SwingCalculator", true);

dlgAbout.setVisible(true);}else if(e.getSource() == jmenuitemExit){

System.exit(0);}

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

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

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

switch(i){

case 0: addDigitToDisplay(i); break;

case 1: addDigitToDisplay(i); break;

case 2: addDigitToDisplay(i); break;

case 3:

Page 25: (674335607) Cs2309-Java-Lab-Manual

addDigitToDisplay(i);break;

case 4: addDigitToDisplay(i); break;

case 5: addDigitToDisplay(i); break;

case 6: addDigitToDisplay(i); break;

case 7: addDigitToDisplay(i); break;

case 8: addDigitToDisplay(i); break;

case 9: addDigitToDisplay(i); break;

case 10: // +/- processSignChange(); break;

case 11: // decimal point addDecimalPoint(); break;

case 12: // = processEquals(); break;

case 13: // divide processOperator("/"); break;

case 14: // * processOperator("*"); break;

case 15: // - processOperator("-"); break;

case 16: // + processOperator("+"); break;

Page 26: (674335607) Cs2309-Java-Lab-Manual

case 17: // sqrtif (displayMode != ERROR_MODE){

try{

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

displayError("Invalid input for function!");

result = Math.sqrt(getNumberInDisplay());displayResult(result);

}

catch(Exception ex){

displayError("Invalid input for function!”);displayMode = ERROR_MODE;

}}break;

case 18: // 1/xif (displayMode != ERROR_MODE){

try{

if(getNumberInDisplay() == 0)

displayError("Cannot divide by zero!");

getNumberInDisplay();result = 1 /

displayResult(result);}

divide by zero!");

ERROR_MODE;

catch(Exception ex) {displayError("Cannot

displayMode =

}}break;

getNumberInDisplay() / 100;

case 19: // %if (displayMode != ERROR_MODE){

try {result =

displayResult(result);}

Page 27: (674335607) Cs2309-Java-Lab-Manual

input for function!");

ERROR_MODE;

catch(Exception ex) {displayError("Invalid

displayMode =

}}break;

case 20: // backspaceif (displayMode != ERROR_MODE){

setDisplayString(getDisplayString().substring(0,

getDisplayString().length() - 1));

(getDisplayString().length() < 1)

}

if

setDisplayString("0");

break;

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

String inputString = getDisplayString();

if (inputString.indexOf("0") == 0){inputString = inputString.substring(1);

}

if ((!inputString.equals("0") || digit > 0)

Page 28: (674335607) Cs2309-Java-Lab-Manual

MAX_INPUT_LENGTH){&& inputString.length() <

setDisplayString(inputString + digit);}

displayMode = INPUT_MODE;clearOnNextDigit = false;

}

void addDecimalPoint(){displayMode = INPUT_MODE;

if (clearOnNextDigit)setDisplayString("");

String inputString = getDisplayString();

don't

}

// If the input string already contains a decimal point,

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

if (numberInDisplay != 0)displayResult(-numberInDisplay);

}}

void clearAll() { setDisplayString("0"); lastOperator = "0"; lastNumber = 0;

Page 29: (674335607) Cs2309-Java-Lab-Manual

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) {if (displayMode != ERROR_MODE){

double numberInDisplay = getNumberInDisplay();

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

try{

}

double result = processLastOperator();displayResult(result);lastNumber = result;

}

else{

}

catch (DivideByZeroException e){}

lastNumber = numberInDisplay;

clearOnNextDigit = true;lastOperator = op;

}}

void processEquals(){double result = 0;

if (displayMode != ERROR_MODE){try{

result = processLastOperator();displayResult(result);

}

Page 30: (674335607) Cs2309-Java-Lab-Manual

catch (DivideByZeroException e) {displayError("Cannot divide by zero!");

}

lastOperator = "0";}

}

double processLastOperator() throws DivideByZeroException {double result = 0;double numberInDisplay = getNumberInDisplay();

if (lastOperator.equals("/")){

if (numberInDisplay == 0)throw (new DivideByZeroException());

result = lastNumber / numberInDisplay;}

if (lastOperator.equals("*"))result = lastNumber * numberInDisplay;

if (lastOperator.equals("-"))result = lastNumber - numberInDisplay;

if (lastOperator.equals("+"))result = lastNumber + numberInDisplay;

return result;}

void displayResult(double result){ setDisplayString(Double.toString(result)); lastNumber = result;displayMode = RESULT_MODE;clearOnNextDigit = true;

}

void displayError(String errorMessage){ setDisplayString(errorMessage); lastNumber = 0;displayMode = ERROR_MODE;clearOnNextDigit = true;

}

public static void main(String args[]) { Calculator calci = new Calculator();Container contentPane = calci.getContentPane();

// contentPane.setLayout(new BorderLayout()); calci.setTitle("Java Swing Calculator"); calci.setSize(241, 217);calci.pack();calci.setLocation(400, 250);

Page 31: (674335607) Cs2309-Java-Lab-Manual

calci.setVisible(true);calci.setResizable(false);

}

} //End of Swing Calculator Class.

class DivideByZeroException extends Exception{public DivideByZeroException(){

super();}

public DivideByZeroException(String s){

super(s);}

}

class CustomABOUTDialog extends JDialog implements ActionListener { JButton jbnOk;

CustomABOUTDialog(JFrame parent, String title, boolean modal){super(parent, title, modal);setBackground(Color.black);

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

StringBuffer text = new StringBuffer();text.append("Calculator Demo Program\n\n");

JTextArea jtAreaAbout = new JTextArea(5, 21); jtAreaAbout.setText(text.toString()); jtAreaAbout.setFont(new Font("Times New Roman", 1, 13)); jtAreaAbout.setEditable(false);

p1.add(jtAreaAbout); p1.setBackground(Color.red); getContentPane().add(p1, BorderLayout.CENTER);

JPanel p2 = new JPanel(newFlowLayout(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)

Page 32: (674335607) Cs2309-Java-Lab-Manual

{Window aboutDialog = e.getWindow();aboutDialog.dispose();}});

pack();}

public void actionPerformed(ActionEvent e){if(e.getSource() == jbnOk) {this.dispose();}}

}

OUTPUT

Page 33: (674335607) Cs2309-Java-Lab-Manual

EX NO:-8 Multithreading

Aim:-

To write a multi-threaded Java program to print all numbers below 100,000 that are both prime and Fibonacci number(some examples are 2, 3, 5, 13, etc.). Design a thread that generates prime numbers below 100,000 and writes them into a pipe. Design another thread that generates fibonacci numbers and writes them to another pipe.The main thread should read both the pipes to identify numbers common to both.

ALGORITHM:

Step 1:-Include Dataoutputstream and pipedOutputStreamClasses in the program to accept numbers as input from user.

Step 2:-Create an object for class DataOutputStream to display the data.

Step 3:-Invoke the run() method to initiate the FOR loop and write the data into the object.

Step 4:Create a function called Fibonacci() and assign the previous,next and final values to display the series.

Step 5:-Create two objects for PipedInputStream and PipedOutputStream and inherit from the Thread class to generate prime numbers.

Step 6:Start the threads and handle the exceptions through the try-catch block.

Step 7:-Call the super class method in the subclass and give the code to check for the condition required for a number to be prime inside the run() method of the Thread class.

Step 8:-Write the list of prime numbers into the object created.Create another thread using the Thread class to write the Fibonacci series into another pipe.

Step 9:-Call the main thread in the main function through the ThreadGroup and read the data from the two separate objects for Fibonacci numbers and prime numbers.Identify the

Page 34: (674335607) Cs2309-Java-Lab-Manual

numbers common to both an dfinally display them.

SOURCE CODE

import java.io.DataOutputStream;import java.io.IOException;import java.io.PipedOutputStream;

public class FibonacciNumberGenerator extends Thread {private DataOutputStream dos;

public FibonacciNumberGenerator(ThreadGroup threadGroup,PipedOutputStream pis, String name){

super(threadGroup, name);dos = new DataOutputStream(pis);

}

@Overridepublic void run() {

try {

10000L){

for(int k=0; k<10000; k++){long fibonacciNum = fib(k);if(fibonacciNum > 0L && fibonacciNum <

dos.writeLong(fibonacciNum);dos.flush();

}}

} catch (IOException e) {}

}

public int fib(int n) {int prev1=0, prev2=1;for(int i=0; i<n; i++) {

int savePrev1 = prev1;prev1 = prev2;prev2 = savePrev1 + prev2;

}return prev1;

}

}

Page 35: (674335607) Cs2309-Java-Lab-Manual

import java.io.DataInputStream; import java.io.IOException; import java.io.PipedInputStream;import java.io.PipedOutputStream;

public class PipedStreamTester extends Thread {

DataInputStream fibonicPis;DataInputStream primePis;

public PipedStreamTester(PipedInputStream fibonicPis, PipedInputStream primePis){

this.fibonicPis = new DataInputStream(fibonicPis);this.primePis = new DataInputStream(primePis);

}

public static void main(String[] args) {try {

PipedOutputStream fibonicPos = newPipedOutputStream();

PipedInputStream fibonicPis = newPipedInputStream(fibonicPos);

PipedOutputStream primePos = newPipedOutputStream();

PipedInputStream primePis = newPipedInputStream(primePos);

ThreadGroup tg = new ThreadGroup("PipedThreads"); FibonacciNumberGenerator f = new

FibonacciNumberGenerator(tg, fibonicPos, "FibonacciNumberGenerator");

PrimeNumberGenerator p = newPrimeNumberGenerator(tg, primePos, "PrimeNumberGenerator");

PipedStreamTester mainTester = newPipedStreamTester(fibonicPis, primePis);

mainTester.start(); f.start();p.start();

} catch (IOException e) {e.printStackTrace();

}

}

/* (non-Javadoc)* @see java.lang.Thread#run()

Page 36: (674335607) Cs2309-Java-Lab-Manual

*/@Overridepublic void run() {

boolean canRun = true;boolean canGoPrimeLoop = true; boolean canGoFibonicLoop = true; Long primeNumber = -1L;Long fibonacciNumber = -1L;while(canRun){

if(fibonicPis != null && canGoFibonicLoop){

#>"+fibonacciNumber);

try {fibonacciNumber = fibonicPis.readLong(); System.out.println(" Fibonic Number

} catch (IOException e) {//System.err.println("Exception

occurred while reading from fibonacci number, "+e);canGoFibonicLoop = false;

}}

if(primePis != null && canGoPrimeLoop){try {

#>"+primeNumber);

primeNumber = primePis.readLong(); System.out.println(" Prime Number

} catch (IOException e) {//System.err.println("Exception

occurred while reading from prime number, "+e);canGoPrimeLoop = false;

}}

}}

}

import java.io.DataOutputStream;import java.io.IOException;import java.io.PipedOutputStream;

public class PrimeNumberGenerator extends Thread {

private DataOutputStream dos;public PrimeNumberGenerator (ThreadGroup threadGroup,

PipedOutputStream pos, String name){super(threadGroup, name);dos = new DataOutputStream(pos);

}

Page 37: (674335607) Cs2309-Java-Lab-Manual

@Overridepublic void run() {

try {int x, y, c = 0;for( x = 2; x < 10000; x++ ){

if( x % 2 != 0 || x == 2 ){for( y = 2; y <= x / 2; y++ ){

if( x % y == 0 ){break;

}}if( y > x / 2 ){

if(x < 10000){ dos.writeLong(x); dos.flush();

}}

}}

} catch (IOException e) {}

}}

OUTPUT

Fibonic Number #>1Prime Number #>2Fibonic Number #>1Prime Number #>3Fibonic Number #>2Prime Number #>5Fibonic Number #>3Prime Number #>7Fibonic Number #>5Prime Number #>11Fibonic Number #>8Prime Number #>13Fibonic Number #>13Prime Number #>17Fibonic Number #>21Prime Number #>19Fibonic Number #>34Prime Number #>23Fibonic Number #>55Prime Number #>29

Page 38: (674335607) Cs2309-Java-Lab-Manual

Fibonic Number #>89Prime Number #>31Fibonic Number #>144Prime Number #>37Fibonic Number #>233Prime Number #>41Fibonic Number #>377Prime Number #>43Fibonic Number #>610Prime Number #>47Fibonic Number #>987Prime Number #>53Fibonic Number #>1597Prime Number #>59Fibonic Number #>2584Prime Number #>61Fibonic Number #>4181Prime Number #>67Fibonic Number #>6765Prime Number #>71Prime Number #>73Prime Number #>79Prime Number #>83Prime Number #>89Prime Number #>97Prime Number #>101Prime Number #>103Prime Number #>107Prime Number #>109Prime Number #>113Prime Number #>127Prime Number #>131Prime Number #>137Prime Number #>139Prime Number #>149Prime Number #>151Prime Number #>157Prime Number #>163Prime Number #>167Prime Number #>173Prime Number #>179Prime Number #>181Prime Number #>191Prime Number #>193Prime Number #>197Prime Number #>199Prime Number #>211Prime Number #>223Prime Number #>227Prime Number #>229Prime Number #>233Prime Number #>239

Page 39: (674335607) Cs2309-Java-Lab-Manual

Prime Number #>241Prime Number #>251Prime Number #>257Prime Number #>263Prime Number #>269Prime Number #>271Prime Number #>277Prime Number #>281Prime Number #>283Prime Number #>293Prime Number #>307Prime Number #>311Prime Number #>313Prime Number #>317Prime Number #>331Prime Number #>337

Page 40: (674335607) Cs2309-Java-Lab-Manual

Ex No:9 Java Database Connectivity

Aim:-To develop a simple OPAC System for library management system using event-driven and concurrent programming paradigms and java database connectivity.

Algorithm:-

Step 1:Initiate a class and declare the driver for the Driver name required to connect to the database.

Step 2:-Enclose the coding in a try block to handle errors and trap the exception in a catch block.

Step 3:-Establish the connection object to connect to the backend.

Step 4:-Create an object for Statement object using createStatement() object.

Step 5:-Issue a query through executeQuery() method.

Source code:-

Page 41: (674335607) Cs2309-Java-Lab-Manual

Import java.awt.*; Import javax.swing.*; Import java.awt.event.*; Import java.sql.*;Public class Jdbcapplet extends JApplet implementsActionListener,ItemListener{JTextField t1,t2;Container contentPane=getContentPane();JLabel l1,l2,l3; JButton save; JPanel p1,p2; JCheckBox c[];String selected=””; Public void init(){contentPane.setLayout(new FlowLayout()); T1=new JTextField(20);T2=new JTextField(20);L1=new JLabel(“enter name:”);L2=new JLabel(“enter occupation”); P1=new JPanel();P1.setLayout(new GridLayout(2,2)); P1.add(l1);P1.add(t1); P1.add(l2); P1.add(t2); P2=new JPanel();P2.setLayout(new GridLayout(8,1)); P2.add(new JLabel(“which os do u use?”)); C=new JCheckbox[6];For(int i=0;i<=5;i++){C[i]=new JCheckBox(“”,false);P2.add(c[i]); C[i].addItemListener(this);}C[0].setText(“complete reference”);;

Ex:10.Multi-threaded Echo Server and Client in Java.

Aim:-To develop a Java Program that supports multithreaded echo server and a GUI client.

Page 42: (674335607) Cs2309-Java-Lab-Manual

Algorithm:-

Step 1:-Import the net package which supports networking features in Java.

Step 2:-Write the input data into an object from the keyboard through BufferedStream class.

Step 3:-Create a new object for Socket s and Write the input data into another object called dos using writeBytes() method.

Step 4:-Read the copied string into br using readLine() method and close the file.

Step 5:-On executing the program,the server sends a message to the client.

Step 6:-For the server side program, create an object forServerSocket class and write input data into it.

Step 7:-Write the data into the dataoutputstream object dos.

Step 8:-close the object and socket.

// Client Program:-

import java.net.*; import java.io.*; class Client{

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

Socket soc=null; String str=null; BufferedReader br=null; DataOutputStream dos=null;BufferedReader kyrd=new BufferedReader(new InputStreamReader(System.in));try{

soc=new Socket(InetAddress.getLocalHost(),95);br=new BufferedReader(new InputStreamReader(soc.getInputStream()));dos=new DataOutputStream(soc.getOutputStream());

}catch(UnknownHostException uhe)

Page 43: (674335607) Cs2309-Java-Lab-Manual

{System.out.println("Unknown Host"); System.exit(0);

}System.out.println("To start the dialog type the message in this client window \n

Type exit to end"); boolean more=true; while(more){

str=kyrd.readLine(); dos.writeBytes(str); dos.write(13); dos.write(10); dos.flush();String s,s1; s=br.readLine(); System.out.println("From server :"+s); if(s.equals("exit"))

break;}br.close(); dos.close(); soc.close();

}}Output:-

E:\java>java ClientTo start the dialog type the message in this client windowType exit to end helloFrom server :hello

how are youFrom server :how are you how are youFrom server :how are you exitFrom server :exit

// Server Program

Page 44: (674335607) Cs2309-Java-Lab-Manual

import java.net.*; import java.io.*; class Server{

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

ServerSocket ss=null;try{

ss=new ServerSocket(95);}catch(IOException ioe){

System.out.println("Error finding port"); System.exit(1);

}Socket soc=null;try{

soc=ss.accept();System.out.println("Connection accepted at :"+soc);

}catch(IOException ioe){

System.out.println("Server failed to accept"); System.exit(1);

}DataOutputStream dos=new DataOutputStream(soc.getOutputStream()); BufferedReader br=new BufferedReader(new

InputStreamReader(soc.getInputStream())); String s;System.out.println("Server waiting for message from tthe client");boolean quit=false;do{String msg=""; s=br.readLine(); int len=s.length();if(s.equals("exit"))quit=true;for(int i=0;i<len;i++){ msg=msg+s.charAt(i); dos.write((byte)s.charAt(i));

}

Page 45: (674335607) Cs2309-Java-Lab-Manual

System.out.println("From client :"+msg);dos.write(13); dos.write(10); dos.flush();

}while(!quit); dos.close(); soc.close();

}}

Output:-

E:\java>java ServerConnection accepted at :Socket[addr=/127.0.0.1,port=49442,localport=95] Server waiting for message from tthe clientFrom client :helloFrom client :how are you From client :how are you From client :exit