0% found this document useful (0 votes)
2 views76 pages

Labmanual Java

The document is a Java Lab Manual that introduces Object-Oriented Programming (OOP) concepts such as classes, objects, encapsulation, inheritance, and polymorphism. It includes exercises demonstrating practical applications of these concepts, including Fibonacci sequence calculations, wrapper classes, prime number identification, palindrome checking, and sorting names. Each exercise is accompanied by algorithms, flowcharts, and sample Java code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views76 pages

Labmanual Java

The document is a Java Lab Manual that introduces Object-Oriented Programming (OOP) concepts such as classes, objects, encapsulation, inheritance, and polymorphism. It includes exercises demonstrating practical applications of these concepts, including Fibonacci sequence calculations, wrapper classes, prime number identification, palindrome checking, and sorting names. Each exercise is accompanied by algorithms, flowcharts, and sample Java code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 76

1

JAVA LAB MANUAL

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.

Basic concepts of Object oriented programming


Object:

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.

Data Abstraction and Encapsulation:

The wrapping up of data and functions in to a single unit is known as encapsulation.

Data encapsulation is the most striking feature of a class.

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.

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


2

JAVA LAB MANUAL

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.

The process of making an operator to exhibit different behaviors in different instance is


known as operator overloading.

Polymorphism plays an important role in allowing objects having different internal


structures to share the same external interface. Polymorphism is extensively used if
implementing inheritance.

Benefits of OOPS:

Data security is enforced.

Inheritance saves time.

User defined data types can be easily constructed.

Inheritance emphasizes inventions of new data types.

Large complexity in the software development cn be easily managed.

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


3

JAVA LAB MANUAL

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:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 144, . . . .

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.

In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recur-


rence relation

Fn = Fn-1 + Fn-2

a)Algorithm:

Step 1: start

Step 2: Accept any number from user

Step 3: If the value of n is equal to 1 or 2 then go to step 5 else go to Stop 4

Step 4: Return the value as fib(n-1)+fib(n-2)

Step 5: Return the value as 1.

Step 6: Stop

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


4

JAVA LAB MANUAL


Flowchart:

start

Read number as n

If(n==1
||

n==2)

Return fib(n-1) Return 1


+fib(n-2)

Stop

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


5

JAVA LAB MANUAL

Sample Program:

/*Fibonacci series- Using Recursive function*/

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

OUTPUT: D:\abc>javac fibr.java

D:\abc>java fibr

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


6

JAVA LAB MANUAL


b)Algorithm:

Step 1: Start

Step 2: Accept any number from the user

Step 3: Assign values to variables f1, f2, f3, as f1=1, f2=1, f3=1and read i.

Step 4: If the value of n is equal to 1 or 2 then go to step5 otherwise go to step 6

Step 5: Return the value as 1

Step 6: Set i=2

Step 7: Check whether the value of is less than n and proceed upto

Step 9: Else go to step10

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

Step 9: Increment the value of i

Step 10: Return the value of f2.

Step 11: Stop.

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


7

JAVA LAB MANUAL


Flowchart:

Start

Read the value


of n

Assign values to variables


f1=1, f2=1, f3=1 and read i
value

If(n==1|
|n==2)

Return 1
i=2

If
i<n

Return f2

f2=f2+f3, f1=f2
f2=f3, i++

Stop

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


8

JAVA LAB MANUAL


Sample Program:

/*Fibonacci series Using-non recursive function*/

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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


9

JAVA LAB MANUAL

Exercise 2
Aim: To demonstrate wrapper classes, and to fix the precision.

Description: Wrapper class is a wrapper around a primitive data type. It represents


primitive data types in their corresponding class instances e.g. a boolean data type can
be represented as a Boolean class instance. All of the primitive wrapper classes in Java
are immutable i.e. once assigned a value to a wrapper class instance cannot be changed
further.

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 2: Assign a floating point value to f.

Step 3: Create a floating point object and the value of f is stored in that object.

Step 4: Assign a double value to d.

Step 5: Create a floating point object and the value of d is stored in that object.

Step 6: Create another floating point object and assign it to a value.

Step7: Display all the 3 object values

Step8: Stop.

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


10

