SRM Valliammai Engineering College Kattankulathur: Lab Manual

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

SRM Valliammai Engineering College

Kattankulathur

LAB MANUAL
CS8383 OBJECT ORIENTED PROGRAMMING LABORATORY

ACADEMIC YEAR 2019-20

YEAR : III Yr B.E EEE

SEMESTER : 5

Prepared by
3B

Name Ms.Vidhya.A
Assistant Professor (Sr.G) / CSE
Ms. Suma.S
Assistant Professor(Sr.G) / CSE

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 1


LIST OF EXPERIMENTS

CYCLE I

EX NO: 1 Develop a Java application to generate Electricity bill. Create a class with the
following members: Consumer no., consumer name, previous month reading, current month reading,
type of EB connection (i.e domestic or commercial). Compute the bill amount using the following
tariff.
If the type of the EB connection is domestic, calculate the amount to be paid as follows:
i. First 100 units - Rs. 1 per unit
ii. 101-200 units - Rs. 2.50 per unit
iii. 201 -500 units - Rs. 4 per unit
iv. > 501 units - Rs. 6 per unit
If the type of the EB connection is commercial, calculate the amount to be paid as follows:

EX NO: 2 Develop a java application to implement currency converter (Dollar to INR, EURO to
INR, Yen to INR and vice versa), distance converter (meter to KM, miles to KM and vice versa) ,
time converter (hours to minutes, seconds and vice versa) using packages.

EX NO: 3 Develop a java application with Employee class with Emp_name, Emp_id, Address,
Mail_id, Mobile_no as members. Inherit the classes, Programmer, Assistant Professor, Associate
Professor and Professor from employee class. Add Basic Pay (BP) as the member of all the inherited
classes with 97% of BP as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1% of BP for staff club
fund. Generate pay slips for the employees with their gross and net salary.

EX NO: 4 Design a Java interface for ADT Stack. Implement this interface using array.
Provide necessary exception handling in both the implementations.

EX NO: 5 Write a program to perform string operations using ArrayList. Write functions for
the following
Append - add at end
Insert – add at particular index
Search
List all string starts with given letter

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 2


CYCLE II
EX NO : 6 Write a Java Program to create an abstract class named Shape that contains two
integers and an empty method named print Area(). Provide three classes named Rectangle, Triangle
and Circle such that each one of the classes extends the class Shape. Each one of the classes contains
only the method print Area () that prints the area of the given shape

EX NO: 7 Write a Java program to implement user defined exception handling.

EX NO : 8Write a Java program that reads a file name from the user, displays information about
whether the file exists, whether the file is readable, or writable, the type of file and the length of the
file in bytes.

EX NO:9 Write a java program that implements a multi-threaded application that has three threads.
First thread generates a random integer every 1 second and if the value is even, second thread
computes the square of the number and prints. If the value is odd, the third thread will print the value
of cube of the number.

EX NO: 10 Write a java program to find the maximum value from the given type of elements using a
generic function.

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 3


EX NO: 11 Design a calculator using event-driven programming paradigm of Java with the following
options.
Decimal manipulations
Scientific manipulations
EX NO: 12 Develop a mini project for any application using Java concepts.

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 4


Ex No: 1

Java application to generate Electricity bill


Develop a Java application to generate Electricity bill. Create a class with the following members:
Consumer no., consumer name, previous month reading, current month reading, type of EB
connection (i.e domestic or commercial). Compute the bill amount using the following tariff.
If the type of the EB connection is domestic, calculate the amount to be paid as follows:
i. First 100 units - Rs. 1 per unit
ii. 101-200 units - Rs. 2.50 per unit
iii. 201 -500 units - Rs. 4 per unit
iv. > 501 units - Rs. 6 per unit
If the type of the EB connection is commercial, calculate the amount to be paid as follows:

AIM:
To write a java program for generating domestic EB bill generation.

ALGORITHM

1. Create a class ebill in java


2. Using input function get the consumed units for current and previous month
3. Calculate the amount depending on the no of units consumed.
4. Display the bill.

PROBLEM DESCRIPTION:

Develop a Java application to generate Electricity bill. Create a class with the following members:
Consumer no., consumer name, previous month reading, current month reading, and type of EB
connection (i.e domestic or commercial). Compute the bill amount using the following tariff.
If the type of the EB connection is domestic, calculate the amount to be paid as follows:
i. First 100 units - Rs. 1 per unit
ii. 101-200 units - Rs. 2.50 per unit
iii. 201 -500 units - Rs. 4 per unit
iv. > 501 units - Rs. 6 per unit
If the type of the EB connection is commercial, calculate the amount to be paid as follows:

PROGRAM:
import java.util.*;
import java.io.*;
class ebill
{
public static void main (String args[])
{
customerdata ob = new customerdata();
ob.Getdata();
ob.Calc();
ob.Display();
}

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 5


}

