Labmanual Java
Labmanual Java
INTRODUCTION
The object oriented paradigm is built on the foundation laid by the structured
programming concepts. The fundamental change in OOP is that a program is designed
around the data being operated upon rather upon the operations themselves. Data and its
functions are encapsulated into a single entity.OOP facilitates creating reusable code that
can eventually save a lot of work. A feature called polymorphism permits to create multiple
definitions for operators and functions. Another feature called inheritance permits to
derive new classes from old ones. OOP introduces many new ideas and involves a
different approach to programming than the procedural programming.
Objects are the basic run time entities in an object oriented system, they may represent a
person, a place, a bank account, a table of data or any item that the program has to
handle.
Class:
The entire set of data and code of an object can be made of a user defined data type with
the help of a class. In fact, Objects are variables of the type class.
Once a class has been defined, we can create any number of objects belonging to that class
A class is thus a collection of objects of similar type.
Example: mango, apple, and orange are members of the class fruit.
ex: fruit mango; will create an object mango belonging to the class fruit.
The data is not accessible to the outside world, and only those functions which are
wrapped in the class can access.
This insulation of the data from direct access by the program is called data hiding.
Abstraction :
Abstraction refers to the act of representing essential features without including the
background details or explanations.
Since the classes use the concept of data abstraction, they are known as abstraction data
type (ADT).
Inheritance :
Inheritance is the process by which objects of one class acquire the properties of objects of
another class. Inheritance supports the concept of hierarchical classification.
Polymorphism:
Polymorphism is another important oop concept. Polymorphism means the ability to take
more than one form. an operation may exhibit different instances. The behavior depends
upon the types of data used in the operation.
Benefits of OOPS:
Exercise 1
Aim:
To implement Java Program that uses both recursive and non-recursive functions to
print the nth value of the Fibonacci sequence.
Description: In mathematics, the Fibonacci numbers are the numbers in the follow-
ing integer sequence:
By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each
subsequent number is the sum of the previous two.
Fn = Fn-1 + Fn-2
a)Algorithm:
Step 1: start
Step 6: Stop
start
Read number as n
If(n==1
||
n==2)
Stop
Sample Program:
class fibonacci
{
int fib(int n)
{
int f1=1,f2=1,f3=0,i;
if(n==1||n==2)
return 1;
else
return(fib(n-1)+fib(n-2));
}
}
class fibr
{
public static void main(String args[])
{
int a=6;
fibonacci f=new fibonacci();
int k=f.fib(a);
System.out.println(+k);
}
}
D:\abc>java fibr
Step 1: Start
Step 3: Assign values to variables f1, f2, f3, as f1=1, f2=1, f3=1and read i.
Step 7: Check whether the value of is less than n and proceed upto
Step 8: Compute f2=f2+f3 and assign the value of f1to f3 and the value of f2 to f1 and
go to step 9
Start
If(n==1|
|n==2)
Return 1
i=2
If
i<n
Return f2
f2=f2+f3, f1=f2
f2=f3, i++
Stop
class fibonacci
{
int fib(int n)
{
int f1=1,f2=1,f3=0,i;
if(n==1||n==2)
return 1;
else
i=2;
while(i<n)
{
f2=f2+f3;
f1=f2;
f2=f3;
i++;
}
return f2;
}
}
class fib1
{
public static void main(String args[])
{
int a=6;
fibonacci f=new fibonacci();
int k=f.fib(a);
System.out.println(+k);
}
}
OUTPUT: D:\abc>javac fib1.java
D:\abc>java fib1
Exercise 2
Aim: To demonstrate wrapper classes, and to fix the precision.
Wrapper Classes are used broadly with Collection classes in the java.util package
and with the classes in the java.lang.reflect reflection package.
Algorithm:
Step 1: Start
Step 3: Create a floating point object and the value of f is stored in that object.
Step 5: Create a floating point object and the value of d is stored in that object.
Step8: Stop.
start
Assign f=10.1
D=10.1,tf=25.34
Stop
Sample Program:
/*Wrapper Classes*/
OUTPUT:
D:\abc>java JavaFloatExample
10.1
10.1
25.34
Exercise 3
Aim: To implement java program that prompts the user for an integer and then prints
out all the prime numbers up to that Integer.
Description: A prime number (or a prime) is a natural number greater than 1 that has no
positive divisors other than 1 and itself. For example, 5 is prime, as only 1 and 5 divide it.
Algorithm:
Step 1: Start
Step 5: If the value of number is less than then goto steps 6,7,8 and if the condition is
true
Step7: Initialize another looping counter with i=2 and checks whether i less than num/2
and if condition is true then value of i is incremented and goto steps 8, 9 .otherwise goto
step 10
Step 8: if num%i==0 then goto step 9 other wise goto step 10.
import java.io.*;
class prime
{
public static void main(String args[])throws IOException
{
int i,num,flag=0;
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter a value");
int n=Integer.parseInt(dis.readLine());
System.out.println("prime numbers upto given integer");
for(num=1;num<=n;num++)
{
flag=0;
for(i=2;i<=num/2;i++)
{
if((num%i)==0)
{
flag++;
break;
}
}
if(flag==0)
System.out.println(+num);
}
}
}
OUTPUT:
D:\abc>java prime
enter a value
10
prime numbers upto given integer
1
2
3
5
7
Exercise 4
Aim: To implement java program that checks whether a given string is a palindrome or
not. Ex: MALAYALAM is a palindrome.
Description: A type of word play in which a word, phrase, or sentence reads the same
backward or forward--such as Madam. In this example The StringBuffer class is used to
represent characters that can be modified. This is simply used for concatenation or ma-
nipulation of the strings. StringBuffer is mainly used for the dynamic string concatena-
tion which enhances the performance.
Algorithm:
Step 1: Start
Step 5: Check whether I less than string length and if it is true then go to step 6 and
value of I is incremented else goto step 9
Step 6: Check if str1.char At(i)!=str2.char At(i) and if it is true then go to step 7 otherwise
go to step 8.
Step 9: Stop.
Sample Program:
import java.io.*;
class palindrome
{
public static void main(String args[])
{
String str1=new String(args[0]);
StringBuffer str2=new StringBuffer(str1);
str2.reverse();
for(int i=0;i<str2.length();i++)
{
if(str1.charAt(i)!=str2.charAt(i))
{
System.out.println(str1+ "is not a palindrome");
System.exit(0);
}
}
System.out.println(str1+ "is a palindrome");
}
}
OUTPUT:
D:\abc>javac palindrome.java
mam is a palindrome
Exercise 5
Aim: To sort a given list of names in ascending order.
Index strings may be used to retrieve values from array elements, or function references
may be passed in to call on each element. Comparison rules are provided for numeric,
bytewise, and case-insensitive orders, as well as a 'natural' comparison that places num-
bers first, in numeric order, followed by the remaining items in case-insensitive textual or-
der.
Algorithm:
STEP 1: Start
Step 4: Check condition that i == 0 and the value of i < n then go to step 5.
Step 5: Again check the value of j as equal to j+1 and again check j value is less than n
then go to 6.
Step 8: Again check the condition i is equal to o and check the value of i is less than n,
then go to step 9.
STEP 9: Display name[i] (all the strings in alphabetical order are then i value is
incremented and goes on if the condition is false.
Sample Program:
import java.io.*;
import java.lang.*;
import java.util.*;
class stringsort
{
public static void main(String args[])throws IOException
{
Static String name[]={"abc","xyz","pqr","cde"};
String temp=null;
int i,j;
System.out.println("prints all strings in Alphabetical order");
int n=name.length;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(name[j].compareTo(name[i])<0)
{
temp=name[i];
name[i]=name[j];
name[j]=temp;
}
}
}
for(i=0;i<n;i++)
System.out.println(name[i]);
}
}
OUTPUT:
D:\abc>javac stringsort.java
D:\abc>java stringsort
Prints all strings in alphabetical order
abc
cde
pqr
xyz
Exercise 6
Aim: To check the compatibility for multiplication, if compatible multiply two matrices
and find its transpose.
Description: In this program, we have to declare two multidimensional array of type in-
teger. Program uses two for loops to get number of rows and columns by using the scan-
ner class. After getting both matrix then multiply to it. Both matrixes will be multiplied to
each other by using 'for' loop. So the output will be displayed on the screen command
prompt by using the println() method. Next it finds out the transpose of a given matrix.
Algorithm:
Step1: start
Step2: read i=0,j=0,m,n,p,q,first[][] by using Scanner class
Step3: check the compatibility of two matrices
Step 4: if it is compatible read second [][]
Step 5: for i=0 to m j=0 to q and k=0 to p do mult[i][j]=mult[i][j]+first[k]
[j]*second[i][k]
Step 6: display mult[i][j] value
Step 7: read a matrix for transpose d[i][j]
Step 8: display d[j][i]
Step 9: stop
import java.util.Scanner;
class matmull
{
public static void main(String args[])
{
int m,n,p,q,i,j,k;
Scanner input=new Scanner(System.in);
System.out.println("Enter the rows n columns of first matrix:");
m=input.nextInt();
n=input.nextInt();
int d[][]=new int[m][n];
int first[][]=new int[m][n];
System.out.println("Enter the first matrix:");
for( i=0;i<m;i++)
for(j=0;j<n;j++)
first[i][j]=input.nextInt();
System.out.println("Enter the rows n columns of second matrix:");
p=input.nextInt();
q=input.nextInt();
if(n!=p)
System.out.println("matrix multiplication not possible");
else
{
int second[][]=new int[p][q];
int mult[][]=new int[m][q];
System.out.println("Enter the second matrix:");
for( i=0;i<p;i++)
for(j=0;j<q;j++)
second[i][j]=input.nextInt();
for( i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
mult[i][j]=0;
for(k=0;k<p;k++)
{
mult[i][j]=first[i][k]*second[k][j]+mult[i]
[i];
OUTPUT:
Exercise 7
The method overriding is an example of runtime polymorphism. You can have a method
in subclass overrides the method in its super classes with the same name and signature.
Java virtual machine determines the proper method to call at the runtime, not at the
compile time.
Algorithm:
Step 1: Start
Step2: Read the variables as d1and d2 and set the values of d1 and d2 as a and b
respectively.
Step 7: Stop.
Sample Program:
/*Runtime polymorphism or overriding*/
OUTPUT:
D:\abc>javac runpoly.java
D:\abc>java runpoly
0.0
300.0
100.0
Exercise 8
Algorithm:
Step 1: Start.
Step 3: In that class a method and a message is displayed and then goto step4.
Step 4: Import the above package and define another class which extends the properties
of super class and also methods defined in it.
Step 5: Create an object in the sub class and access the methods from super class.
Step 6: Stop.
Sample Program:
/*creation of packages*/
package p1;
OUTPUT:
D:\p1>cd..
sum of a+b is 30
Exercise 9
Algorithm:
Step 1: start
Step 2: Accept any number from the user and assign sum=0.
Step 3: Set the loop and checks the conditions whether a.hasMoreTokens() and if it is
true then go to Step 4 otherwise go to step 5.
Step 6: Stop.
Sample Program:
import java.util.*;
import java.io.*;
import java.lang.Math;
class stringtokeniser
{
public static void main(String args[])throws IOException
{
String str;
int n,sum=0;
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter a line of integers");
str=dis.readLine();
StringTokenizer a=new StringTokenizer(str);
while(a.hasMoreTokens());
{
n=Integer.parseInt(a.nextToken());
System.out.println(+n);
sum=sum+n;
}
System.out.println("sum of integers" +sum);
}
}
OUTPUT:
D:\abc>javac stringtokeniser.java
D:\abc>java stringtokeniser
Enter a line of integers
12345
1
2
3
4
5
sum of integers 15
Description: Java has Two types of streams- Byte & Characters. For reading and writing
binary data, byte stream is incorporated. The InputStream abstract class is used to read
data from a file. The FileInputStream is the subclass of the InputStream abstract class.
The FileInputStream is used to read data from a file.
The read() method of an InputStream returns an int which contains the byte value of the
byte read. If there is no more data left in stream to read, the read() method returns -1
and it can be closed after this. One thing to note here, the value -1 is an int not a byte
value.
Algorithm:
Step 1: Start.
Step 2: Accept a file from the user.
Sample Program:
/*Displaying contents from a file*/
import java.io.*;
class filedata
{
public static void main(String args[])throws IOException
{
String str=" ";
DataInputStream in=new DataInputStream(System.in);
System.out.println("enter a file name");
str=in.readLine();
File s1=new File(str);
System.out.println(s1.exists()?"exists":"not exists");
System.out.println(s1.canRead()?"readable":"not readable");
System.out.println(s1.canWrite()?"writable":"not writable");
System.out.println(s1.isFile()?"is a file":"is not a file");
System.out.println(s1.isDirectory()?"is dir":"is not dir");
System.out.println("length of file is"+s1.length()+"bytes");
}
}
OUTPUT:
D:\abc>javac filedata.java
D:\abc>java filedata
enter a file name
sample.java
exists
readable
writable
is a file
is not dir
length of file is100bytes
Exercise 11
Aim: To WAJP that displays the number of characters, lines and words in a text/text file.
Description: This example illustrates how to count the number of lines, number of words
and number of characters in the specified file. Program takes the file name as parameter
and it counts the number of words and lines present in the file. By using BufferedReader
class it takes file name as input and counts the lines by ‘\n’ parameter and so on.
Algorithm:
Step 1: Start
Step 3: Initialise the no. of characters, no. of lines and no. of words to zero and no. of
words to zero and read characters ch from the file.
Step 4: Check whether (char)ch== empty then increment no.of words otherwise goto
step 5.6.
Step 9: Check whether character is not equal to -1 then goto step 10.
Sample Program:
/*Displaying characters, lines, word from a file*/
import java.io.*;
import java.lang.String;
class wordcount
{
public static void main(String args[])throws IOException
{
OUTPUT:
D:\abc>javac wordcount.java
D:\abc>java wordcount
Enter filename
sample.java
no of lines 8
no of words 14
no of characters 86
Exercise 12
Aim: Write an Applet that displays the content of a file.
Description: In this program we will show you about the concept of the reading file
from an applet. This program illustrates you how an applet can read the content from
the given file. In this program we passes the file name as applet parameter which is then
read by the applet program. If you specify the file name( which has to be read ) in the
html file then the program will read the file otherwise applet will read the specified file
for the String type variable namedfileToRead
Algorithm:
Step1: start
Step 2: initialize an applet
Step 3: read a file name
Step 4: read the contents of a file by using Buffered Reader
Step 5: display the contents of file
Step 6: stop
Sample Program:
/*Reading file from applet*/
import java.applet.*;
import java.net.*;
import java.io.*;
/*<applet code="readFileApplet.class" width=200 height=200></applet>*/
public class MyApplet extends Applet
{
public void init()
{
readFile("test1.txt");
}
public void readFile(String f)
{
try
{
String aLine = " ";
URL source = new URL(getCodeBase(), f);
OUTPUT:
D:\abc>javac readFileApplet
D:\abc>appletviewer readFileApplet
Exercise 13
Aim: To WAJP that works as a simple calculator. Use a grid layout to arrange buttons for
the digits and for the + - x / % operations. Add a text field to display the result.
Description: The grid layout provides the facility to arrange some created GUI compo-
nents for the frame. The grid layout arranges components by dividing areas into rows
and columns. This Program shows grid layout components added for panel on the frame.
There are different components like text fields and buttons.
Algorithm:
Step 1: start
Step 4 : actionPerformed(ActionEvent e)
Step 5 : stop
Sample Program:
/*creating calculator*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JFrame implements ActionListener
{
private JTextField display = new JTextField("0");
private String buttonText = "789/456*123-0.=+";
private double result = 0;
private String operator = "=";
private boolean calculating = true;
public Calculator(){
setLayout(new BorderLayout());
display.setEditable(false);
add(display, "North");
JPanel p = new JPanel();
OUTPUT:
D:\abc>javac Calculator.java
D:\abc>java Calculator
Exercise 14
Description: EVENTS ARE CENTRAL to programming for a graphical user interface. A GUI
program doesn't have a main() routine that outlines what will happen when the program
is run, in a step-by-step process from beginning to end. The most basic kinds of events
are generated by the mouse and keyboard. The user can press any key on the keyboard,
move the mouse, or press a button on the mouse. In Java, events are represented by ob-
jects. When an event occurs, the system collects all the information relevant to the
event and constructs an object to contain that information. For example, when the user
presses one of the buttons on a mouse, an object belonging to a class
called MouseEvent is constructed. In order to detect an event, the program must "listen"
for it. Listening for events is something that is done by an object called an event listener.
An event listener object must contain instance methods for handling the events for
which it listens.
Algorithm:
Step1: Start the program.
Step4: Mouse moments, mouse Clicked, mouse Pressed, mouse Released, mouse
Entered, mouse Exited, mouse Dragged events args.
Sample Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="mevents" width=200 height=100></applet>*/
public class mevents extends Applet implements
MouseListener,MouseMotionListener
{
String msg= " ";
int mousex=0,mousey=0;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
mousex=0;
mousey=10;
msg="MouseClicked";
repaint();
}
public void mouseEntered(MouseEvent me)
{
mousex=0;
mousey=10;
msg="MouseEntered";
repaint();
}
OUTPUT:
D:\abc>javac mevents.java
D:\abc>appletviewer mevents.java
Exercise 15
Aim: To demonstrating the life cycle of a thread.
Description: The following diagram shows the states that a Java thread can be in during
its life. It also illustrates which method calls cause a transition to another state. This fig -
ure is not a complete finite state diagram, but rather an overview of the more interest-
ing and common facets of a thread's life.
Born State: After the creations of Thread instance the thread is in this state but before
the start() method invocation.
Runnable (Ready-to-run) state: A thread starts its life from Runnable state. A thread
first enters runnable state after the invoking of start() method but a thread can return to
this state after either running, waiting, sleeping or coming back from blocked state also.
On this state a thread is waiting for a turn on the processor.
Running state: A thread is in running state that means the thread is currently executing.
Dead state: A thread can be considered dead when its run() method completes. If any
thread comes on this state that means it cannot ever run again.
Blocked - A thread can enter in this state because of waiting the resources that are hold
by another thread.
{
for(int i=5;i>0;i--)
{
System.out.println("main thread"+i);
Thread.sleep(2000);
}
}
}
catch(InterruptedException e)
{
System.out.println("main Interrupted");
}
System.out.println("exiting main Thread");
}
}
OUTPUT:
D:\abc>javac newthread.java
D:\abc>java newthread
Main thread:0
Child thread:0
Child thread:1
Main thread:1
Child thread:2
Child thread:3
Main thread:2
Child thread:4
Main thread:3
Main thread:4
Exercise 16
Aim: To implement Producer-Consumer problem using the concept of Inter Thread Com-
munication.
Description: Java provides a very efficient way through which multiple-threads can com-
municate with each-other. This way reduces the CPU’s idle time i.e. A process where, a
thread is paused running in its critical region and another thread is allowed to enter (or
lock) in the same critical section to be executed. This technique is known as Interthread
communication which is implemented by some methods.
In this program, two threads "Producer" and "Consumer" share the synchro-
nized methods of the class "Shared". At time of program execution, the "put( )" method
is invoked through the "Producer"class which increments the variable "num" by 1. After
producing 1 by the producer, the method "get( )"is invoked by through the "Con-
sumer" class which retrieves the produced number and returns it to the output. Thus the
Consumer can't retrieve the number without producing of it.
Algorithm:
Step1: Start
Step 2 define producer, consumer, and cubbyhole class
Step 3: for singal wait
Step 4 true 0r false
Step 5 : print producer and consumer contents value
Step 6 stop
Sample Program:
/*Producer-Consumer Problem*/
cubbyhole.put(i);
System.out.println("Producer #" + this.number+ " put: " + i);
try
{
sleep((int)(Math.random() * 100));
}
catch (InterruptedException e) { }
}
}
}
OUTPUT:
D:\abc>javac ProducerConsumer.java
D:\abc>java ProducerConsumer
Producer #1 put: 0
Consumer #1 got: 0
Producer #1 put: 1
Consumer #1 got: 1
Producer #1 put: 2
Consumer #1 got: 2
Producer #1 put: 3
Consumer #1 got: 3
Producer #1 put: 4
Consumer #1 got: 4
Producer #1 put: 5
Consumer #1 got: 5
Producer #1 put: 6
Consumer #1 got: 6
Producer #1 put: 7
Consumer #1 got: 7
Producer #1 put: 8
Consumer #1 got: 8
Producer #1 put: 9
Consumer #1 got: 9
Exercise 17
Aim: To WAJP that lets users create Pie charts. Design your own user interface (with
Swings & AWT).
Description: This Java Pie Chart example is drawing a pie chart to show the percentage
obtained in particular session. In this example we have used the Applet to draw a pie
chart and filling with colors and values of their sessions.
Algorithm:
Step1: start
Step 2: Define applets
Step 3: set background colors and define strings to display pie chart
Step 4: End applet
Sample Program:
/*Creating Pie Charts Using Swings & AWT*/
import java.awt.*;
import java.applet.*;
import java.swing.*;
/*<applet code=PiChart.class width=600 height=600></applet>*/
public class PiChart extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.green);
g.drawString("PI CHART",200,40);
g.setColor(Color.blue);
g.fillOval(50,50,150,150);
g.setColor(Color.white);
g.drawString("40%",130,160);
g.setColor(Color.magenta);
g.fillArc(50,50,150,150,0,90);
g.setColor(Color.white);
g.drawString("25%",140,100);
g.setColor(Color.yellow);
g.fillArc(50,50,150,150,90,120);
g.setColor(Color.black);
g.drawString("35%",90,100);
g.fillArc(250,50,150,150,30,120);
g.setColor(Color.white);
g.drawString("30%",330,100);
g.setColor(Color.black);
g.fillArc(250,50,150,150,120,180);
g.setColor(Color.white);
g.drawString("50%",280,160);
}
}
OUTPUT:
D:\>javac PiChart.java
D:\>appletviewer PiChart.java
Exercise 18
Aim: WAJP that allows user to draw lines, rectangles and ovals.
Description: Drawing rectangles, ovals, lines in Java is fairly easy. There are some meth-
ods provided by the "Graphics" object that provide this. These methods are follows:
Algorithm:
Step 1: Start the program.
Sample Program:
/*Draw lines, Rectangles, Ovals*/
import javax.swing.*;
import java.awt.Graphics;
/*<applet code="choice.class" width=300 height=300></applet>*/
public class choice extends JApplet
{
int i,ch;
public void init()
{
String input;
input=JOptionPane.showInputDialog("enter yourchoice(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++)
OUTPUT:
D:\>javac choice.java
D:\>appletviewer choice.java
Exercise 19
Aim: To implement 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 cir-
cle.
The client issues socket statement to request a connection to a server. Then the server
must be running when a client starts. The server waits for a connection request from a
client. To establish a server, you need to create a server socket and attach it to a port,
which is where the server listens for connections. Whenever a server socket is created,
the server can use this statement to listen for connections. After the server accepts the
connection, communication between server and client is conducted the same as for I/O
streams.
Server
Client
area
Algorithm:
Step 1: start
Step 2: create the server socket
Step 3: connect to client
Step 4: create a buffered reader stream to get data from client
Step 5: create a buffer reader to send result to client
Step 6: create a buffer reader to send result to client
Step 7: continuously read from client, process, send back while (true) read a line
and create string tokenizer
Step 8: display radius on console
Step 9: stop
Sample Program:
/* Client Server Application*/
// Server Program
import java.io.*;
import java.net.*;
import java.util.*;
PrintWriter(connectToClient.getOutputStream(), true);
// comput area
double area = radius * radius *Math.PI;
// Client Program
import java.io.*;
import java.net.*;
import java.util.*;
}
catch (IOException e)
{
System.err.println(e);
}
}
}
OUTPUT:
D:/>javac Client.java
Please enter a radius: 12
Area received from server is 452.389321169302
Please enter a radius: 10
Area received from server is 314.1592653589793
D:/>javac Server.java
Radius received from client: 12.0
Area Found: 452.3893421169302
Exercise 20
Aim: To generate a set of random numbers between two numbers x1 and x2, and x1>0.
The many applications of randomness have led to the development of several different
methods for generating random data. Many of these have existed since ancient times,
including dice, coin flipping, the shuffling of playing cards and many other tech-
niques. The Random class of java.util package can be used to generate a random number
in the range which can be specified. If you don't mention the range value then program
will generate any random number.
Algorithm:
Step 1: start
Step 2: read x1, x2 values
Step 3: read a[]
Step 4: generate random numbers
Step 5: display the result
Step 6: stop
Sample Program:
/* Generate a set of Random Numbers*/
import java.util.*;
class Randnum
int x1=input.nextInt();
int x2=input.nextInt();
a[i]=r.nextInt(x2);
System.out.println(a[i]);
OUTPUT:
D:\>javac Randnum.java
3
2
0
4
Exercise 21
Aim: 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 contains only the method numberOfSides(), that contains
the number of sides in the given geometrical figure.
Description: Java provides a special type of class called an abstract class. This helps us
to organize our classes based on common methods. An abstract class lets you put the
common method names in one abstract class without having to write the actual
implementation code.
An abstract class can be extended into sub-classes, these sub-classes usually provide
implementations for all of the abstract methods. The key idea with an abstract class is
useful when there is common functionality that's like to implement in a super class and
some behavior is unique to specific classes. So you implement the super class as an ab-
stract class and define methods that have common subclasses. Then you implement
each subclass by extending the abstract class and add the methods unique to the class.
Algorithm:
Step 1: Start
Step 3: In this class shape we should define any method no.of sides().
Step 4: Initially triangle inherits the properties of shape and defined by the no.of sides()
method.
Step 6: Similarly trapezoid, hexagon inherits the properties of shape and defined by the
no.of sides() method.
Step 8: Stop.
Sample Program:
OUTPUT:
D:\>javac demo.java
Exercise 22
Aim: To implement a Queue, using user defined Exception Handling (also make use of
throw, throws).
You can create your own exceptions in Java. Keep the following points in mind when
writing your own exception classes:
If you want to write a runtime exception, you need to extend the Runtime Exception
class.
In this program user defined exception is named ExcQueue which throws by using throw
and throws keyword.
Algorithm:
Step 1: start
Step 2: create user defined exception ExcQueue
Step 3: read q[] and initialize rear and front to -1
Steep 4: if rear equal to 9 then throws a exception Queue is full otherwise increment the
rear
Step 5: if front equal to -1 then throw a exception queue is empty otherwise
temp=q[front]
Step 6: display the result
Step 7: stop
Sample Program:
/* Implementation of Queue*/
import java.util.Scanner;
class Queue
{
int front,rear;
int q[ ]=new int[10];
Queue()
{
rear=-1;
front=-1;
}
OUTPUT:
D:\>javac UseQueue.java
Java UseQueue
20
Queue is empty
Exercise 23
Aim: To creates 3 threads by extending Thread class. First thread displays “Good Morn-
ing” every 1 sec, the second thread displays “Hello” every 2 seconds and the third dis-
plays “Welcome” every 3 seconds.
Description:
A thread is a lightweight process which exists within a program and executed to perform
a special task. Several threads of execution may be associated with a single process. Thus
a process that has only one thread is referred to as a single-threaded process, while a
process with multiple threads is referred to as a multi-threaded process. In this program
three threads are created and displays good morning, hello, and welcome each thread is
sleeping for some amount of time which invoked the other thread.
Algorithm:
Step 1: start
Step 2: create three classes for three threads to display the the messages like goodmorn-
ing, hello, and welcome
Step 3: start the all threads
Step 4: stop
Sample Program:
/* Creation of 3 Threads*/
}
class SecondThread extends Thread
{
public void run()
{
for (int i = 0; i < 10; i++)
{
try
{
sleep(2000);
System.out.println("Hello");
}
catch(Exception e) { }
}
}
}
class ThirdThread extends Thread
{
public void run()
{
for (int i = 0; i < 10; i++)
{
try
{
sleep(3000);
System.out.println("Welcome");
}
catch(Exception e) { }
}
}
}
public class Test
{
public static void main(String[] args)
{
FirstThread ft = new FirstThread();
SecondThread st = new SecondThread();
ThirdThread tt = new ThirdThread();
ft.start();
st.start();
tt.start();
try
{
ft.join();
st.join();
tt.join();
}
catch (Exception e){ }
}
}
OUTPUT:
D:\abc>javac Test.java
D:\abc>java Test
Good Morning
Hello
Good Morning
Welcome
Good Morning
Hello
Good Morning
Good Morning
Welcome
Hello
Good Morning
Good Morning
Hello
Good Morning
Welcome
Good Morning
Hello
Good Morning
Welcome
Hello
Hello
Welcome
Hello
Welcome
Hello
Hello
Welcome
Welcome
Welcome
Welcome
Exercise 24
Aim: To Create an inheritance hierarchy of Rodent, Mouse, Gerbil, Hamster etc. In the
base class provide methods that are common to all Rodents and override these in the
derived classes to perform different behaviors, depending on the specific type of Ro-
dent. Create an array of Rodent, fill it with different specific types of Rodents and call
your base class methods.
Algorithm:
Step 1: start
Step 2: Define rodent as a super class and define the abstract methods like
eat().tail(),place()
Step 3: override these methods in to different classes like mouse, gerbil, hamster, beaver
Step 4: create an array of rodent and call all the base classes
Step 5: stop
Sample Program:
/* Creation of Inheritance*/
class rodent
{
void place(){}
void tail(){}
OUTPUT:
gerbil are found in arid parts of Africa and Asia
gerbil have long tail
gerbil eat seeds,roots,insects,parts of plants
Mice are found all over the world
Mice have long and hairless tail
Mice eat carboards,papers,clothes
gerbil are found in arid parts of Africa and Asia
gerbil have long tail
gerbil eat seeds,roots,insects,parts of plants
Mice are found all over the world
Mice have long and hairless tail
Mice eat carboards,papers,clothes
gerbil are found in arid parts of Africa and Asia
gerbil have long tail
gerbil eat seeds,roots,insects,parts of plants
hamster are found in Western Europe to China(dry regions)
hamster have short tail
hamster eat cereals
Description: An applet is a program written in the Java programming language that can
be included in an HTML page, much in the same way an image is included in a page.
When you use a Java technology-enabled browser to view a page that contains an ap-
plet, the applet's code is transferred to your system and executed by the browser's Java
Virtual Machine (JVM). In this program it computes the payment of the loan based on in-
terest Rate and number of months.
Algorithm:
Step 1: start
Step 2: take applet
Step 3: add(new Label("select months/years "));
Step 4: actionPerformed(ActionEvent e)
Step 5: if (monthlyRate)
payment = amt * period * rate * 12 / 100;
Step 6: otherwise payment = amt * period * rate / 100;
Step 7: stop
Sample Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code = "LoanPayment" width=500 height=300 > <param name =
monthlyRate value=true>
</applet> */
monthlyRate = Boolean.valueOf(getParameter("monthlyRate"));
amt_t.addActionListener(this);
rate_t.addActionListener(this);
period_t.addActionListener(this);
compute.addActionListener(this);
}
public void paint(Graphics g)
{
D:\>appletviewer LoanPayment.java
Algorithm:
Step 1: start
Step 2: define paint method
Sample Program:
import java.applet.*;
public class ChessBoard extends Applet {
{
x = col * 40;
y = row * 40;
if ( (row % 2) == (col % 2) )
g.setColor(Color.white);
else
g.setColor(Color.black);
g.fillRect(x, y, 40, 40);
}
} // end paint()
} // end class
OUTPUT:
D:\>appletviewer ChessBoard.java