JAVA LAB MANUAL

start

Assign f=10.1
D=10.1,tf=25.34

Display the values


of f1,f2,f3

Stop

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


11

JAVA LAB MANUAL

Sample Program:
/*Wrapper Classes*/

public class JavaFloatExample


{

public static void main(String[] args)


{

//create a Float object using one of the below given constructors

//1. Create an Float object from float primitive type


float f = 10.10f;
Float fObj1 = new Float(f);
System.out.println(fObj1);
//2. Create an Float object from double primitive type
double d = 10.10;
Float fObj2 = new Float(d);
System.out.println(fObj2);

Float fObj3 = new Float("25.34");


System.out.println(fObj3);
}
}

OUTPUT:
D:\abc>java JavaFloatExample
10.1
10.1
25.34

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


12

JAVA LAB MANUAL

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 2: Accept any non zero number from the user.

Step 3: Read the value of I, num and set flag=0.

Step 4: Initialize looping counters as num=1 and goto step 5

Step 5: If the value of number is less than then goto steps 6,7,8 and if the condition is
true

then the value of num is incremented else goto step 9

Step 6: Set flag equal to 0 and goto step 7

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.

Step 9: The value of flag is incremented and comes out of loop.

Step 10:I f flag==0 then goto step 11

Step 11: Display series of prime numbers

Step 12: Stop.

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


13

JAVA LAB MANUAL


Sample Program:
/*prime numbers upto given integer*/

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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


14

JAVA LAB MANUAL

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 2: Accept any string from the user

Step 3: Read the string as str1 and store in another str2

Step 4: Initialize the looping conditions as int i=0,and go to step 5.

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 7: Display “string is not a palindrome”

Step 8: Display “string is a palindrome”.

Step 9: Stop.

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


15

JAVA LAB MANUAL

Sample Program:

/*checking palindrome of a given sring*/

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

D:\abc>java palindrome mam

mam is a palindrome

D:\abc>java palindrome abc

abc is not a palindrome

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


16

JAVA LAB MANUAL

Exercise 5
Aim: To sort a given list of names in ascending order.

Description: Data::Sorting provides functions to sort the contents of arrays based on a


collection of extraction and comparison rules. Extraction rules are used to identify the at-
tributes of array elements on which the ordering is based; comparison rules specify how
those values should be ordered.

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 2: Accept any no. of strings from the user

Step 3: Set the temporary string to null.

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 6: Check whether name is equal to compareTo(name[i]<0) if it is true then go to step


7

Step 7: If temp value is equal is equal to name[i],name[i] is equal to name[j],name[j]is


equal to temp and the loops are closed.

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.

Step 10: Stop.

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


17

JAVA LAB MANUAL

Sample Program:

/*sorting given names in ascending order*/

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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


18

JAVA LAB MANUAL

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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


19

JAVA LAB MANUAL


Sample Program:
/*Matrix Multiplication & Transpose*/

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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


20

JAVA LAB MANUAL


}
}
}
System.out.println("result matrix:");
for( i=0;i<m;i++)
{
for(j=0;j<q;j++)
System.out.print(mult[i][j]+"\t");
System.out.print("\n");
}
System.out.println("transpose of matrix is");
for( i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
d[i][j]=mult[j][i];
System.out.print(d[i][j]+"\t");
}
System.out.println("\n");
}
}
}
}

OUTPUT:

D:\> java matmul


Enter the rows n columns of first matrix:2 2
Enter the First matrix: 1 2 3 4 5 6 7 8
Enter the rows n columns of second matrix:2 2
Enter the second matrix: 1 2 3 4 5 6
Result matrix 7 10
15 22
Transpose of matrix is 7 15
10 22

Exercise 7

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


21

JAVA LAB MANUAL


Aim: To implement Java program that illustrates how runtime polymorphism is
achieved.

Description: Polymorphism is the capability of an action or method to do different


things based on the object that it is acting upon. In other words, polymorphism allows
you define one interface and have multiple implementation. This is one of the basic
principles of object oriented programming.

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 3: The area of rectangle can be calculated as d1*d2.

Step 4: Display the result of area of rectangle

Step 5: The area of triangle can be calculated as (d1*d2).