class customerdata
{
Scanner in = new Scanner (System.in);
Scanner ins = new Scanner (System.in);
String cname,fname;
int bn,connection;
double punits,cunits,uc, amttbill,amt, famt, tax ;

void Getdata()
{
System.out.print ("\n\t Enter block number = ");
bn = in.nextInt();
System.out.print ("\n\t Enter flat name = ");
fname = ins.nextLine();
System.out.print ("\n\t Enter customer name = ");
cname = ins.nextLine();
System.out.print ("\n\t Enter previous month consumed units = ");
punits = in.nextDouble();
System.out.print ("\n\t Enter current month consumed units = ");
cunits = in.nextDouble();
uc=cunits-punits;
}

void Calc()
{
amt=uc*1;

if(uc>100 && uc<=200)


amt=((uc-100)*2)+100;
else
{
if(uc>200 && uc<=300)
amt=((uc-200)*3)+300;
else
{
if(uc>300 && uc<=500)
amt=((uc-300)*4)+600;
else
amt=((uc-500)*5)+1400;
}
}

//add tax.
tax=(amt*10)/100;
famt=amt+50+tax;

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 6


}

OUTPUT:

C:\jdk1.7\bin>java ebill

Enter block number = 12

Enter flat name = RUBY

Enter customer name = ANUSHA

Enter previous month consumed units = 1000

Enter current month consumed units = 2000


-----------------------
Electricity Bill
-----------------------
Units Charge 3900.0
Meter Charge 50
Tax 390.0
-----------------------
Total 4340.0

RESULT:

Thus the java program for generating domestic EB bill generation is written and executed.

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 7


Ex No: 2
Implement currency converter
Develop a java application to implement currency converter (Dollar to INR, EURO to INR, Yen to
INR and vice versa), distance converter (meter to KM, miles to KM and vice versa) , time converter
(hours to minutes, seconds and vice versa) using packages.

AIM:
To write a java program to implement currency converter.

PROBLEMDESCRIPTION:

Develop a java application to implement currency converter (Dollar to INR, EURO to INR, Yen to
INR and vice versa), distance converter (meter to KM, miles to KM and vice versa) , time converter
(hours to minutes, seconds and vice versa) using packages.

ALGORITHM

1.Import java input ,output and java utility packages.


2.Declare class currency which implements serializable interface.
3. Declare public and protected members.
4. Convert rupees to dollars and vice versa.
5. Exceptions are handled by using try and catch block.

PROGRAM:

import java.io.*;
import java.util.Scanner;

public class Currency1


{

public static void main(String[] args)


{
Scanner input = new Scanner(System.in);
double value1 = 0.00, value2 = 0.00;
String ch;
String currency;
System.out.println("Enter your choice");
System.out.println("1.USD to INR 2.EUR to INR 3.YEN to INR 4.INR to USD,EURO, YEN ");
ch=input.next();
switch(ch)
{
case "1":
System.out.print("Enter a value usd: ");
value1 = input.nextDouble();
value2 = value1 * 68.20;

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 8


System.out.println(value1 + "USD = " + value2 + " INR. (Conversion rate: 1 USD = 68.2 INR)");
break;

case "2":
System.out.print("Enter a value eur: ");
value1 = input.nextDouble();
value2 = value1 * 78.84;
System.out.println(value1 + "eur = " + value2 + " INR. (Conversion rate: 1 eur = 78.84 INR)");
break;
case "3":
System.out.print("Enter a value yen: ");
value1 = input.nextDouble();
value2 = value1 * 0.62;
System.out.println(value1 + "yen = " + value2 + " INR. (Conversion rate: 1 yen = 0.62 INR)");
break;
case "4":

System.out.print("Enter a value INR: ");


value1 = input.nextDouble();
input.nextLine();
System.out.print("USD or EUR or YEN: ");
currency = input.nextLine();

if(currency.equals("USD"))
{
value2 = value1 * 0.015;
System.out.println(value1 + "INR = " + value2 + " USD. (Conversion rate: 1 INR = 0.015 USD)");
}

else if (currency.equals("EUR"))
{
value2 = value1 * 0.013;
System.out.println(value1 + "INR = " + value2 + " EUR. (Conversion rate: 1 INR = 0.013 EUR)");
}

else if (currency.equals("YEN"))
{
value2 = value1 * 1.62;
System.out.println(value1 + "INR = " + value2 + " YEN. (Conversion rate: 1 INR = 1.62 YEN)");
}}

input.close();
}

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 9


}
OUTPUT :

C:\jdk1.7\bin>javac Currency1.java

C:\jdk1.7\bin>java Currency1
Enter your choice
1.USD to INR 2.EUR to INR 3.YEN to INR 4.INR to USD,EURO, YEN
1
Enter a value usd: 100
100.0USD = 6820.0 INR. (Conversion rate: 1 USD = 68.2 INR)

C:\jdk1.7\bin>java Currency1
Enter your choice
1.USD to INR 2.EUR to INR 3.YEN to INR 4.INR to USD,EURO, YEN
2
Enter a value eur: 100
100.0eur = 7884.0 INR. (Conversion rate: 1 eur = 78.84 INR)

C:\jdk1.7\bin>java Currency1
Enter your choice
1.USD to INR 2.EUR to INR 3.YEN to INR 4.INR to USD,EURO, YEN
3
Enter a value yen: 100
100.0yen = 62.0 INR. (Conversion rate: 1 yen = 0.62 INR)

C:\jdk1.7\bin>java Currency1
Enter your choice
1.USD to INR 2.EUR to INR 3.YEN to INR 4.INR to USD,EURO, YEN
4
Enter a value INR: 100
USD or EUR or YEN: YEN
100.0INR = 162.0 YEN. (Conversion rate: 1 INR = 1.62 YEN)
RESULT:

Thus the java program for implement currency converter executed and output is verified.

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 10


Ex No:3
Java Application with Employee Class

AIM:
To write a java application with Employee class.

PROBLEMDESCRIPTION:

Develop a java application with Employee class with Emp_name, Emp_id, Address, Mail_id,
Mobile_no as members. Inherit the classes, Programmer, Assistant Professor, Associate Professor and
Professor from employee class. Add Basic Pay (BP) as the member of all the inherited classes with
97% of BP as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1% of BP for staff club fund. Generate
pay slips for the employees with their gross and net salary.

ALGORITHM
1.Import the necessary java packages.
2.Declare class with necessary public and private menbers.
3. Calculate basic pay, gross pay and net pay for employee.
4. Display employee name ,basic pay, gross pay and net pay.
5. Generate pay slip with necessary details.

PROGRAM:
import java.io.*;
import java.lang.*;
interface salary
{
final double da=10.7;
final double cps=10.0;
final double hra=5.0;
final double ma=15.0;
final double nhi=10.0;
}
class emppay
{
String name;
double basicpay,netpay,grosspay;
emppay(String n,double bp)
{
name=n;
basicpay=bp;
}
}
class payslip extends emppay implements salary
{
double c1,h1,d1;
payslip(String n1,double bp1)

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 11


{
super(n1,bp1);
}
public void paybill()
{
d1=basicpay*(da/100);
h1=basicpay*(hra/100);
c1=basicpay*(cps/100);
netpay=basicpay+d1+h1+ma;
grosspay=netpay-(c1+nhi);
}
void disp()
{
System.out.println("\t Payslip");
System.out.println("Name of The Employee :"+name +"\t payslip");
System.out.println("\t Grosspay="+grosspay);
System.out.println("\t Netpay="+netpay);
}
}
class paybill
{
public static void main(String arg[])throws IOException
{
String name;
double pay;
DataInputStream inp=new DataInputStream(System.in);
System.out.println("Enter Name of Employee :");
name=inp.readLine();
System.out.println("Enter The Basicpay :");
pay=Double.valueOf(inp.readLine());
payslip p1=new payslip(name,pay);
p1.paybill();
p1.disp();
}

OUTPUT:
C:\jdk1.7\bin>java paybill
Enter Name of Employee :Rajesh
Enter The Basicpay :
8000

Payslip
Name of The Employee :Rajesh
Grosspay=8461.0
Netpay=9271.0
Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 12
RESULT:

Thus the java application with employee class is executed and output is verified.

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 13


Ex No:4
Java interface for ADT StackClasses and Objects

AIM:
To write a java program to illustrate the concept of java interface for ADT Stack.

PROBLEMDESCRIPTION:

Design a Java interface for ADT Stack. Implement this interface using array. Provide necessary
exception handling in both the implementations.

ALGORITHM
1. Create an class stack
2. Create an interface mystack which defines stack operation push , pop, display.
3. In stack, push operation -insertion of element are done at top
and top pointer is incremented by one.
4. In stack, pop operation Remove an item, pointed by top
and top pointer is decremented by one.

PROGRAM:
importjava.io.*;
interfaceMystack
{
publicvoidpop();
publicvoidpush();
publicvoiddisplay();
}
classStack_array implementsMystack
{
finalstaticintn=5;
intstack[]=newint[n];
inttop=-1;
publicvoidpush()
{
try
{
BufferedReader br=newBufferedReader(newInputStreamReader(System.in));
if(top==(n-1))
{
System.out.println(" Stack Overflow");
return;
}
else
{
System.out.println("Enter the element");
intele=Integer.parseInt(br.readLine());
stack[++top]=ele;

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 14


}
}
catch(IOException e)
{
System.out.println("e");
}
}
publicvoidpop()
{
if(top<0)
{
System.out.println("Stack underflow");
return;
}
else
{
intpopper=stack[top];
top--;
System.out.println("Popped element:"+popper);
}
}

publicvoiddisplay()
{
if(top<0)
{
System.out.println("Stack is empty");
return;
}
else
{
String str=" ";
for(inti=0; i<=top; i++)
str=str+" "+stack[i]+" <--";
System.out.println("Elements are:"+str);
}
}
}
classStackADT
{
publicstaticvoidmain(String arg[])throwsIOException
{
BufferedReader br=newBufferedReader(newInputStreamReader(System.in));
System.out.println("Implementation of Stack using Array");
Stack_array stk=newStack_array();
intch=0;
do
{

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 15


System.out.println("1.Push 2.Pop 3.Display 4.Exit");
System.out.println("Enter your choice:");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case1:
stk.push();
break;
case2:
stk.pop();
break;
case3:
stk.display();
break;
case4:
System.exit(0);
}
}
while(ch<5);

}
}

OUTPUT:

Implementation of Stack using Array


1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
1
Enter the element
10
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
1
Enter the element
15
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
1
Enter the element
25
1.Push 2.Pop 3.Display 4.Exit 5.Use Linked List
Enter your choice:
3
Elements are: 25 <-- 15 <-- 10<--
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
2

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 16


Popped: 25
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
3
Elements are: 15 <-- 10<--
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
4

RESULT:

Thus the java program using interfaces for ADT stack was executed and output verified.

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 17


Ex No:5
String operations using ArrayList

AIM:
To perform string operations using ArrayList. Write functions for the following
Append - add at end
Insert – add at particular index
Search
List all string starts with given letter

PROBLEMDESCRIPTION:

Write a program to perform string operations using ArrayList. Write functions for the
following
Append - add at end
Insert – add at particular index
Search
List all string starts with given letter

ALGORITHM
1. Import java necessary packages
2. Declare class and create a arraylist
3. Add elements to the arraylist using add()
4. Display the arraylist elements
5. Add index to the elements
6. Remove elements from the given index in the arraylist
7. Display the arraylist

PROGRAM:
import java.util.*;

public class ArrayListExample {


public static void main(String args[]) {
/*Creation of ArrayList: I'm going to add String
*elements so I made it of string type */
ArrayList<String> obj = new ArrayList<String>();

/*This is how elements should be added to the array list*/


obj.add("Ajeet");
obj.add("Harry");
obj.add("Chaitanya");
obj.add("Steve");
obj.add("Anuj");

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 18


/* Displaying array list elements */
System.out.println("Currently the array list has following elements:"+obj);

/*Add element at the given index*/


obj.add(0, "Rahul");
obj.add(1, "Justin");
System.out.println("Currently the array list has following elements:"+obj);

/*Remove elements from array list like this*/


obj.remove("Chaitanya");
obj.remove("Harry");

System.out.println("Current array list is:"+obj);

/*Remove element from the given index*/


obj.remove(1);
System.out.println("Currently the array list :"+obj);
/*search a letter */
String str = "GeeksforGeeks";
int firstIndex = str.indexOf('s');
System.out.println("First occurrence of char 's'" +
" is found at : " + firstIndex);

}
}import
public
publicjava.util.*;
class
static
/*Creation
*elements ArrayListExample
void
of
so main(String
ArrayList:
Ihow
made {=args[]) {be
ArrayList<String>
/*This
obj.add("Harry");
obj.add("Ajeet");
obj.add("Chaitanya");
obj.add("Anuj");
obj.add("Steve");
/* Displaying
obj.add(0,
obj.add(1,
String
}importint obj.remove(1);
} /*Creation str"void
firstIndex
java.util.*; atatitthe
is "GeeksforGeeks";
elements
array
System.out.println("Currently
/*Add =element
"Rahul");
"Justin");
elements
obj.remove("Chaitanya");
obj.remove("Harry");
System.out.println("Current
/*Remove element ofI'm
obj string
"list
going
given
from
from
= str.indexOf('s');
System.out.println("First
isArrayList:
found :of +
new
thetype
should
elementsto
the
index*/
array
array
given add
*/
list
firstIndex);
occurrence
String
ArrayList<String>();
*/added
array
like
list to the
list
this*/
is:"+obj);
index*/
of char
array
has's'" list*/
following
+ list*/ elements:"+obj);
public
publicclass
static
*elements ArrayListExample
/*This of
ArrayList<String>
sois main(String
Ihow
obj.add("Ajeet");made
obj.add("Chaitanya");
obj.add("Harry");
obj.add("Steve");
obj.add("Anuj");
/* it
elements
System.out.println("Currently
Displaying
/*Add
obj.add(0,
obj.add(1,
/*Remove element array
"Rahul");
at
"Justin");
elements
obj.remove("Harry");
obj.remove("Chaitanya"); the I'm
obj
list{=args[])
going
stringnewtype
should
elements
given
from {be
to
the
index*/
array add
*/
list String
ArrayList<String>();
*/added
array
like to
list
this*/the
hasarray
following elements:"+obj);
}} obj.remove(1); element from the given
System.out.println("Current array list is:"+obj);
index*/
OUTPUT:

