JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY ANANTAPUR
B.Tech. II-II Sem. (CSE)
OBJECT ORIENTED PROGRAMMING LAB
Objectives:
• To make the student learn an object oriented way of solving problems.
• To teach the student to write programs in Java to solve the problems
Recommended Systems/Software Requirements:
• Intel based desktop PC with minimum of 166 MHZ or faster processor with at least 64 MB RAM and 100 MB free disk space
• JDK Kit. Recommended
Week1:
a) Write a Java program that prints all real solutions to the quadratic equation ax2 + bx + c = 0. Read in
a, b, c and use the quadratic formula. If the discriminant b2 -4ac is negative, display a message
stating that there are no real solutions.
b) The Fibonacci sequence is defined by the following rule:
The first two values in the sequence are 1 and 1. Every subsequent value is the sum of the two
Values preceding it. Write a Java program that uses both recursive and non recursive functions to
print the nth value in the Fibonacci sequence.
Week 2 :
a) Write a Java program that prompts the user for an integer and then prints out all prime numbers
up to that integer.
b) Write a Java program to multiply two given matrices.
c) Write a Java Program that reads a line of integers, and then displays each integer, and the sum of
All the integers (Use StringTokenizer class of java.util)
Week 3:
a) Write a Java program that checks whether a given string is a palindrome or not. Ex: MADAM is a
Palindrome.
b) Write a Java program for sorting a given list of names in ascending order.
c) Write a Java program to make frequency count of words in a given text.
Week 4:
a) Write a Java program that reads a file name from the user, then displays information about
whether the file exists, whether the file is readable, whether the file is writable, the type of file and
the length of the file in bytes.
b) Write a Java program that reads a file and displays the file on the screen, with a line number before
each line.
c) Write a Java program that displays the number of characters, lines and words in a text file.
Week 5 :
a) Write a Java program that:
i) Implements stack ADT.-
ii) Converts infix expression into Postfix form
iii) Evaluates the postfix expression
Week 6:
a) Develop an applet that displays a simple message.
b) Develop an applet that receives an integer in one text field, and computes its factorial Value and returns it in another text field, when the button named “Compute” is clicked.
Week 7:
Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons for the digits and for the +, -,*, % operations. Add a text field to display the result.
Week 8:
a) Write a Java program for handling mouse events.
Week 9:
a) Write a Java program that creates three threads. First thread displays “Good Morning” every one
second, the second thread displays “Hello” every two seconds and the third thread displays
“Welcome” every three seconds.
b) Write a Java program that correctly implements producer consumer problem using the concept of
inter thread communication.
Week 10:
A. Write a program that creates a user interface to perform integer divisions. The user enters two numbers in the textfields, Num1 and Num2. The division of Num1 and Num2 is displayed in the Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program would throw a NumberFormatException. If Num2 were Zero, the program would throw an ArithmeticException Display the exception in a message dialog box.
Week 11:
A. Write a Java program that implements a simple client/server application. The client sends data to a server. The server receives the data, uses it to produce a result, and then sends the result back to the client. The client displays the result on the console. For ex: The data sent from the client is the radius of a circle, and the result produced by the server is the area of the circle. (Use java.net)
Week 12:
a) Write a java program that simulates a traffic light. The program lets the user select one of three
Lights: red, yellow, or green. When a radio button is selected, the light is turned on, and only one
light can be on at a time No light is on when the program starts.
b) Write a Java program that allows the user to draw lines, rectangles and ovals.
Week 13:
a) Write a java program to create an abstract class named Shape that contains an empty method
named numberOfSides ( ).Provide three classes named Trapezoid, Triangle and Hexagon such that
each one of the classes extends the class Shape. Each one of the classes contains only the method
numberOfSides ( ) that shows the number of sides in the given geometrical figures.
b) Suppose that a table named Table.txt is stored in a text file. The first line in the file is the header, and the remaining lines correspond to rows in the table. The elements are eparated by commas. Write a java program to display the table using Jtable component.
TEXT BOOKS :
1. Java How to Program, Sixth Edition, H.M.Dietel and P.J.Dietel, Pearson Education/PHI.
2. Introduction to Java programming, Sixth edition, Y.Daniel Liang, Pearson Education.
3. Big Java, 2nd edition, Cay Horstmann, Wiley Student Edition, Wiley India Private Limited.
4. Introduction to Programming with Java, J.Dean & R.Dean, McGraw Hill education.
5. Java Programming, D S Malik, cengage learning, India Edition.
OBJECT ORIENTED PROGRAMMING LAB
INDEX
S.No Program Name Page No
1. Quadratic Equation
2. Fibonacci Sequence Generation
3. Prime Number Generation
4. Matrix Multiplication
5. Sum of Integers
6. Palindrome Checking
7. String Sorting
8. Word Count
9. File Reader
10. Text file Processing
11. Stack ADT
12. Infix to Postfix Conversion
13. Expression Evaluation
14. Applets
15. Calculator
16. Event Handling
17. Threads
18. Exception Handling
19. Socket Implementation
20. Traffic Light Simulation
Program 1 Quadratic Equation
Write a Java program that prints all real solutions to the quadratic equation ax2+bx+c=0. Read in a, b, c and use the quadratic formula. If the discriminant b2 -4ac is negative, display a message stating that there are no real solutions.
import java.io.*;
class Quadratic
{
public static void main(String args[])throws IOException
{
int a,b,c,disc;
double x1,x2;
InputStreamReader obj=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(obj);
System.out.println("enter a,b,c values");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
c=Integer.parseInt(br.readLine());
disc=(b*b)-(4*a*c);
if(disc==0)
{
System.out.println("roots are real and equal ");
x1=x2=-b/(2*a);
System.out.println("roots are "+x1+","+x2);
}
else if(disc>0)
{
System.out.println("roots are real and unequal");
x1=(-b+Math.sqrt(disc))/(2*a);
x2=(-b+Math.sqrt(disc))/(2*a);
System.out.println("roots are "+x1+","+x2);
}
else
{
System.out.println("roots are imaginary");
}
}
Output
// Compilation
C:\nagarjuna>javac Quadratic.java
C:\nagarjuna>java Quadratic
Enter a,b,c Values : 10 3 6
Roots are Imaginary
Program 2 Fibonacci sequence Generation
A) Java program to find all the Fibonacci sequence using non-recursive.
import java.io.*;
import java.lang.*;
class Demo
{
int a=0,b=1,c,i=1;
void fib(int n)
{
System.out.println("Fibonacci Sequence : ");
System.out.println(" "+a);
System.out.println(" "+b);
while(i<=n-2)
{
c=a+b;
System.out.println(" "+c);
a=b;
b=c;
i++;
}
}
}
class FibonacciDemo
{
public static void main(String args[])throws IOException
{
InputStreamReader obj=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(obj);
System.out.println("enter last number");
int n=Integer.parseInt(br.readLine());
Demo ob=new Demo();
ob.fib(n);
}
}
Output
// Compilation
C:\nagarjuna>javac FibonacciDemo.java
C:\nagarjuna>java Quadratic
Give Length of Sequence: 5
Fibonacci Sequence: 0 1 1 2 3
B) A java program to find all the Fibonacci sequence using recursive
import java.io.*;
import java.lang.*;
class Demo
{
int fib(int n)
{
if(n==1)
return (0);
else if(n==2)
return (1);
else
return (fib(n-1)+fib(n-2));
}
}
class RecursiveFibDemo
{
public static void main(String args[])throws IOException
{
InputStreamReader obj=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(obj);
System.out.println("enter last number");
int n=Integer.parseInt(br.readLine());
Demo ob=new Demo();
System.out.println("fibonacci series is as follows");
for(int i=1;i<=n;i++)
{
int res=ob.fib(i);
System.out.println(" "+res);
}
}
}
Output
// Compilation
C:\nagarjuna>javac RecursiveFibDemo.java
C:\nagarjuna>java RecursiveFibDemo
Enter Last No : 5
Fibonacci Sequence : 1 1 2 3 5
Program – 3 Prime Number Generations
Write a Java program that prompts the user for an integer and then prints out all prime numbers up to that integer.
import java.io.*;
import java.lang.*;
class Demo
{
int step,i,k;
void prime(int n)
{
System.out.println("prime numbers are as follows");
for(i=2;i<=n;i++)
{
step=1;
for(k=2;k<=(i/2);k++)
{
if(i%k==0)
step=0;
}
if (step==1)
System.out.println(" "+i);
}
}
}
class PrimeDemo
{
public static void main(String args[])throws IOException
{
InputStreamReader obj=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(obj);
System.out.println("enter last number");
int n=Integer.parseInt(br.readLine());
Demo ob=new Demo();
ob.prime(n);
}
}
Output
// Compilation
C:\nagarjuna>javac PrimeDemo.java
C:\nagarjuna>java PrimeDemo
Enter Last Number : 7
Prime Numbers : 2 3 5 7
Program 4 Matrix Multiplication
Write a Java program to multiply two given matrices.
import java.io.*;
class matmul
{
public static void main(String args[]) throws IOException
{
int i,j,k,m,n,p,q;
int a[][],b[][],c[][];
InputStreamReader obj=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(obj);
System.out.println("Give Matrix A Size\n");
m=Integer.parseInt(br.readLine());
n=Integer.parseInt(br.readLine());
a=new int[m][n];
System.out.println("Enter Matrix A : ");
for(i=0;i
for(j=0;j
}
System.out.println("Give Matrix B Size ");
p=Integer.parseInt(br.readLine());
q=Integer.parseInt(br.readLine());
b=new int[p][q];
System.out.println("Enter Matrix B");
for(i=0;i
{
for(j=0;j
for(j=0;j
b[i][j]=Integer.parseInt(br.readLine());
}
c=new int[m][n];
if(n==p)
{
for(i=0;i{ for(j=0;j { for(k=0;kc[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
System.out.println("Matrix Multiplication ");
for(i=0;i{
for(j=0;j{
System.out.print(" "+c[i][j]);
}
System.out.println(" ");
}
}
else
System.out.println("matrix multiplication is not possible");
}
}
Output
// Compilation
C:\nagarjuna>javac matmul.java
C:\nagarjuna>java matmul
Give Matrix A Size
2 2
Enter Matrix A :
4 3 2 4
Give Matrix B Size
2 2
Enter Matrix A :
2 2 5 3
Matrix Multiplication
23 17
24 16
Program 5 Sum of Integers
Write a Java Program that reads a line of integers, and then displays each integer, and the sum of all the integers (Use StringTokenizer class of java.util)
import java.lang.*;
import java.util.*;
class tokendemo
{
public static void main(String args[])
{
String s="10,20,30,40,50";
int sum=0;
StringTokenizer a=new StringTokenizer(s,",",false);
System.out.println("integers are ");
while(a.hasMoreTokens())
{
int b=Integer.parseInt(a.nextToken());
sum=sum+b;
System.out.println(" "+b);
}
System.out.println("sum of integers is "+sum);
}
}
Output
// Compilation
C:\nagarjuna>javac tokenDemo.java
C:\nagarjuna>java tokenDemo
Integers are
10 20 30 40
Sum of integers are 100
Program 6 Palindrome Checking
Write a Java program that checks whether a given string is a palindrome or not. Ex: MADAM is a palindrome.
class demo
{
boolean ispalin(String word)
{
int left=0;
int right=word.length()-1;
while(left{
if(word.charAt(left)!=word.charAt(right))
return false;
left++;
right--;
}
return true;
}
}
class palindemo
{
public static void main(String args[])
{
System.out.println("Enter Word to check”);
String s=args[0];
demo obj=new demo();
boolean flag=obj.ispalin(s);
if(flag==true)
System.out.println("palindrome");
else
System.out.println("not palindrome");
}
}
Output
// Compilation
C:\nagarjuna>javac palindemo.java
C:\nagarjuna>java palindemo
Enter Word to check : madam
Palindrome
Program 7 Name Sorting
Write a Java program for sorting a given list of names in ascending order.
import java.util.*;
class demo
{
int i,j;
void stringsort(String a[],int n)
{
String temp;
for(i=0;ifor(j=i+1;j {
if(a[i].compareTo(a[j])>0)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}}}
class stringsortdemo
{
public static void main(String args[])
{
int i;
String a[];
String s="rama,sita,rahul,prem,aryan,pooja,siddu";
demo obj=new demo();
StringTokenizer st=new StringTokenizer(s,",",false);
int n=st.countTokens();
a=new String[n];
for(i=0;i<=n-1;i++)
a[i]=st.nextToken();
obj.stringsort(a,n);
System.out.println("sorted strings are as follows");
for(i=0;iSystem.out.println(a[i]);
}
}
Output
// Compilation
C:\nagarjuna>javac PrimeDemo.java
C:\nagarjuna>java PrimeDemo
Sorted Strings are
Aryan, pooja, prem, rama,rahul,siddu,sita
Program 8 File Processing
Write a Java program that reads a file name from the user, then displays information about whether the file exists, whether the file is readable, whether the file is writable, the type of file and the length of the file in bytes.
import java.io.*;
import java.util.*;
class filedemo
{
public static void main(String args[])
{
File f=new File(args[0]);
System.out.println("name :"+f.getName());
System.out.println("path:"+f.getAbsolutePath());
System.out.println("exists:"+f.exists());
System.out.println("is file:"+f.isFile());
System.out.println("is dir:"+f.isDirectory());
System.out.println("read :"+f.canRead());
System.out.println("write:"+f.canWrite());
long l=f.lastModified();
Date d=new Date(l);
int date=d.getDate();
int month=d.getMonth();
int year=d.getYear();
int hh=d.getHours();
int mm=d.getMinutes();
int ss=d.getSeconds();
System.out.println(date+"/"+(month+1)+"/"+(1900+year));
System.out.println(hh+":"+mm+":"+ss);
} }
Output
C:\nagarjuna>javac filedemo.java
C:\ nagarjuna >java filedemo stringsortdemo.java
name :stringsortdemo.java
path:C:\javapgms\checkboxdemo.java
exists:true
is file:true
is dir:false
read :true
write:true
hidden:false
3/13/2007
14:37:45
Program 9 Character Count
Write a Java program that displays the number of characters
import java.io.*;
public class buff
{
public static void main(string args[])
{
int ctr=0;
FileInputStream fis= new FileInputStream(buff.txt);
BufferedInputStream bis=new BufferedInputStream(fis);
int x=bis.read();
while(x!=-1)
{
System.out.print((char)x);
ctr++;
x=bis.read();
}
System.out.println( "Number of characters present in a file="+ctr);
}
}
Output
C:\nagarjuna>javac buff.java
C:\ nagarjuna >java buff
Number of characters present in a file = 10
Program 10 Stack ADT
Write a Java program that Implements stack ADT.
import java.io.*;
interface stack
{
void push(int item);
int pop();
}
class stackimpl
{
private int stck[];
private int top;
stackimpl(int size)
{
stck=new int[size];
top=-1;
}
void push(int item)
{
if(top==stck.length-1)
System.out.println("stack is full insertion is not possible");
else
{
stck[++top]=item;
System.out.println("number is inserted");
}
}
int pop( )
{
if(top==-1)
{
System.out.println("stack is empty deletion is not possible");
return 0;
}
else
return stck[top--];
}
}
class stackdemo
{
public static void main(String args[])throws IOException
{
int a[];
InputStreamReader obj=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(obj);
System.out.println("Enter size of Stack ");
int n=Integer.parseInt(br.readLine());
stackimpl obj1=new stackimpl(n);
a=new int[n];
System.out.println("Enter elements into Stack");
for(int i=0;ia[i]=Integer.parseInt(br.readLine());
for(int i=0;iobj1.push(a[i]);
System.out.println("Stack contents are as follows");
for(int i=0;iSystem.out.println(" "+obj1.pop());
}
}
Output
C:\nagarjuna>javac stackdemo.java
C:\ nagarjuna >java stackdemo
Enter size of Stack 4
Enter elements into Stack
10 20 30 40
Stack contents are as follows
10 20 30 40
Program 11 Runtime Polymorphism
Write a Java program to demonstrate Runtime Polymorphism
class Figure
{
double dim1;
double dim2;
Figure(double a,double b)
{
dim1=a;
dim2=b;
}
double area()
{
System.out.println("Area of the figure is Undefined");
return 0;
}
}
class Rectangle extends Figure
Rectangle(double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("Inside area for Rectangle is");
return dim1*dim2;
}
}
class Triangle extends Figure
{
Triangle(double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("Inside area of Triangle is");
return (dim1*dim2)/2;
}
}
class FindArea
{
public static void main(String args[])
{
Figure f=new Figure(10,10);
Rectangle r=new Rectangle(9,5);
Triangle t=new Triangle(10,8);
Figure figref;
figref=r;
System.out.println("Area "+figref.area());
figref=t;
System.out.println("Area "+figref.area());
figref=f;
System.out.println("Area "+figref.area());
}
}
Output
C:\nagarjuna>javac FindArea.java
C:\ nagarjuna >java FindArea
Inside area for Rectangle is
Area 45.0
Inside area of Triangle is
Area 40.0
Area of the figure is Undefined
Area 0.0
Program 12 Applet
Develop an applet that displays a simple message.
import java.applet.*;
import java.awt.*;
public class draw extends Applet
{
public void paint(Graphics g)
{
g.drawString("hello",50,50);
}
}
Program 13
Write an applet to display 10 concentric circles
import java.applet.*;
import java.awt.*;
public class circ extends Applet
{
public void paint(Graphics g)
{
for(int i=1;i<=10;i++)
g.drawOval(110-10*i,110-10*i,20*i,20*i);
}
}
Program 14
Write an applet to display 10 Intersecting 1) Lines or 2) Rectangles, or 3) Ovals
import javax.swing.*;
import java.awt.Graphics;
public class choice extends JApplet
{
int i,ch;
public void init()
{
String input;
input=JOptionPane.showInputDialog("EnterChoice(1-lines,2-rectangles,3-ovals)");
ch=Integer.parseInt(input);
}
public void paint(Graphics g)
{
switch(ch)
{
case 1:
{
for(i=1;i<=10;i++)
g.drawLine(10,10,250,10*i);
break;
}
case 2:
{
for(i=1;i<=10;i++)
g.drawRect(10*i,10*i,50+10*i,50+10*i);
break;
}
case 3:
{
for(i=1;i<=10;i++)
g.drawOval(10*i,10*i,50+10*i,50+10*i);
break;
}
}
}
}
Program 15 Calculator
Write a Java program that works as simple calculator. Use a grid layout to arrange buttons for the digits and for the +, -,*, % operations. Display the result in Text Field
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener
{
JLabel a[];
JTextField b[];
JButton d[];
JPanel pan;
public static void main(String args[])
{
new Calculator();
}
public Calculator()
{
int i;
Container c=getContentPane();
c.setLayout(new GridLayout(3,2));
pan=new JPanel();
pan.setLayout(new GridLayout(1,8));
a=new JLabel[3];
b=new JTextField[3];
d=new JButton[8];
for(i=0;i<=a.length-1;i++)
{
a[i]=new JLabel();
b[i]=new JTextField(10);
b[i].addActionListener(this);
c.add(a[i]);
c.add(b[i]);
}
a[0].setText("first number");
a[1].setText("second number");
a[2].setText("result");
b[2].setEditable(false);
for(i=0;i<=d.length-1;i++)
{
String names[]={"+","-","*","/","%","sqrt","pow","exit"};
d[i]=new JButton(names[i]);
pan.add(d[i]);
d[i].addActionListener(this);
}
c.add(pan,BorderLayout.SOUTH);
setSize(500,300);
show();
}
public void actionPerformed(ActionEvent e)
{
int value1,value2;
value1=Integer.parseInt(b[0].getText());
value2=Integer.parseInt(b[1].getText());
if(e.getSource()==d[0])
b[2].setText(" "+(value1+value2));
else if(e.getSource()==d[1])
b[2].setText(" "+(value1-value2));
else if(e.getSource()==d[2])
b[2].setText(" "+(value1*value2));
else if(e.getSource()==d[3])
b[2].setText(" "+(value1/value2));
else if(e.getSource()==d[4])
b[2].setText(" "+(value1%value2));
else if(e.getSource()==d[5])
b[2].setText(" "+Math.sqrt(value1));
else if(e.getSource()==d[6])
b[2].setText(" "+Math.pow(value1,value2));
else
System.exit(0);
}
}
Program 16 MOUSE EVENTS
Write a Java program for handling mouse events.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class mouse extends JFrame implements MouseListener,MouseMotionListener
{
JLabel l;
public static void main(String args[])
{
mouse obj=new mouse();
}
public mouse()
{
Container c=getContentPane();
l=new JLabel();
c.add(l);
addMouseListener(this);
addMouseMotionListener(this);
setSize(500,300);
show();
}
public void mouseClicked(MouseEvent e)
{
l.setText("you have clicked at ("+e.getX()+","+e.getY()+")");
}
public void mousePressed(MouseEvent e)
{
l.setText("you have pressed at ("+e.getX()+","+e.getY()+")");
}
public void mouseReleased(MouseEvent e)
{
l.setText("you have released at ("+e.getX()+","+e.getY()+")");
}
public void mouseEntered(MouseEvent e)
{
l.setText("mouse is in window");
}
public void mouseExited(MouseEvent e)
{
l.setText("mouse is out of window");
}
public void mouseDragged(MouseEvent e)
{
l.setText("you have dragged at ("+e.getX()+","+e.getY()+")");
}
public void mouseMoved(MouseEvent e)
{
l.setText("you have moved at ("+e.getX()+","+e.getY()+")");
}
}
Program 17 Key Board Events
Write a java program for handling the key board events
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class keyboard extends JFrame implements KeyListener
{
String a,b,c,d;
JTextArea ta;
public static void main(String args[])
{
new keyboard();
}
public keyboard()
{
ta=new JTextArea(10,15);
ta.addKeyListener(this);
ta.setText("press any key on keyboard");
ta.setEditable(false);
getContentPane().add(ta);
setSize(500,300);
show();
}
public void keyPressed(KeyEvent e)
{
a="key pressed:"+e.getKeyCode();
f1(e);
}
public void keyReleased(KeyEvent e)
{
a="key released :"+e.getKeyText(e.getKeyCode());
f1(e);
}
public void keyTyped(KeyEvent e)
{ }
public void f1(KeyEvent e)
{
if(e.isActionKey())
b="you have pressed action key";
else
b="not an action key";
d=e.getKeyModifiersText(e.getKeyCode());
if(d.equals(" "))
c="you have pressed modifier key";
ta.setText(a+"\n"+b+"\n"+c);
}
}
Program 18 Producer Consumer Problem
Write a Java program that correctly implements producer consumer problem using the concept of inter thread communication.
class producer implements Runnable
{
queue q;
producer(queue q1)
{
q=q1;
Thread t=new Thread(this,"producer");
t.start();
}
public void run()
{
int i=0;
while(true)
{
try
{
Thread.sleep((int)Math.random()*10000);
q.store(++i);
}
catch(InterruptedException e)
{ }
} } }
class consumer implements Runnable
{
queue q;
consumer(queue q1)
{
q=q1;
Thread t=new Thread(this,"consumer");
t.start();
}
public void run()
{
int i=0;
while(true)
{
try
{
Thread.sleep((int)Math.random()*10000);
q.ret();
}
catch(InterruptedException e)
{ }
} } }
class queue
{
private int x=-1;
boolean write=true;
public synchronized void store(int y)
{
while(!write)
{
try
{
wait();
}
catch(InterruptedException e)
{ }
}
System.out.println("stored:"+y);
x=y;
write=false;
notify();
}
synchronized int ret()
{
while(write)
{
try
{
wait();
}
catch(InterruptedException e)
{ }
}
System.out.println("retrieved:"+x);
write=true;
notify();
return x;
}
}
class pc
{
public static void main(String args[])
{
queue s=new queue();
producer p=new producer(s);
consumer c=new consumer(s);
System.out.println("press ctrl+c to stop execution");
}
}
program 19 Client Server Application
Write a Java program that implements a simple client/server application. The client sends data to a server. The server receives the data, uses it to produce a result, and then sends the result back to the client. The client displays the result on the console.
For ex: The data sent from the client is the radius of a circle, and the result produced by the server is the area of the circle. (Use java.net)
SERVER PROGRAM
import java.io.*;
import java.net.*;
import javax.swing.*;
public class Server
{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(777);
Socket s=ss.accept();
System.out.println("connection with client established");
OutputStream obj=s.getOutputStream();
PrintStream ps=new PrintStream(obj);
Double r=Double.parseDouble(JOptionPane.showInputDialog("enter
radius"));
double area=3.14*r*r;
ps.println(""+area);
ps.println("bye");
ss.close();
s.close();
ps.close();
}
}
CLIENT PROGRAM
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String args[])throws Exception
{
Socket s=new Socket("localhost",777);
InputStream obj=s.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(obj));
String str;
while((str=br.readLine())!=null)
System.out.println(str);
s.close();
br.close();
}
}
Output
C:\javapgms>javac Server.java
C:\javapgms>java Server
connection with client established
C:\javapgms>javac Client.java
C:\javapgms>java Client
50.24
No comments:
Post a Comment