Step 6: Display the result of area of triangle.

Step 7: Stop.

Sample Program:
/*Runtime polymorphism or overriding*/

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


22

JAVA LAB MANUAL


class figure
{
double d1,d2;
figure(double a, double b)
{
d1=a;
d2=b;
}
double area()
{
System.out.println("Area of the figure");
return 0;
}
}
class rectangle extends figure
{
rectangle(double a, double b)
{
super(a,b);
}
double area()
{
System.out.println("Area of rectangle");
return d1*d2;
}
}
class triangle extends figure
{
triangle(double a, double b)
{
super(a,b);
}
double area()
{
System.out.println("Area of triangle");
return d1*d2/2;
}
}
class runpoly
{
public static void main(String[] args)

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


23

JAVA LAB MANUAL


{
figure f=new figure(45,6);
rectangle r=new rectangle(10,30);
triangle t=new triangle(10,20);
figure a;
a=f;
System.out.println(a.area());
a=r;
System.out.println(a.area());
a=t;
System.out.println(a.area());
}
}

OUTPUT:

D:\abc>javac runpoly.java

D:\abc>java runpoly

Area of the figure

0.0

Area of the rectangle

300.0

Area of the triangle

100.0

Exercise 8

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


24

JAVA LAB MANUAL


Aim: To create and demonstrate packages.

Description: A package allows a developer to group classes (and interfaces) together.


These classes will all be related in some way – they might all be to do with a specific appli-
cation or perform a specific set of tasks. For example, the Java API is full of packages. One
of them is the javax.xml package. It and its sub packages contain all the classes in the Java
API to do with handling XML.

Algorithm:

Step 1: Start.

Step 2: Create a user defined package and define a class.

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;

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


25

JAVA LAB MANUAL


public class example
{
public void display(int a, int b)
{
System.out.println(“sum of a+b is”+(a+b));
}
}
import p1.example.*;
class pakexample
{
public static void main(string args[])
{
Example ob=new example();
ob.display(10,20);
System.out.println(“accesing package of p1 in pakexample”);
}
}

OUTPUT:

D:\p1> javac example.java

D:\p1>cd..

D:\> javac pakexample.java

D:\> java pakexample

sum of a+b is 30

accesing package of p1 in pakexample

Exercise 9

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


26

JAVA LAB MANUAL


Aim: To implement a java program using StringTokenizer class, this reads a line of
integers and then displays each integer and the sum of all integers.

Description: Tokens can be used where we want to break an application into


tokens. We have to break a String into tokens as well as we will know how many tokens
has been generated. That's what we are trying to do in this program. In the program a
string is passed into a constructor of StringTokenizer class. StringTokenizer is a class in
java.util.package. We are using while loop to generate tokens. The following methods
have been used in this program.

 countTokens(): It gives the number of tokens remaining in the string.


 hasMoreTokens(): It gives true if more tokens are available, else false.

 nextToken(): It gives the next token available in the string.

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 4: The value of sum= sum+n.

Step 5: Display the “sum of integers” and go to step 6.

Step 6: Stop.

Sample Program:

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


27

JAVA LAB MANUAL


/*Sum of Integers*/

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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


28

JAVA LAB MANUAL


Exercise 10
Aim: To implement a java program that reads on file name from the user then displays
information about whether the file exists, whether the file is readable/writable, the type
of file and the length of the file in bytes and display the content of the using
FileInputStream class.

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.

Step 3: check whether the accepted file exists or not.

Step 4: If exists display exists otherwise does not exist.

Step 5: check whether the accepted file is read or not.

Step 6: if read display Readable otherwise not readable.

Step 7: check whether the accepted file is writable or not.

Step 8: If writable display writable otherwise not writable.

Step 9: check whether the accepted file is file or not.

Step 10: If file display file otherwise not a file.

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


29

JAVA LAB MANUAL


Step 11: check whether the accepted file is directory or not.

Step 12: if directory display directory otherwise not a directory.

Step 13: display the length of the file in bytes.

Step 14: Stop.

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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


30

JAVA LAB MANUAL

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 2: Accept a file from the user.

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 5:Incrementno.ofwords, no.of lines other wisegoto step 6,