C:\jdk1.7\bin>java ArrayListExample
Currently the array list has following elements:[Ajeet, Harry, Chaitanya, Steve,
Anuj]
Currently the array list has following elements:[Rahul, Justin, Ajeet, Harry, Chaitanya,
Steve, Anuj]
Current array list is:[Rahul, Justin, Ajeet, Steve, Anuj]
Current array list is:[Rahul, Ajeet, Steve, Anuj]
First occurrence of char 's' is found at : 4
RESULT:

Thus the java program for creating string operations using ArrayList was executed and output
verified.

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 19


Ex No:6
Java UsingAbstract class
U

AIM:
To write a Java Program to create an abstract class.

PROBLEMDESCRIPTION:

Develop a Java code to create an abstract class named Shape that contains two integers and an
empty method named print Area(). Provide three classes named Rectangle, Triangle and Circle such
that each one of the classes extends the class Shape. Each one of the classes contains only the
method print Area () that prints the area of the given shape

ALGORITHM
1. Declare a class with abstract keyword
2. abstract keyword is used to create an abstract class in java
3. class rectangle, triangle and circle inherits the abstract class
4. calculate area of rectangle and triangle
5. Display the area of rectangle and triangle.

PROGRAM:

abstract class shape


{
int a=3,b=4;
abstract public void print_area();
}
class rectangle extends shape
{
public int area_rect;
public void print_area()
{
area_rect=a*b;
System.out.println("The area ofrectangle is:"+area_rect);
}
}
class triangle extends shape
{
int area_tri;
@Override
public void print_area()
{
area_tri=(int) (0.5*a*b);
System.out.println("The area oftriangle is:"+area_tri);

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 20


}
}
class circle extends shape
{
int area_circle;
@Override
public void print_area()
{
area_circle=(int) (3.14*a*a);
System.out.println("The area of circle is:"+area_circle);
}
}
public class JavaApplication3
{
public static void main(String[] args)
{
rectangle r=new rectangle();
r.print_area();
triangle t=new triangle();
t.print_area();
circle r1=new circle();
r1.print_area();
}
}
OUTPUT:
run:
The area of rectangle is:12
The area of triangle is:6
The area of circle is:28

