cs2309 java lab manual2
DESCRIPTION
javaTRANSCRIPT
![Page 1: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/1.jpg)
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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/2.jpg)
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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/3.jpg)
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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/4.jpg)
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();
System.out.println("Date object showing specific date and time"); Date particulardate1 = new Date(24L*60L*60L*1000L); Date particulardate2 = new Date(0L); System.out.println(); System.out.println("First Particular date : " + particulardate1); System.out.println("Second Particular date: " + particulardate2); System.out.println();
System.out.println("Demo of getTime() method returning milliseconds"); 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 + " milliseconds"); System.out.println();
System.out.println("Changed date object using setTime() method"); 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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/5.jpg)
}
OUTPUT
Current Date and Time is : Mon Dec 10 18:39:27 GMT+05:30 2007
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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/6.jpg)
Ex4 : Implementation of Stack ADT
AIM
To write a Java Program to design an interface for Stack ADT.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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/7.jpg)
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. */
![Page 8: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/8.jpg)
public void pop( ) { 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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/9.jpg)
//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.
![Page 10: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/10.jpg)
* @throws UnderflowException if the stack is empty. */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 ) {
![Page 11: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/11.jpg)
element = theElement;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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/12.jpg)
public static void main(String[] args) {
System.out.println("******************************************");System.out.println("Stack using Array & Linked List
example");
System.out.println("******************************************");
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,
c");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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/13.jpg)
}}
/** * 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, cStack 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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/14.jpg)
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 inheritedpublic class Vehicle{ public int doors; public int seats; public int wheels; Vehicle() {
wheels=4; doors=4;
seats=4; }}//This class inherits Vehicle.javapublic class Car extends Vehicle{
![Page 15: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/15.jpg)
public String toString() {
return "This car has "+seats+" Seats, "+doors+" Doors "+ "and "+wheels+" wheels.";
}}//This class inherits Vehicle.javapublic 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.javapublic 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[]) {
![Page 16: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/16.jpg)
MotorCycle mine = new MotorCycle();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 wheelsThis car has 4 Seats, 2 Doors and 4 wheelsThis pickup has 4 Seats, 4 Doors and 4 wheelsThis 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 and Rupees.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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/17.jpg)
Step 6:terminate the execution.The output is displayed as dollar to rupee conversion and vice versa.
Sourcecode:-
// Currency conversionimport 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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/18.jpg)
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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/19.jpg)
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 applet window.
Step 4:-Create objects from the main classes for JLabel,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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/20.jpg)
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;
![Page 21: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/21.jpg)
private JButton jbnButtons[];private JPanel jplMaster, jplBackSpace, jplControl;
/* * 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));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");
![Page 22: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/22.jpg)
jlbOutput.setHorizontalTextPosition(JLabel.RIGHT);jlbOutput.setBackground(Color.WHITE);jlbOutput.setOpaque(true);
// Add components to framegetContentPane().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 Jbuttonsfor (int i=0; i<=9; i++){
// set each Jbutton label to the value of indexjbnButtons[i] = new JButton(String.valueOf(i));
}
// Create operator JbuttonsjbnButtons[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 Redfor (int i=0; i<jbnButtons.length; i++) {
jbnButtons[i].setFont(f12);
if (i<10)jbnButtons[i].setForeground(Color.blue);
![Page 23: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/23.jpg)
elsejbnButtons[i].setForeground(Color.red);
}
// Set panel layout manager for a 4 by 5 gridjplButtons.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 sqrtjplButtons.add(jbnButtons[13]);jplButtons.add(jbnButtons[17]);
// Second rowfor(int i=4; i<=6; i++){
jplButtons.add(jbnButtons[i]);}
// add button * and x^2jplButtons.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 framegetContentPane().add(jplMaster, BorderLayout.SOUTH);requestFocus();
![Page 24: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/24.jpg)
//activate ActionListenerfor (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 programaddWindowListener(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 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);break;
case 2:addDigitToDisplay(i);break;
![Page 25: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/25.jpg)
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;
case 8:addDigitToDisplay(i);break;
case 9:addDigitToDisplay(i);break;
case 10: // +/-processSignChange();break;
case 11: // decimal pointaddDecimalPoint();break;
case 12: // =processEquals();break;
case 13: // divideprocessOperator("/");break;
case 14: // *processOperator("*");break;
case 15: // -processOperator("-");break;
case 16: // +processOperator("+");
![Page 26: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/26.jpg)
break;
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!");
result = 1 / getNumberInDisplay();
displayResult(result);}
catch(Exception ex) {displayError("Cannot
divide by zero!");displayMode =
ERROR_MODE;}
}break;
case 19: // %if (displayMode != ERROR_MODE){
try {result =
getNumberInDisplay() / 100;displayResult(result);
}
![Page 27: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/27.jpg)
catch(Exception ex) {displayError("Invalid
input for function!");displayMode =
ERROR_MODE;}
}break;
case 20: // backspaceif (displayMode != ERROR_MODE){
setDisplayString(getDisplayString().substring(0,
getDisplayString().length() - 1));
if (getDisplayString().length() < 1)
setDisplayString("0");}break;
case 21: // CEclearExisting();break;
case 22: // CclearAll();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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/28.jpg)
&& 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
// 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));
elsesetDisplayString("-" + input);
}
}
else if (displayMode == RESULT_MODE){
double numberInDisplay = getNumberInDisplay();
if (numberInDisplay != 0)displayResult(-numberInDisplay);
}}
void clearAll() {setDisplayString("0");lastOperator = "0";lastNumber = 0;
![Page 29: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/29.jpg)
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;
}
catch (DivideByZeroException e){}
}
else{
lastNumber = numberInDisplay;}
clearOnNextDigit = true;lastOperator = op;
}}
void processEquals(){double result = 0;
if (displayMode != ERROR_MODE){try{
result = processLastOperator();displayResult(result);
}
![Page 30: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/30.jpg)
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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/31.jpg)
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(new FlowLayout(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(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)
![Page 32: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/32.jpg)
{Window aboutDialog = e.getWindow();aboutDialog.dispose();}});
pack();}
public void actionPerformed(ActionEvent e){if(e.getSource() == jbnOk) {this.dispose();}}
}
OUTPUT
![Page 33: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/33.jpg)
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 pipedOutputStream Classes 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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/34.jpg)
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 {for(int k=0; k<10000; k++){
long fibonacciNum = fib(k);if(fibonacciNum > 0L && fibonacciNum <
10000L){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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/35.jpg)
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 = new PipedOutputStream();
PipedInputStream fibonicPis = new PipedInputStream(fibonicPos);
PipedOutputStream primePos = new PipedOutputStream();
PipedInputStream primePis = new PipedInputStream(primePos);
ThreadGroup tg = new ThreadGroup("PipedThreads");FibonacciNumberGenerator f = new
FibonacciNumberGenerator(tg, fibonicPos, "FibonacciNumberGenerator");
PrimeNumberGenerator p = new PrimeNumberGenerator(tg, primePos, "PrimeNumberGenerator");
PipedStreamTester mainTester = new PipedStreamTester(fibonicPis, primePis);
mainTester.start();f.start();p.start();
} catch (IOException e) {e.printStackTrace();
}
}
/* (non-Javadoc) * @see java.lang.Thread#run()
![Page 36: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/36.jpg)
*/@Overridepublic void run() {
boolean canRun = true;boolean canGoPrimeLoop = true;boolean canGoFibonicLoop = true;Long primeNumber = -1L;Long fibonacciNumber = -1L;while(canRun){
if(fibonicPis != null && canGoFibonicLoop){
try {fibonacciNumber = fibonicPis.readLong();System.out.println(" Fibonic Number
#>"+fibonacciNumber);
} catch (IOException e) {//System.err.println("Exception occurred
while reading from fibonacci number, "+e);canGoFibonicLoop = false;
}}
if(primePis != null && canGoPrimeLoop){try {
primeNumber = primePis.readLong();System.out.println(" Prime Number
#>"+primeNumber);
} 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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/37.jpg)
@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 #>1 Prime Number #>2 Fibonic Number #>1 Prime Number #>3 Fibonic Number #>2 Prime Number #>5 Fibonic Number #>3 Prime Number #>7 Fibonic Number #>5 Prime Number #>11 Fibonic Number #>8 Prime Number #>13 Fibonic Number #>13 Prime Number #>17 Fibonic Number #>21 Prime Number #>19 Fibonic Number #>34 Prime Number #>23 Fibonic Number #>55 Prime Number #>29
![Page 38: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/38.jpg)
Fibonic Number #>89 Prime Number #>31 Fibonic Number #>144 Prime Number #>37 Fibonic Number #>233 Prime Number #>41 Fibonic Number #>377 Prime Number #>43 Fibonic Number #>610 Prime Number #>47 Fibonic Number #>987 Prime Number #>53 Fibonic Number #>1597 Prime Number #>59 Fibonic Number #>2584 Prime Number #>61 Fibonic Number #>4181 Prime Number #>67 Fibonic Number #>6765 Prime Number #>71 Prime Number #>73 Prime Number #>79 Prime Number #>83 Prime Number #>89 Prime Number #>97 Prime Number #>101 Prime Number #>103 Prime Number #>107 Prime Number #>109 Prime Number #>113 Prime Number #>127 Prime Number #>131 Prime Number #>137 Prime Number #>139 Prime Number #>149 Prime Number #>151 Prime Number #>157 Prime Number #>163 Prime Number #>167 Prime Number #>173 Prime Number #>179 Prime Number #>181 Prime Number #>191 Prime Number #>193 Prime Number #>197 Prime Number #>199 Prime Number #>211 Prime Number #>223 Prime Number #>227 Prime Number #>229 Prime Number #>233 Prime Number #>239
![Page 39: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/39.jpg)
Prime Number #>241 Prime Number #>251 Prime Number #>257 Prime Number #>263 Prime Number #>269 Prime Number #>271 Prime Number #>277 Prime Number #>281 Prime Number #>283 Prime Number #>293 Prime Number #>307 Prime Number #>311 Prime Number #>313 Prime Number #>317 Prime Number #>331 Prime Number #>337
![Page 40: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/40.jpg)
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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/41.jpg)
Import java.awt.*;Import javax.swing.*;Import java.awt.event.*;Import java.sql.*;Public class Jdbcapplet extends JApplet implements ActionListener,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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/42.jpg)
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 for ServerSocket 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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/43.jpg)
{ 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 window Type exit to endhelloFrom server :hello
how are youFrom server :how are youhow are youFrom server :how are youexitFrom server :exit
// Server Program
![Page 44: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/44.jpg)
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: Cs2309 Java Lab Manual2](https://reader031.vdocument.in/reader031/viewer/2022020716/5525431c4a795968498b4a95/html5/thumbnails/45.jpg)
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 youFrom client :how are youFrom client :exit