Step 6:Incrementno.of characters and then goto step 7.

Step 7: Check whether a character is equal to -1, if true goto step 8.

Step 8:Incrementno.of lines.

Step 9: Check whether character is not equal to -1 then goto step 10.

Step 10:Displayno.of lines, words and characters.

Step 11: Stop.

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
{

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


31

JAVA LAB MANUAL


BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter filename");
String str=br.readLine();
FileInputStream fin=new FileInputStream(str);
int ch,nc=0,nl=0,nw=0;
ch=fin.read();
do
{
if((char)ch==' ')
{
nw++;
}
else if((char)ch== '\n')
{
nw++;
nl++;
}
else
nc++;
ch=fin.read();
if(ch==-1)
{
nl++;
}
}
while(ch!=-1);
System.out.println("no of lines\n" +nl+"no of words\n" +nw+"no of
characters"+nc);
br.close();
}
}

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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


32

JAVA LAB MANUAL

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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


33

JAVA LAB MANUAL


BufferedReader br = new BufferedReader (new
InputStreamReader(source.openStream()));
while(null != (aLine = br.readLine()))
{
System.out.println(aLine);
}
br.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

OUTPUT:

D:\abc>javac readFileApplet

D:\abc>appletviewer readFileApplet

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


34

JAVA LAB MANUAL

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 2: take applet

Step 3 : add(new Labels)

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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


35

JAVA LAB MANUAL


p.setLayout(new GridLayout(4, 4));
for (int i = 0; i < buttonText.length(); i++) {
JButton b = new JButton(buttonText.substring(i, i + 1));
p.add(b);
b.addActionListener(this);}
add(p, "Center");
}
public void actionPerformed(ActionEvent evt) {
String cmd = evt.getActionCommand();
if('0'<=cmd.charAt(0)&&cmd.charAt(0)<='9'||cmd.equals(".")){
if(calculating)
display.setText(cmd);
else
display.setText(display.getText() + cmd);
calculating = false;
}
else
{
if(calculating)
{
if(cmd.equals("-"))
{
display.setText(cmd);
calculating = false;
}
else
operator = cmd;
}
else
{
double x = Double.parseDouble(display.getText());
calculate(x);
operator = cmd;
calculating = true;
}
}
}
private void calculate(double n) {
if (operator.equals("+"))
result += n;
else if (operator.equals("-"))

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


36

JAVA LAB MANUAL


result -= n;
else if (operator.equals("*"))
result *= n;
else if (operator.equals("/"))
result /= n;
else if (operator.equals("="))
result = n;
display.setText("" + result);
}
public static void main(String[] args)
{
Calculator cFrame=new Calculator();
JFrame frame = new JFrame();
cFrame.setTitle("Calculator");
cFrame.setSize(200, 200);
cFrame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
cFrame.show();
}
}

OUTPUT:
D:\abc>javac Calculator.java

D:\abc>java Calculator

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


37

JAVA LAB MANUAL

Exercise 14

Aim: To implement java program for handling mouse events.

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.

Step2: Import the packages of applet, awt, awt.event.

Step3: Create a classes, methods.

Step4: Mouse moments, mouse Clicked, mouse Pressed, mouse Released, mouse
Entered, mouse Exited, mouse Dragged events args.

Step5: g.drawString() application of Graphical User Interface.

Step6: while rotating mouse event args.

Step7: The mouse event arguments execution.

Step8: Printing in the separated Applet viewer window.

Step9: Stop the program.

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


38

JAVA LAB MANUAL

Sample Program:

/*Handling Mouse Events*/

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

public void mouseExited(MouseEvent me)


{
mousex=0;
mousey=10;
msg="MouseExited";

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


39

JAVA LAB MANUAL


repaint();
}
public void mousePressed(MouseEvent me)
{
mousex=0;
mousey=10;
msg="down";
repaint();
}
public void mouseReleased(MouseEvent me)
{
mousex =me.getX();
mousey=me.getY(); msg="up";
repaint();
}
public void mouseDragged(MouseEvent me)
{
mousex=me.getX();
mousey=me.getY(); msg="*";
showStatus("Dragging mouse at: "+mousex+","+mousey);
repaint();
}
public void mouseMoved(MouseEvent me)
{
mousex=me.getX();
mousey=me.getY();
showStatus("Moving mouse at: "+mousex+","+mousey);
}
public void paint(Graphics g)
{
g.drawString(msg,mousex,mousey);
}
}

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