RESULT:
Thus the java program using abstract class has been executed and output verified.

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 21


Ex No:7
User defined exception handling
U

Write a Java program to implement user defined exception handling.

AIM:
To implement user defined exception handling.

PROBLEMDESCRIPTION:

Develop a Java program to implement an exception (or exceptional event) is a problem that
arises during the execution of a program. When an Exception occurs the normal flow of the
program is disrupted and the program/Application terminates abnormally, which is not
recommended, therefore, these exceptions are to be handled.

ALGORITHM
1.Declare a user defined class and function to validate age.
2.Pass the age argument to function validate.
3.Check if age is above 18 print “welcome to vote”
else throw ArithmeticException("not valid");

PROGRAM:

public class TestThrow1


{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}

OUTPUT:

Compile by: javac TestThrow1.javaRun by: java TestThrow1

Exception in thread "main" java.lang.ArithmeticException: not valid


at TestThrow1.validate(TestThrow1.java:5)
at TestThrow1.main(TestThrow1.java:11)

RESULT:

Thus the program to implement system defined exception was executed and
output verified.

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 22


Ex No:8
Java program using Files
Write a Java program that reads a file name from the user, displays information about
whether the file exists, whether the file is readable, or writable, the type of file and the
length of the file in bytes.

AIM:
To write a Java program that reads a file.

PROBLEMDESCRIPTION:

Develop a Java program that reads a file name from the user, displays information
about whether the file exists, whether the file is readable, or writable, the type of file
and the length of the file in bytes.

ALGORITHM

1. Read the file name from the user using BufferedReader class.
2. Check if file exists. if true check for file readable or writeable
3. else display file does not exist.
4. Check the type of the file whether it is image file ,text file or executable file using the
file extension.
5. Also print the length of the file in bytes using length() function.

PROGRAM:
import java.io.*;
public class FileInfo
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("\nEnter A File Name:");
String fName = br.readLine();
File f = new File(fName);
String result = f.exists() ? "exists." : "does not exist.";
System.out.println("\nThe given file " + result);
if(f.exists())
{
result = f.canRead() ? "readable." : "not readable.";
System.out.println("The given file is " + result);
result = f.canWrite() ? "writable." : "not writable.";
System.out.println("The given file is " + result);
System.out.println("The given file length is " + f.length() + " in bytes.");
if (fName.endsWith(".jpg") || fName.endsWith(".gif") ||
fName.endsWith(".png"))
{
System.out.println("The given file is an image file.");
}

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 23


else if (fName.endsWith(".exe"))
{
System.out.println("The given file is an executable file.");
}
else if (fName.endsWith(".txt"))
{
System.out.println("The given file is a text file.");
}
else
{
System.out.println("The file type is unknown.");
}
}
}
}
OUTPUT:

RESULT:
Thus the java program to implement files was executed and output verified.

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 24


Ex No:9
Multithreaded Application
MM

Write a java program that implements a multi-threaded application that has three
threads. First thread generates a random integer every 1 second and if the value is
even, second thread computes the square of the number and prints. If the value is odd,
the third thread will print the value of cube of the number.

AIM:
To write a java program that implements a multi-threaded application.

PROBLEMDESCRIPTION:

To write a java program that implements a multi-threaded application that has three
threads. First thread generates a random integer every 1 second and if the value is
even, second thread computes the square of the number and prints. If the value is
odd, the third thread will print the value of cube of the number.

ALGORITHM

1. Create threads for classes odd and even by implementing Runnable interface.
2. Generate a random number using Random().
3. Check the random number generated is odd or even.
4. if number is even, a thread squares the generated number and print.
5. else if number is odd, a thread cubes the generated number and print.

PROGRAM:
import java.util.*;
class even implements Runnable {
public int x;
public even(int x) {
this.x = x;
}
public void run() {
System.out.println("Thread Name:Even Thread and " + x + "is even Number
and Square of " + x
+ " is: " + x * x);
}
}
class odd implements Runnable {
public int x;
public odd(int x) {
this.x = x;
}
public void run() {
System.out.println("Thread Name:ODD Thread and " + x + " is odd number
and Cube of " + x +
" is: " + x * x * x);
}
}

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 25