40

JAVA LAB MANUAL

OUTPUT:

D:\abc>javac mevents.java

D:\abc>appletviewer mevents.java

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


41

JAVA LAB MANUAL

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.

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


42

JAVA LAB MANUAL


Algorithm:
Step 1: start
Step 2: create a thread
Step 3: start the thread
Step 4: run the thread
Step 5: suspend the thread
Step 6: invoke the suspended thread and goto step 4
Step 7: stop
Sample Program:

/*Life Cycle of a Thread*/

class newthread implements Runnable


{
Thread t;//creation of thread
newthread()
{
t=new Thread(this,"Demo Thread");
System.out.println("child Thread:"+t);
t.start();//starting the thread
}
public void run()//running thread
{
try
{
for(int i=5;i>0;i--)
{
System.out.println("child Thread:"+i);
Thread.sleep(500);//suspending thread
}
}
catch(InterruptedException e)
{
System.out.println("child Interrupted");
}
System.out.println("exiting child Thread");//stops the thread
}
}
class threadmain
{
public static void main(String args[])
{
newthread ob=new newthread();
try

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


43

JAVA LAB MANUAL

{
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

exiting child Thread

Main thread:3

Main thread:4

exiting main Thread

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


44

JAVA LAB MANUAL

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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


45

JAVA LAB MANUAL

Sample Program:
/*Producer-Consumer Problem*/

public class ProducerConsumerTest


{
public static void main(String[] args)
{
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
class CubbyHole
{
private int contents;
private boolean available = false;
public synchronized int get()
{
while (available == false)
{
try
{
wait();
}
catch (InterruptedException e) { }
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value)
{
while (available == true)
{
try
{
wait();

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


46

JAVA LAB MANUAL


}
catch (InterruptedException e) { }
}
contents = value;
available = true;
notifyAll();
}
}
class Consumer extends Thread
{
private CubbyHole cubbyhole;
private int number;

public Consumer(CubbyHole c, int number)


{
cubbyhole = c;
this.number = number;
}
public void run()
{
int value = 0;
for (int i = 0; i < 10; i++)
{
value = cubbyhole.get();
System.out.println("Consumer #" + this.number+ " got: " + value);
}
}
}
class Producer extends Thread
{
private CubbyHole cubbyhole;
private int number;
public Producer(CubbyHole c, int number)
{
cubbyhole = c;
this.number = number;
}
public void run()
{
for (int i = 0; i < 10; i++)
{

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


47

JAVA LAB MANUAL

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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


48

JAVA LAB MANUAL

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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


49

JAVA LAB MANUAL

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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


50

JAVA LAB MANUAL

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:

 drawRect - Draws a rectangle outline in the current color


 drawOval- Draws a oval outline in the current color
 drawLine- Draws a line outline in the current color

Algorithm:
Step 1: Start the program.

Step 2: Import the packages of applet,awt,awt.event.

Step 3: Create a classes: public void paint(Graphics g).

Step 4: Assume the values of string, color and font.

Step 5: g.drawString() application of Graphical User Interface.

Step 6: Printing in the separated Applet viewer window.

Step 7: Stop the program.

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


51

JAVA LAB MANUAL

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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


52

JAVA LAB MANUAL


{
g.drawOval(10*i,10*i,50+10*i,50+10*i);
}
break;
}
default:
{
g.drawString("invalid option",30,30);
}
}
}
}

OUTPUT:
D:\>javac choice.java
D:\>appletviewer choice.java

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


53

JAVA LAB MANUAL

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 Host Client Host

Server socket on port 8000


SeverSocket server =
I/O Stream
new ServerSocket(8000);
A client socket Client socket
Socket socket = Socket socket =
server.accept() new Socket(host, 8000)

compute area radius

Server
Client

area

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


54

JAVA LAB MANUAL

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.*;

public class Server


{
public void static main (String args [ ] )
{
try
{
// create a server socket
ServerSocket s = new ServerSocket(8000);

// start listening for connections on srver socket


Socket connectToClient = s.accept();

// create a buffered reader stream to get data from


client
BufferedReader isFromClient = new
BufferedReader(new InputStreamReader
(connectToClient.getInputStream()));

// create a buffer reader to send result to client


PrintWriter osToClient = new

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


55

JAVA LAB MANUAL

PrintWriter(connectToClient.getOutputStream(), true);

// continuously read from client, process, send back


while (true)
{
// read a line and create string tokenizer
StringTokenizer st = new
StringTokenizer(isFromClient.readLine());

//convert string to double


double radius = new
Double(st.nextToken()).doubleValue();

// display radius on console


System.out.println("Radius received from client:
" + radius);

// comput area
double area = radius * radius *Math.PI;

// send result to client


osToClient.println(area);

// print result on console


System.out.println("Area found: " +area);
}
}
catch (IOException e)
{
System.err.println(e);
}
}
}

// Client Program
import java.io.*;
import java.net.*;
import java.util.*;

public class Client {


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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


56

JAVA LAB MANUAL


// create a socket to connect to server
Socket connectToServer = new Socket("local host", 8000);
// create a buffered input stream to get result from server
BufferedReader isFromServer = new BufferedReader(new
InputStreamReader(connectToServer.getInputStream()));
// create a buffer output stream to send data to server
PrintWriter osToServer = new
PrintWriter(connectToClient.getOutputStream(), true);

// continuously send radius and get area while (true)


{
Scanner input=new Scanner(System.in);
System.out.print("Please enter a radius: ");
double radius =input.nextDouble();
// display radius on console
osToServer.println(radius);
// get area from server
StringTokenizer st = new
StringTokenizer(isFromServer.readLine());
// convert string to double
Double area = new
Double(st.nextToken()).doubleValue();
// print result on console
System.out.println("Area received from the
server is: " +area);
}

}
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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


57

JAVA LAB MANUAL

Exercise 20
Aim: To generate a set of random numbers between two numbers x1 and x2, and x1>0.

Description: A random number generator (RNG) is a computational or physical device


designed to generate a sequence of numbers or symbols that lack any pattern, i.e. ap-
pear random.

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

public static void main(String args[ ])

Scanner input=new Scanner(System.in);

System.out.println("Enter the x1(starting) value");

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


58

JAVA LAB MANUAL

int x1=input.nextInt();

System.out.println("Enter the x2(ending) value");

int x2=input.nextInt();

int a[ ]=new int[x2];

Random r=new Random();

for (int i=x1;i<x2;i++)

a[i]=r.nextInt(x2);

System.out.println(a[i]);

OUTPUT:

D:\>javac Randnum.java

D:\> Java Randnum


Enter the x1(starting) value 0

Enter the x2(ending) value 5

3
2
0
4

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


59

JAVA LAB MANUAL

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 2: Define any abstract class (say shape)

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 5:Displayno.of sides as three.

Step 6: Similarly trapezoid, hexagon inherits the properties of shape and defined by the
no.of sides() method.

Step 7: Display no.of sides as four and six.

Step 8: Stop.

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


60

JAVA LAB MANUAL

Sample Program:

/* Creation of Abstract Class*/

abstract class shape


{
public abstract void numberOfSlides();
}
class Trapezoid extends shape
{
public void numberOfSides()
{
System.out.println(" trapezoid contain 4 sides ");
}
}
class Triangle extends shape
{
public void numberOfSides()
{
System.out.println(" Triangle contain 3 sides");
}
}
class hexagon extends shape
{
public void numberOfSides()
{
System.out.println(" hexagon contain 6 sides");
}
}
class demo
{
public static void main(String args[])
{
triangle t=new Triangle();
hexagon h=new hexagon();
trapezoid tr=new trapezoid();
shape s;
S=t;
s.numberOfSides();
S=h;

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


61

JAVA LAB MANUAL


s.numberOfSides();
S=tr;
s.numberOfSides();
}
}

OUTPUT:

D:\>javac demo.java

D:\> Java demo


Triangle contains 3 sides.

Hexagon contains 6 sides

Trapezoid contains 4 sides

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


62

JAVA LAB MANUAL

Exercise 22
Aim: To implement a Queue, using user defined Exception Handling (also make use of
throw, throws).

Description: An exception is a problem that arises during the execution of a program. An


exception can occur for many different reasons like user has entered invalid data, file
that needs to be opened cannot be found, network connection has been lost in the mid-
dle of communications.

You can create your own exceptions in Java. Keep the following points in mind when
writing your own exception classes:

 All exceptions must be a child of Throwable.


 If you want to write a checked exception that is automatically enforced by the Han-
dle or Declare Rule, you need to extend the Exception class.

 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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


63

JAVA LAB MANUAL

Sample Program:
/* Implementation of Queue*/

import java.util.Scanner;

class ExcQueue extends Exception


{
ExcQueue(String s)
{
super(s);
}
}

class Queue
{
int front,rear;
int q[ ]=new int[10];
Queue()
{
rear=-1;
front=-1;
}

void enqueue(int n) throws ExcQueue


{
if (rear==9)
throw new ExcQueue("Queue is full"); rear++;
q[rear]=n;
if (front==-1)
front=0;
}

int dequeue() throws ExcQueue


{
if (front==-1)
throw new ExcQueue("Queue is empty");
int temp=q[front];
if (front==rear)
front=rear=-1; else
front++;
return(temp);
}
}
class UseQueue
{

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


64

JAVA LAB MANUAL

public static void main(String args[ ])


{
Queue a=new Queue();
try
{
a.enqueue(5);
a.enqueue(20);
}
catch (ExcQueue e)
{
System.out.println(e.getMessage());
}
try
{
System.out.println(a.dequeue());
System.out.println(a.dequeue());
System.out.println(a.dequeue()); } catch(ExcQueue e)
{
System.out.println(e.getMessage());
}
}
}

OUTPUT:

D:\>javac UseQueue.java

Java UseQueue

20

Queue is empty

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


65

JAVA LAB MANUAL

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 FirstThread extends Thread


{
public void run()
{
for (int i = 0; i < 10; i++)
{
try
{
sleep(1000);
System.out.println("Good Morning");
}
catch(Exception e) { }
}
}

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


66

JAVA LAB MANUAL

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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


67

JAVA LAB MANUAL

}
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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


68

JAVA LAB MANUAL

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.

Description: In object-oriented programming (OOP), inheritance is a way to reuse code


of existing objects, establish a subtype from an existing object, or both, depending upon
programming language support. In classical inheritance where objects are defined
by classes, classes can inherit attributes and behavior (i.e., previously coded algorithms
associated with a class) from pre-existing classes called base classes or super
classes or parent classes or ancestor classes. The new classes are known as derived
classes or subclasses or child classes. The relationships of classes through inheritance
give rise to a hierarchy. In this program Rodent is the super class for Mouse, Gerbil,
Hamster classes to override the methods in Rodent class.

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(){}

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


69

JAVA LAB MANUAL


void eat(){}
}
class mouse extends rodent
{
void place()
{
System.out.println("Mice are found all over the world");
}
void tail()
{
System.out.println("Mice have long and hairless tail");
}
void eat()
{
System.out.println("Mice eat carboards,papers,clothes");
}
}
class gerbil extends rodent
{
void place()
{
System.out.println("gerbil are found in arid parts of Africa and Asia");
}
void tail()
{
System.out.println("gerbil have long tail");
}
void eat()
{
System.out.println("gerbil eat seeds,roots,insects,parts of plants");
}
}

class hamster extends rodent


{
void place()
{
System.out.println("hamster are found in Western Europe to China(dry
regions)");

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


70

JAVA LAB MANUAL


void tail()
{
System.out.println("hamster have short tail");
}
void eat()
{
System.out.println("hamster eat cereals");
}
}
class beaver extends rodent
{
void place()
{
System.out.println("beaver are found in northern Europe and north
America");
}
void tail()
{
System.out.println("beaver have broad tail");
}
void eat()
{
System.out.println("beaver eat bark");
}
}
public class rodents
{
public static void main(String args[])
{
rodent r[]=new rodent[6];
for(int i=0;i<r.length;i++)
r[i]=randrodent();
for(int i=0;i<r.length;i++)
{
r[i].place();
r[i].tail();
r[i].eat();
}
}
public static rodent randrodent()
{

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


71

JAVA LAB MANUAL


switch((int)(Math.random()*4))
{
default:
case 0:return new mouse();
case 1: return new gerbil();
case 2: return new hamster();
case 3: return new beaver();
}
}
}

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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


72

JAVA LAB MANUAL


DESIGN PROGRAMS
1. To write an Applet that computes the payment of a loan
Aim: To write an Applet that computes the payment of a loan based on the amount of the
loan, the interest rate and the number of months. It takes one parameter from the
browser: Monthly rate; if true, the interest rate is per month, otherwise the interest rate is
annual.

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> */

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


73

JAVA LAB MANUAL


public class LoanPayment extends Applet implements ActionListener
{
TextField amt_t, rate_t, period_t;
Button compute = new Button("Compute"); boolean monthlyRate;
public void init() {
Label amt_l = new Label("Amount: ");
Label rate_l = new Label("Rate: ", Label.CENTER);
Label period_l = new Label("Period: ", Label.RIGHT);
amt_t = new TextField(10);
rate_t = new TextField(10);
period_t = new TextField(10);
add(amt_l);
add(amt_t);
add(rate_l);
add(rate_t);
add(period_l);
add(period_t);
add(compute);
amt_t.setText("0");
rate_t.setText("0");
period_t.setText("0");

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

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


74

JAVA LAB MANUAL


double amt=0, rate=0, period=0, payment=0; String amt_s, rate_s, period_s,
payment_s;
g.drawString("Input the Loan Amt, Rate and Period in each box and press
Compute", 50,100);
try
{
amt_s = amt_t.getText();
amt = Double.parseDouble(amt_s); rate_s = rate_t.getText();
rate = Double.parseDouble(rate_s); period_s = period_t.getText();
period = Double.parseDouble(period_s);
}
catch (Exception e) { }
if (monthlyRate)
payment = amt * period * rate * 12 / 100;
else
payment = amt * period * rate / 100;
payment_s = String.valueOf(payment);
g.drawString("The LOAN PAYMENT amount is: ", 50, 150);
g.drawString(payment_s, 250, 150);
}
public void actionPerformed(ActionEvent ae)
{
repaint();
}
}
OUTPUT:

D:\> javac LoanPayment.java

D:\>appletviewer LoanPayment.java

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


75

JAVA LAB MANUAL

2. WAJP to print a chessboard pattern

Aim: To print a chessboard pattern.


Description: In this program assume that the size of the applet is 160 by 160 pixels.
Each square in the checkerboard is 20 by 20 pixels. The checkerboard contains 8 rows
of squares and 8 columns. The squares are White and black. Here is a tricky way to de-
termine whether a given square is red or black: If the row number and the column
number are either both even or both odd, then the square is red. Otherwise, it is black.
Note that a square is just a rectangle in which the height is equal to the width, so you
can use the subroutine g.fillRect() to draw the squares. Here is an image of the checker-
board:

Algorithm:
Step 1: start
Step 2: define paint method

Step 3: read row, col, x, y values


Step 4: if row%2 is equal to col%2then set color as white otherwise set color black
Step 5: stop

Sample Program:
import java.applet.*;
public class ChessBoard extends Applet {

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS


76

JAVA LAB MANUAL


/* This applet draws a White-and-black checkerboard.
It is assumed that the size of the applet is 160 by 160 pixels. */
/* <applet code="ChessBoard.class" width=200 height=160>
</applet> */
public void paint(Graphics g)
{
int row; // Row number, from 0 to 7
int col; // Column number, from 0 to 7
int x,y; // Top-left corner of square
for ( row = 0; row < 8; row++ ) { for ( col = 0; col < 8; col++)

{
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 for row

} // end paint()

} // end class

OUTPUT:

D:\> javac ChessBoard.java

D:\>appletviewer ChessBoard.java

Ms.T.S.R.Lakshmi, Asst. Prof., Dept of CSE, BVCITS

You might also like