class A extends Thread {
public String tname;
public Random r;
public Thread t1, t2;
public A(String s) {
tname = s;
}
public void run() { int num = 0;
r = new Random();
try {
for (int i = 0; i < 50; i++) {
num = r.nextInt(100);
System.out.println("Main Thread and Generated Number is " + num);
if (num % 2 == 0) {
t1 = new Thread(new even(num));
t1.start();
} else {
t2 = new Thread(new odd(num));
t2.start();
}
Thread.sleep(1000);
System.out.println("--------------------------------------");
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
public class Mthread
{
public static void main(String[] args)
{
A a = new A("One");
a.start();
}
}
OUTPUT

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 26


RESULT:
Thus the java program to implement multithreaded application was executed and output
verified.

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 27


Ex No:10
Generic Function
U

Write a java program to find the maximum value from the given type of elements
using a generic function.

AIM:
To write a Java program using a generic function

PROBLEM DESCRIPTION:

Develop a program to find the maximum value from the given type of elements which
can specify, with a single method declaration, a set of related methods, or with a
single class declaration, a set of related types, respectively. Generics also provide
compile-time type safety that allows programmers to catch invalid types at compile
time.

ALGORITHM

1. Declare a generic class to print the numbers.


2. Intialize integer array and pass to generic function to print the integer numbers.
3. Intialize double array and pass to generic function to print the double numbers.
4. Intialize character array and pass to generic function to print the character.

PROGRAM:

public class MaximumTest


{
// determines the largest of three Comparable objects

public static <T extends Comparable<T>> T maximum(T x, T y, T z)


{
T max = x; // assume x is initially the largest

if(y.compareTo(max) > 0)
{
max = y; // y is the largest so far
}

if(z.compareTo(max) > 0)
{
max = z; // z is the largest now
}
return max; // returns the largest object
}

public static void main(String args[])


{
System.out.printf("Max of %d, %d and %d is %d\n\n",
3, 4, 5, maximum( 3, 4, 5 ));

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 28


System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n",
6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ));

System.out.printf("Max of %s, %s and %s is %s\n","pear",


"apple", "orange", maximum("pear", "apple", "orange"));
}
}

OUTPUT:
1 2E2.2
1.1 3L4characterArray
Array
H integerArray
5 O 4.4
doubleArray
L3.3 contains:
contains:
C:\jdk1.7\bin>javac MaximumTest.java

C:\jdk1.7\bin>java -Xmx128M -Xms16M MaximumTest

Max of 3, 4 and 5 is 5

Max of 6.6,8.8 and 7.7 is 8.8

Max of pear, apple and orange is pear

RESULT:

Thus the java program using generic function was executed and output
verified.

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 29


Ex No:11

Event driven Calculator


E

Design a calculator using event-driven programming paradigm of Java with the


following options.
Decimal manipulations
Scientific manipulations

AIM:
Develop event-driven programming paradigm of Java.
PROBLEMDESCRIPTION:
To Design a calculator using event-driven programming paradigm of Java with the
following options.
Decimal manipulations
Scientific manipulations

ALGORITHM

1. Create a class calculator using all layouts with buttons, textfields and labels.
2. If decimal numbers and arithmetic operators are selected, appropriate function
implements the necessary event like addition, subtraction etc.
3. If decimal numbers and scientific functions are selected, appropriate function
implements the necessary event like sin,cos,exp etc.
4. The required output is displayed.

PROGRAM:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class Calculator
{
JFrame frame = new JFrame();
// Creating the Menu Bar
JMenuBar menubar = new JMenuBar();
//---> Creating the "Calculator-->Exit" Menu
JMenu firstmenu = new JMenu("Calculator");
JMenuItem exitmenu = new JMenuItem("Exit");
// Creating The TextArea that gets the value
JTextField editor = new JTextField();
JRadioButton degree = new JRadioButton("Degree");
JRadioButton radians = new JRadioButton("Radians");
String[] buttons = {"BKSP","CLR","sin","cos","tan","7","8","9","/","+/-
","4","5","6","X","x^2","1","2","3","-","1/x","0",".","=","+","sqrt"};
JButton[] jbuttons = new JButton[26];
double buf=0,result;
boolean opclicked=false,firsttime=true;
String last_op;
public Calculator()
{

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 30


frame.setSize(372,270);
frame.setTitle("Calculator .");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
ButtonHandler bhandler = new ButtonHandler();
menubar.add(firstmenu);
firstmenu.add(exitmenu);
exitmenu.setActionCommand("mExit");
exitmenu.addActionListener(bhandler);
editor.setPreferredSize(new Dimension(20,50));
Container buttoncontainer = new Container();
buttoncontainer.setLayout(new GridLayout(5,5));
for(int i=0;i<buttons.length;i++)
{
jbuttons[i] = new JButton(buttons[i]);
jbuttons[i].setActionCommand(buttons[i]);
jbuttons[i].addActionListener(bhandler);
buttoncontainer.add(jbuttons[i]);
}
JPanel degrad = new JPanel();
degrad.setLayout(new FlowLayout());
ButtonGroup bg1 = new ButtonGroup();
bg1.add(degree);
bg1.add(radians);
degrad.add(degree);
radians.setSelected(true);
degrad.add(radians);
frame.setJMenuBar(menubar);
frame.add(editor,BorderLayout.NORTH);
frame.add(degrad,BorderLayout.CENTER);
frame.add(buttoncontainer,BorderLayout.SOUTH);
frame.setVisible(true);
}
public static void main(String args[])
{
Calculator a = new Calculator();
}
public class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String action = e.getActionCommand();
if(action == "0" || action=="1" || action=="2" || action=="3" || action=="4"
|| action=="5" || action=="6" || action=="7" || action=="8" || action=="9" ||
action==".")
{
if(opclicked == false)
editor.setText(editor.getText() + action);
else
{
editor.setText(action);
opclicked = false;
}
}
Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 31
if(action == "CLR")
{
editor.setText("");
buf=0;
result=0;
opclicked=false;
firsttime=true;
last_op=null;
}
//Addition
if(action=="+")
{
firsttime = false;
if(last_op!="=" && last_op!="sqrt" && last_op!="1/x" &&
last_op!="x^2" && last_op!="+/-")
{
buf = buf + Double.parseDouble(editor.getText());
editor.setText(Double.toString(buf));
last_op = "+";
opclicked=true;
}
else
{
opclicked=true;
last_op = "+";
}
}
// Subtraction
if(action=="-")
{
if(firsttime==true)
{
buf = Double.parseDouble(editor.getText());
firsttime = false;
opclicked=true;
last_op = "-";
}
else
{
if(last_op!="=" && last_op!="sqrt" && last_op!="1/x" &&
last_op!="x^2" && last_op!="+/-")
{
buf = buf - Double.parseDouble(editor.getText());
editor.setText(Double.toString(buf));
last_op = "-";
opclicked=true;
}
else
{
opclicked=true;
last_op = "-";
}
}
}
//Multiplication
if(action=="X")
{
if(firsttime==true)
{
buf = Double.parseDouble(editor.getText());
firsttime = false;
Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 32
opclicked = true;
last_op = "X";
}
else
{
if(last_op!="=" && last_op!="sqrt" && last_op!="1/x" &&
last_op!="x^2" && last_op!="+/-")
{
buf = buf * Double.parseDouble(editor.getText());
editor.setText(Double.toString(buf));
last_op = "X";
opclicked=true;
}
else
{
opclicked=true;
last_op = "X";
}
}
}
//Division
if(action=="/")
{
if(firsttime==true)
{
buf = Double.parseDouble(editor.getText());
firsttime = false;
opclicked=true;
last_op = "/";
}
else
{
if(last_op!="=" && last_op!="sqrt" && last_op!="1/x" &&
last_op!="x^2" && last_op!="+/-")
{
buf = buf / Double.parseDouble(editor.getText());
editor.setText(Double.toString(buf));
last_op = "/";
opclicked=true;
}
else
{
opclicked=true;
last_op = "/";
}
}
}
// Equal to
if(action=="=")
{
result = buf;
if(last_op=="+")
{
result = buf + Double.parseDouble(editor.getText());
buf = result;
}
if(last_op=="-")
{
result = buf - Double.parseDouble(editor.getText());
buf = result;
}
Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 33
if(last_op=="X")
{
result = buf * Double.parseDouble(editor.getText());
buf = result;
}
if(last_op=="/")
{
try
{
result = buf / Double.parseDouble(editor.getText());
}
catch(Exception ex)
{
editor.setText("Math Error " + ex.toString());
}
buf = result;
}
editor.setText(Double.toString(result));
last_op = "=";
}
// Sqrt
if(action=="sqrt")
{
if(firsttime==false)
{
buf = Math.sqrt(buf);
editor.setText(Double.toString(buf));
opclicked=true;
last_op = "sqrt";
}
else
{
if(editor.getText()=="")
JOptionPane.showMessageDialog(frame,"Enter input pls...","Input
Missing",JOptionPane.ERROR_MESSAGE);
else
{
buf = Double.parseDouble(editor.getText());
buf = Math.sqrt(buf);
editor.setText(Double.toString(buf));
firsttime = false;
opclicked=true;
last_op = "sqrt";
}
}
}
// Reciprocal
if(action=="1/x")
{
if(firsttime==false)
{
buf = 1/ buf;
editor.setText(Double.toString(buf));
opclicked=true;
last_op = "1/x";
Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 34
}
else
{
if(editor.getText()==null)
JOptionPane.showMessageDialog(frame,"Enter input pls...","Input
Missing",JOptionPane.ERROR_MESSAGE);
else
{
buf = Double.parseDouble(editor.getText());
buf = 1 / buf;
editor.setText(Double.toString(buf));
firsttime = false;
opclicked=true;
last_op = "1/x";
}
}
}
// Square
if(action=="x^2")
{
if(firsttime==false)
{
buf = buf * buf;
editor.setText(Double.toString(buf));
opclicked=true;
last_op = "x^2";
}
else
{
if(editor.getText()==null)
JOptionPane.showMessageDialog(frame,"Enter input pls...","Input
Missing",JOptionPane.ERROR_MESSAGE);
else
{
buf = Double.parseDouble(editor.getText());
buf = buf * buf;
editor.setText(Double.toString(buf));
firsttime = false;
opclicked=true;
last_op = "x^2";
}
}
}
// Negation +/-
if(action=="+/-")
{
if(firsttime==false)
{
buf = -(buf);
editor.setText(Double.toString(buf));
opclicked=true;
last_op = "+/-";
}
else
Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 35
{
if(editor.getText()==null)
JOptionPane.showMessageDialog(frame,"Enter input pls...","Input
Missing",JOptionPane.ERROR_MESSAGE);
else
{
buf = Double.parseDouble(editor.getText());
buf = -(buf);
editor.setText(Double.toString(buf));
firsttime = false;
opclicked=true;
last_op = "+/-";
}
}
}
// Exit
if(action=="mExit")
{
frame.dispose();
System.exit(0);
}
if(action=="mCut")
editor.cut();
if(action=="mCopy")
editor.copy();
if(action=="mPaste")
editor.paste();
if(action=="sin")
{
if(radians.isSelected())
{
if(firsttime==false)
{
buf = Math.sin(Double.parseDouble(editor.getText()));
editor.setText(Double.toString(buf));
opclicked=true;
last_op = "sin";
}
else
{
if(editor.getText()=="")
JOptionPane.showMessageDialog(frame,"Enter input pls...","Input
Missing",JOptionPane.ERROR_MESSAGE);
else
{
buf = Double.parseDouble(editor.getText());
buf = Math.sin(Double.parseDouble(editor.getText()));
editor.setText(Double.toString(buf));
firsttime = false;
opclicked=true;
last_op = "sin";
}
}
}
else
{
if(firsttime==false)
{
double rad=Math.toRadians(Double.parseDouble(editor.getText()));
buf = Math.sin(rad);
Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 36
editor.setText(Double.toString(buf));
opclicked=true;
last_op = "sin";
}
else
{
if(editor.getText()=="")
JOptionPane.showMessageDialog(frame,"Enter input pls...","Input
Missing",JOptionPane.ERROR_MESSAGE);
else
{
double rad=Math.toRadians(Double.parseDouble(editor.getText()));
buf = Math.sin(rad);
editor.setText(Double.toString(buf));
firsttime = false;
opclicked=true;
last_op = "sin";
}
}
}
}// end of sin
if(action=="cos")
{
if(radians.isSelected())
{
if(firsttime==false)
{
buf = Math.cos(Double.parseDouble(editor.getText()));
editor.setText(Double.toString(buf));
opclicked=true;
last_op = "cos";
}
else
{
if(editor.getText()=="")
JOptionPane.showMessageDialog(frame,"Enter input pls...","Input
Missing",JOptionPane.ERROR_MESSAGE);
else
{
buf = Double.parseDouble(editor.getText());
buf = Math.sin(Double.parseDouble(editor.getText()));
editor.setText(Double.toString(buf));
firsttime = false;
opclicked=true;
last_op = "cos";
}
}
}
else
{
if(firsttime==false)
{
double rad=Math.toRadians(Double.parseDouble(editor.getText()));
buf = Math.cos(rad);
editor.setText(Double.toString(buf));
opclicked=true;
last_op = "cos";
}
else
{
Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 37
if(editor.getText()=="")
JOptionPane.showMessageDialog(frame,"Enter input pls...","Input
Missing",JOptionPane.ERROR_MESSAGE);
else
{
double rad=Math.toRadians(Double.parseDouble(editor.getText()));
buf = Math.cos(rad);
editor.setText(Double.toString(buf));
firsttime = false;
opclicked=true;
last_op = "cos";
}
}
}
}// end of cos
if(action=="tan")
{
if(radians.isSelected())
{
if(firsttime==false)
{
buf = Math.tan(Double.parseDouble(editor.getText()));
editor.setText(Double.toString(buf));
opclicked=true;
last_op = "tan";
}
else
{
if(editor.getText()=="")
JOptionPane.showMessageDialog(frame,"Enter input pls...","Input
Missing",JOptionPane.ERROR_MESSAGE);
else
{
buf = Double.parseDouble(editor.getText());
buf = Math.tan(Double.parseDouble(editor.getText()));
editor.setText(Double.toString(buf));
firsttime = false;
opclicked=true;
last_op = "tan";
}
}
}
else
{
if(firsttime==false)
{
double rad=Math.toRadians(Double.parseDouble(editor.getText()));
buf = Math.tan(rad);
editor.setText(Double.toString(buf));
opclicked=true;
last_op = "tan";
}
else
{
if(editor.getText()=="")
JOptionPane.showMessageDialog(frame,"Enter input pls...","Input
Missing",JOptionPane.ERROR_MESSAGE);
else
{
double rad=Math.toRadians(Double.parseDouble(editor.getText()));
buf = Math.tan(rad);
Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 38
editor.setText(Double.toString(buf));
firsttime = false;
opclicked=true;
last_op = "tan";
}
}
}
}// end of tan
}
}
}
OUTPUT:

RESULT:

Thus the event driven java program to implement calculator was executed and
output verified.

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 39


VIVA QUESTIONS
1. What are the principle concepts of OOPS?
2. What is Abstraction?
3. What is Encapsulation?
4. What is Inheritance?
5. What is Polymorphism?
6. Explain the different forms of Polymorphism?
7. Define a constructor?
8. Define Destructor?
9. What is JVM?
10. What is difference between Stream classes and Reader writer classes?
11. Explain the use of RandomAccessFile classes.
12. What is object Serialization? Explain the use of Persisting object.
13. What is the difference between procedural and object-oriented programs?
14. What is multithreading and what is the class in which these methods are
defined?
15. What is the difference between applications and applets?
16. What is adapter class?
17. What is the difference between Process and Thread?
18. How do you declare a class as private?
19. What is the drawback of inheritance?
20. Why are there no global variables in Java?

General

1. What is garbage collection? How does it happen?


2. What is the difference between a constructor and a method?
3. What is a static block? How do you create a static block? Why is it used?
4. What are static variable, static method and static class?
5. What are final variable, final method and final class?
6. Why do we use finalize() method?

Abstract classes and interfaces

1. What is an abstract class?


2. What are the differences between abstract class and interface? Can you tell me
examples where we use interface and abstract class?

Exception

1. What are the differences between “NullPointerException” and “Exception”


classes?
2. What are the differences between exception and error classes?

String

1. What is the difference between “==” and “equals”


2. Can we extend String class?
3. What are the differences between String, StringBuffer and StringBuilder?

Prepared By: Ms.Vidhya.A & Ms. S. Suma Page 40

You might also like