You are on page 1of 51

CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

SYLLABUS

COURSE OBJECTIVES

CO1: To understand and apply the concepts of Classes and Objects


CO2: To develop applications using Packages and Interfaces
CO3: To understand and apply IO Streaming classes and Exception Handling
CO4: To develop a multi threaded program
CO5: To develop application using Generic programming and Event Handling.
COURSE OUTCOME

 Develop and implement Java programs for simple applications that make use of classes, packages and interfaces.
 Develop and implement Java programs with arraylist, exception handling and multithreading .
 Design applications using file processing, generic programming and event handling.

LIST OF EXPERIMENTS

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:
 First 100 units - Rs. 1 per unit
 101-200 units - Rs. 2.50 per unit
 201 -500 units - Rs. 4 per unit
 501 units - Rs. 6 per unit
If the type of the EB connection is commercial, calculate the amount to be paid as follows:
 First 100 units - Rs. 2 per unit
 101-200 units - Rs. 4.50 per unit
 201 -500 units - Rs. 6 per unit
 501 units - Rs. 7 per unit

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.

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.

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

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

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.

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


8. 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.

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.

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

11. Design a calculator using event-driven programming paradigm of Java with the following options.
a) Decimal manipulations
b) Scientific manipulations

12. Develop a mini project for any application using Java concepts.

ESEC/CSE/III SEMESTER B.E. CSE 1


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

Exp. 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:

 First 100 units - Rs. 1 per unit


 101-200 units - Rs. 2.50 per unit
 201 -500 units - Rs. 4 per unit
 501 units - Rs. 6 per unit

If the type of the EB connection is commercial, calculate the amount to be paid as follows:

 First 100 units - Rs. 2 per unit


 101-200 units - Rs. 4.50 per unit
 201 -500 units - Rs. 6 per unit
 501 units - Rs. 7 per unit

PROGRAM
import java.util.*;
class ElectricityBill
{
int cno;
String cname;
int pr;
int cr;
String atype;
int reading;
double bamount;
public ElectricityBill(int no, String name,int prev, int cur,String acc)
{
this.cno=no;
this.cname=name;
this.pr=prev;
this.cr=cur;
this.atype=acc;
}
public void calculate()
{
reading=cr-pr;
if(atype.compareToIgnoreCase("domestic")==0)
{
if(reading<=100)
bamount=reading*1.0;
if(reading>100 && reading<=200)
bamount=100+((reading-100)*2.50);
if(reading>200 && reading<=500)
bamount=100+250 + (reading-200)*4;
if(reading>500)
bamount=100+250+ 1200+(reading-500)*6;
}
else if(atype.compareToIgnoreCase("commercial")==0)
{
if(reading<=100)
bamount=reading*2.0;
if(reading>100 && reading<=200)
bamount=200+((reading-100)*4.50);
if(reading>200 && reading<=500)
bamount=200+450 + (reading-200)*6;
if(reading>500)
bamount=200+450 +1800+(reading-500)*7;
}
else
{
System.out.println("Invalid Customer Type");
System.exit(0);
}
}
public void displaybill()

ESEC/CSE/III SEMESTER B.E. CSE 2


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

{
System.out.println("\t\t Electricity Bill \n");
System.out.println("\t\t________________\n");
System.out.println("customer Name :"+cname);
System.out.println("Customer Number :"+cno);
System.out.println("Customer Type :"+atype);
System.out.println("Total Reading :"+reading);
System.out.println("Total Amount : Rs."+bamount);
}
}
public class EBBill
{

public static void main(String ss[])


{int no=0;
String name=" ";
int prev=0;
int cur=0;
String type=" ";
try
{
Scanner s= new Scanner(System.in);
System.out.println("Enter the Customer No\t");
no=s.nextInt();
System.out.println("Enter the Customer Name\t");
name=s.next();
System.out.println("Previous Month Reading\t");
prev=s.nextInt();
System.out.println("Current Month Reading\t");
cur=s.nextInt();
System.out.println("Account Type\t");
type=s.next();

}
catch(Exception ee)
{
System.out.println("Read Error");
}

ElectricityBill eb=new ElectricityBill(no,name,prev,cur,type);


eb.calculate();
eb.displaybill();

}
}
OUTPUT
G:\R17OOPSLAB\progs>java EBBill
Enter the Customer No
1
Enter the Customer Name
sivakumar
Previous Month Reading
200
Current Month Reading
280
Account Type
domestic
Electricity Bill

________________

customer Name :sivakumar


Customer Number :1
Customer Type :domestic
Total Reading :80
Total Amount : Rs.80.0

ESEC/CSE/III SEMESTER B.E. CSE 3


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

G:\R17OOPSLAB\progs>java EBBill
Enter the Customer No
1
Enter the Customer Name
siva
Previous Month Reading
200
Current Month Reading
450
Account Type
domestic
Electricity Bill

________________

customer Name :siva


Customer Number :1
Customer Type :domestic
Total Reading :250
Total Amount : Rs.550.0

G:\R17OOPSLAB\progs>

G:\R17OOPSLAB\progs>java EBBill
Enter the Customer No
1
Enter the Customer Name
siva
Previous Month Reading
200
Current Month Reading
450
Account Type
commercial
Electricity Bill

________________

customer Name :siva


Customer Number :1
Customer Type :commercial
Total Reading :250
Total Amount : Rs.950.0

G:\R17OOPSLAB\progs>java EBBill
Enter the Customer No
1
Enter the Customer Name
siva
Previous Month Reading
200
Current Month Reading
312
Account Type
jfdlj
Invalid Customer Tpe

G:\R17OOPSLAB\progs>

ESEC/CSE/III SEMESTER B.E. CSE 4


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

Exp. 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.

PROGRAM

package myconverter;
import java.text.*;

class INRtoDOLLAR
{
double value;

public INRtoDOLLAR(double inr)


{
value=inr;
}
public double convert()
{
return value/68.25;
}
}

class DOLLARtoINR
{
double value;

public DOLLARtoINR(double inr)


{
value=inr;
}
public double convert()
{
return value*68.25;
}
}

class INRtoEURO
{
double value;

public INRtoEURO(double inr)


{
value=inr;
}
public double convert()
{
return value/80.1;
}
}

class EUROtoINR
{
double value;

public EUROtoINR(double inr)


{
value=inr;
}
public double convert()
{
return value*80.10;
}
}

class INRtoYEN

ESEC/CSE/III SEMESTER B.E. CSE 5


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

{
double value;

public INRtoYEN(double inr)


{
value=inr;
}
public double convert()
{
return value/1.92;
}
}

class YENtoINR
{
double value;

public YENtoINR(double inr)


{
value=inr;
}
public double convert()
{
return value*1.92;
}
}

class MILEtoKM
{
double value;

public MILEtoKM(double inr)


{
value=inr;
}
public double convert()
{
return value*1.60;
}
}

class KMtoMILE
{
double value;

public KMtoMILE(double inr)


{
value=inr;
}
public double convert()
{
return value/1.60;
}
}

class HOURStoMINUTES
{
double value;

public HOURStoMINUTES(double inr)


{
value=inr;
}
public double convert()
{
return value*60.0;

ESEC/CSE/III SEMESTER B.E. CSE 6


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

}
}

class MINUTEStoHOURS
{
double value;

public MINUTEStoHOURS(double inr)


{
value=inr;
}
public double convert()
{
return value/60.0;
}
}

class HOURStoSECONDS
{
double value;

public HOURStoSECONDS(double inr)


{
value=inr;
}
public double convert()
{
return value*3600.0;
}
}

class SECONDStoHOURS
{
double value;

public SECONDStoHOURS(double inr)


{
value=inr;
}
public double convert()
{
return value/3600.0;
}
}

import myconverter.*;
class Convert
{
public static void main(String str[])
{
int r=500,d=54,y=350,e=250,h=2,m=324,s=1200,mile=7,km=270;

INRtoDOLLAR obj1=new INRtoDOLLAR(r);


System.out.println("The Rs. "+r+" = USD "+obj1.convert());

DOLLARtoINR obj2= new DOLLARtoINR(d);


System.out.println("The USD "+d+" = Rs."+obj2.convert());

INRtoEURO obj3=new INRtoEURO(r);


System.out.println("The Rs. "+r+" = EURO "+obj3.convert());

EUROtoINR obj4= new EUROtoINR(e);


System.out.println("The EURO "+e+" = Rs."+obj4.convert());

INRtoYEN obj5=new INRtoYEN(r);


System.out.println("The Rs. "+r+" = YEN "+obj5.convert());

ESEC/CSE/III SEMESTER B.E. CSE 7


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

YENtoINR obj6= new YENtoINR(y);


System.out.println("The YEN "+y+" = Rs."+obj6.convert());

MILEtoKM obj7=new MILEtoKM(mile);


System.out.println("The "+mile+"Mile = "+obj7.convert()+" KM");

KMtoMILE obj8=new KMtoMILE(km);


System.out.println("The "+km+" KM = "+obj8.convert()+" Mile");

HOURStoMINUTES obj9=new HOURStoMINUTES(h);


System.out.println(h+" Hours = "+obj9.convert()+" Minutes");

MINUTEStoHOURS obj10=new MINUTEStoHOURS(m);


System.out.println(m+" Minutes = "+obj10.convert()+" Hours");

HOURStoSECONDS obj11=new HOURStoSECONDS(h);


System.out.println(h+" Hours = "+obj11.convert()+" Seconcds");

SECONDStoHOURS obj12=new SECONDStoHOURS(s);


System.out.println(s+" Seconds = "+obj10.convert()+" Hours");
}
}
OUTPUT
G:\R17OOPSLAB\progs>javac Convert.java

G:\R17OOPSLAB\progs>java Convert
The Rs. 500 = USD 7.326007326007326
The USD 54 = Rs.3685.5
The Rs. 500 = EURO 6.242197253433209
The EURO 250 = Rs.20025.0
The Rs. 500 = YEN 260.4166666666667
The YEN 350 = Rs.672.0
The 7Mile = 11.200000000000001 KM
The 270 KM = 168.75 Mile
2 Hours = 120.0 Minutes
324 Minutes = 5.4 Hours
2 Hours = 7200.0 Seconcds
1200 Seconds = 5.4 Hours

G:\R17OOPSLAB\progs>

ESEC/CSE/III SEMESTER B.E. CSE 8


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

Exp. 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.

PROGRAM
import java.io.*;
import java.util.*;
class Employee
{
String ename;
int eid;
String eaddr;
String email;
String emobile;
public void getempdata()
{
Scanner sc= new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

try
{
System.out.println("Enter Employee Name ");
ename=br.readLine();
System.out.println("Enter Employee Id ");
eid=sc.nextInt();
System.out.println("Enter Address of Employee ");
eaddr=br.readLine();
System.out.println("Enter E-Mail Id ");
email=br.readLine();
System.out.println("Enter Mobile Nummber ");
emobile=br.readLine();
}
catch(IOException ie)
{
System.out.println(ie);
}
}

}
class Programmer extends Employee
{
int bpay;
double hra;
double da;
double pf;
double sclub;
double gross;
double net;
public Programmer(int pay)
{
bpay=pay;
}
public void calculate()
{
da=bpay*.97;
hra=bpay*.10;
pf=bpay*.12;
sclub=bpay*.01;
gross=bpay+da+hra;
net=gross-(pf+sclub);
}

public void displaybill()


{

System.out.println("Employee Name : "+ename);

ESEC/CSE/III SEMESTER B.E. CSE 9


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

System.out.println("Employee Id : "+eid);

System.out.println("Address of Employee :"+eaddr);


System.out.println("E-Mail Id "+email);
System.out.println("Mobile Nummber "+emobile);
System.out.println("Basic Pay : "+bpay);
System.out.println("HRA : "+hra);
System.out.println("DA : "+da);
System.out.println("PF: "+pf);
System.out.println("Staff Club : "+sclub);
System.out.println("Gross Pay : "+gross);
System.out.println("Net Pay : "+net);
}
}

class AssistantProfessor extends Employee


{
int bpay;
double hra;
double da;
double pf;
double sclub;
double gross;
double net;
public AssistantProfessor(int pay)
{
bpay=pay;
}
public void calculate()
{
da=bpay*.97;
hra=bpay*.10;
pf=bpay*.12;
sclub=bpay*.01;
gross=bpay+da+hra;
net=gross-(pf+sclub);
}

public void displaybill()


{

System.out.println("Employee Name : "+ename);


System.out.println("Employee Id : "+eid);
System.out.println("Address of Employee :"+eaddr);
System.out.println("E-Mail Id "+email);
System.out.println("Mobile Nummber "+emobile);
System.out.println("Basic Pay : "+bpay);
System.out.println("HRA : "+hra);
System.out.println("DA : "+da);
System.out.println("PF: "+pf);
System.out.println("Staff Club : "+sclub);
System.out.println("Gross Pay : "+gross);
System.out.println("Net Pay : "+net);
}

class AssociateProfessor extends Employee


{
int bpay;
double hra;
double da;
double pf;
double sclub;
double gross;
double net;

ESEC/CSE/III SEMESTER B.E. CSE 10


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

public AssociateProfessor(int pay)


{
bpay=pay;
}
public void calculate()
{
da=bpay*.97;
hra=bpay*.10;
pf=bpay*.12;
sclub=bpay*.01;
gross=bpay+da+hra;
net=gross-(pf+sclub);
}

public void displaybill()


{

System.out.println("Employee Name : "+ename);


System.out.println("Employee Id : "+eid);
System.out.println("Address of Employee :"+eaddr);
System.out.println("E-Mail Id "+email);
System.out.println("Mobile Nummber "+emobile);
System.out.println("Basic Pay : "+bpay);
System.out.println("HRA : "+hra);
System.out.println("DA : "+da);
System.out.println("PF: "+pf);
System.out.println("Staff Club : "+sclub);
System.out.println("Gross Pay : "+gross);
System.out.println("Net Pay : "+net);
}
}

class Professor extends Employee


{
int bpay;
double hra;
double da;
double pf;
double sclub;
double gross;
double net;
public Professor(int pay)
{
bpay=pay;
}
public void calculate()
{
da=bpay*.97;
hra=bpay*.10;
pf=bpay*.12;
sclub=bpay*.01;
gross=bpay+da+hra;
net=gross-(pf+sclub);
}

public void displaybill()


{

System.out.println("Employee Name : "+ename);


System.out.println("Employee Id : "+eid);
System.out.println("Address of Employee :"+eaddr);
System.out.println("E-Mail Id "+email);
System.out.println("Mobile Nummber "+emobile);
System.out.println("Basic Pay : "+bpay);
System.out.println("HRA : "+hra);
System.out.println("DA : "+da);

ESEC/CSE/III SEMESTER B.E. CSE 11


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

System.out.println("PF: "+pf);
System.out.println("Staff Club : "+sclub);
System.out.println("Gross Pay : "+gross);
System.out.println("Net Pay : "+net);
}

}
class Inherit2
{
public static void main(String str[])
{
Programmer pr=new Programmer(6000);
AssistantProfessor ap=new AssistantProfessor(16500);
AssociateProfessor asp=new AssociateProfessor(34500);
Professor p= new Professor(36000);
System.out.println("Pay Bill for Programmer ");
pr.getempdata();
pr.calculate();
pr.displaybill();

System.out.println("Pay Bill for Assistant Professor ");


ap.getempdata();
ap.calculate();
ap.displaybill();

System.out.println("Pay Bill for Associate Professor ");


asp.getempdata();
asp.calculate();
asp.displaybill();
System.out.println("Pay Bill for Professor ");
p.getempdata();
p.calculate();
p.displaybill();
}
}

OUTPUT
G:\R17OOPSLAB\progs>java Inherit2
Pay Bill for Programmer
Enter Employee Name
SIVAKUMAR
Enter Employee Id
1
Enter Address of Employee
PERUNDURAI
Enter E-Mail Id
sivakumar.g@esec.ac.in
Enter Mobile Nummber
9994244540
Employee Name : SIVAKUMAR
Employee Id : 1
Address of Employee :PERUNDURAI
E-Mail Id sivakumar.g@esec.ac.in
Mobile Nummber 9994244540
Basic Pay : 6000
HRA : 600.0
DA : 5820.0
PF: 720.0
Staff Club : 60.0
Gross Pay : 12420.0
Net Pay : 11640.0
Pay Bill for Assistant Professor
Enter Employee Name
SENTHILKUMAR
Enter Employee Id
2
Enter Address of Employee

ESEC/CSE/III SEMESTER B.E. CSE 12


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

CHENNAI
Enter E-Mail Id
senthil@gmail.com
Enter Mobile Nummber
9994244541
Employee Name : SENTHILKUMAR
Employee Id : 2
Address of Employee :CHENNAI
E-Mail Id senthil@gmail.com
Mobile Nummber 9994244541
Basic Pay : 16500
HRA : 1650.0
DA : 16005.0
PF: 1980.0
Staff Club : 165.0
Gross Pay : 34155.0
Net Pay : 32010.0
Pay Bill for Associate Professor
Enter Employee Name
KANNAN
Enter Employee Id
3
Enter Address of Employee
ERODE
Enter E-Mail Id
kannan@gmail.com
Enter Mobile Nummber
9994244542
Employee Name : KANNAN
Employee Id : 3
Address of Employee :ERODE
E-Mail Id kannan@gmail.com
Mobile Nummber 9994244542
Basic Pay : 34500
HRA : 3450.0
DA : 33465.0
PF: 4140.0
Staff Club : 345.0
Gross Pay : 71415.0
Net Pay : 66930.0
Pay Bill for Professor
Enter Employee Name
MURALI
Enter Employee Id
4
Enter Address of Employee
SALEM
Enter E-Mail Id
muralik@gmail.com
Enter Mobile Nummber
9994244543
Employee Name : MURALI
Employee Id : 4
Address of Employee :SALEM
E-Mail Id muralik@gmail.com
Mobile Nummber 9994244543
Basic Pay : 36000
HRA : 3600.0
DA : 34920.0
PF: 4320.0
Staff Club : 360.0
Gross Pay : 74520.0
Net Pay : 69840.0

G:\R17OOPSLAB\progs>

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

ESEC/CSE/III SEMESTER B.E. CSE 13


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

PROGRAM

interface StackI {

void push(int item) throws StackOverflow;

int pop() throws StackUnderflow;

boolean isEmpty();

class StackOverflow extends Exception

String msg=" ";

public StackOverflow(String title)

this.msg=title;

public String toString()

return "StackError:"+msg;

class StackUnderflow extends Exception

String msg=" ";

public StackUnderflow(String title)

this.msg=title;

public String toString()

return "StackError:"+msg;

class StackImpl implements StackI {

private int stck[];

private int tos;

StackImpl(int size)

stck = new int[size];

tos = -1;

public void push(int item) throws StackOverflow

if(tos==stck.length-1) // use length member

throw new StackOverflow("Stack Overflow");

else

{
ESEC/CSE/III SEMESTER B.E. CSE 14
CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

stck[++tos] = item;

System.out.println("Item " + item+" Pushed");

public int pop() throws StackUnderflow

if(tos < 0)

throw new StackUnderflow("Stack underflow.");

else

return stck[tos--];

public boolean isEmpty()

if(tos<0)

return true;

else

return false;

class StackTest {

public static void main(String args[]) {

StackImpl mystack1 = new StackImpl(5);

StackImpl mystack2 = new StackImpl(8);

// push some numbers onto the stack

try

System.out.println("Capacity of Stack1 is 5 ");

for(int i=0; i<5; i++) mystack1.push(i);

System.out.println("Capacity of Stack2 is 8 ");

for(int i=0; i<9; i++) mystack2.push(i);

catch(StackOverflow sov)

System.out.println(sov);

// pop those numbers off the stack

try

System.out.println("Items in mystack1:");

for(int i=0; i<5; i++)

System.out.println(mystack1.pop());

System.out.println("Items in mystack2:");

for(int i=0; i<10; i++)

System.out.println(mystack2.pop());

}
ESEC/CSE/III SEMESTER B.E. CSE 15
CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

catch(StackUnderflow suf)

System.out.println(suf);

if(mystack1.isEmpty())

System.out.println("The stack1 is empty");

if(mystack2.isEmpty())

System.out.println("The stack2 is empty");

OUTPUT

G:\R17OOPSLAB\progs>java StackTest
Capacity of Stack1 is 5
Item 0 Pushed
Item 1 Pushed
Item 2 Pushed
Item 3 Pushed
Item 4 Pushed
Capacity of Stack2 is 8
Item 0 Pushed
Item 1 Pushed
Item 2 Pushed
Item 3 Pushed
Item 4 Pushed
Item 5 Pushed
Item 6 Pushed
Item 7 Pushed
StackError:Stack Overflow
Items in mystack1:
4
3
2
1
0
Items in mystack2:
7
6
5
4
3
2
1
0
StackError:Stack underflow.
The stack1 is empty
The stack2 is empty
G:\R17OOPSLAB\progs>

Exp. No. 5. Write a program to perform string operations using ArrayList. Write functions for the following

ESEC/CSE/III SEMESTER B.E. CSE 16


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

a. Append - add at end


b. Insert – add at particular index
c. Search
d. List all string starts with given letter

PROGRAM
import java.io.*;
import java.util.*;
class StringOp
{
public static void main(String args[]) throws IOException
{
int ch=0;
String str=null;
ArrayList<String> al= new ArrayList<String>();
do
{
System.out.println("String Operations using ArrayList");
System.out.println("1. Append - add at end ");
System.out.println("2. Insert at particular index");
System.out.println("3. Search");
System.out.println("4. List all string starts with given letter");
System.out.println("5. Exit");
System.out.println("Enter your Choice :");
Scanner sc= new Scanner(System.in);
ch=sc.nextInt();

switch(ch)
{

case 1:
try
{
System.out.println("Enter the String to be appended at end :");
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
str=br.readLine();
}
catch(IOException ie)
{
System.out.println(ie);
}
al.add(str);
System.out.println("Item Added at the end");
break;

case 2:
System.out.println("Enter the Position: ");
try
{

Scanner sc1= new Scanner(System.in);


int p=sc1.nextInt();

System.out.println("Enter the String to be inserted :");


BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
str=br.readLine();
al.add(p,str);
System.out.println("Item inserted at the position "+p);
}
catch(IOException ie)
{
System.out.println(ie);
}
break;
case 3:
boolean res=false;

ESEC/CSE/III SEMESTER B.E. CSE 17


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

System.out.println("Enter the item to search ;");


try
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
str=br.readLine();
for(String obj:al)
{
if(obj.equals(str))
{
res=true;
break;
}
}
if(res)
System.out.println("Item found ");
else
System.out.println("Item Not found ");
}
catch(IOException ie)
{
System.out.println(ie);
}

break;
case 4:
System.out.println("The elements of array list are ");
System.out.println(al);
break;
}
}while (ch>0 && ch<5);
}
}
OUTPUT

G:\R17OOPSLAB\progs>javac StringOp.java

G:\R17OOPSLAB\progs>java StringOp
String Operations using ArrayList
1. Append - add at end
2. Insert at particular index
3. Search
4. List all string starts with given letter
5. Exit
Enter your Choice :
1
Enter the String to be appended at end :
siva
Item Added at the end
String Operations using ArrayList
1. Append - add at end
2. Insert at particular index
3. Search
4. List all string starts with given letter
5. Exit
Enter your Choice :
1
Enter the String to be appended at end :
senthil
Item Added at the end
String Operations using ArrayList
1. Append - add at end
2. Insert at particular index
3. Search
4. List all string starts with given letter
5. Exit
Enter your Choice :
1

ESEC/CSE/III SEMESTER B.E. CSE 18


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

Enter the String to be appended at end :


kannan
Item Added at the end
String Operations using ArrayList
1. Append - add at end
2. Insert at particular index
3. Search
4. List all string starts with given letter
5. Exit
Enter your Choice :
2
Enter the Position:
1
Enter the String to be inserted :
murugan
Item inserted at the position 1
String Operations using ArrayList
1. Append - add at end
2. Insert at particular index
3. Search
4. List all string starts with given letter
5. Exit
Enter your Choice :
4
The elements of array list are
[siva, murugan, senthil, kannan]
String Operations using ArrayList
1. Append - add at end
2. Insert at particular index
3. Search
4. List all string starts with given letter
5. Exit
Enter your Choice :
3
Enter the item to search ;
senthil
Item found
String Operations using ArrayList
1. Append - add at end
2. Insert at particular index
3. Search
4. List all string starts with given letter
5. Exit
Enter your Choice :
3
Enter the item to search ;
arun
Item Not found
String Operations using ArrayList
1. Append - add at end
2. Insert at particular index
3. Search
4. List all string starts with given letter
5. Exit
Enter your Choice :
5

G:\R17OOPSLAB\progs>

ESEC/CSE/III SEMESTER B.E. CSE 19


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

Exp. 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.

PROGRAM
abstract class Shape
{
int no1,no2;
public abstract void printArea();
}
class Rectangle extends Shape
{
public Rectangle(int h,int w)
{
no1=h;
no2=w;
}
public void printArea()
{
System.out.println("Area of Rectangle is "+ (no1*no2));
}
}
class Circle extends Shape
{
public Circle(int r)
{
no1=r;
}
public void printArea()
{
System.out.println("Area of Circle is "+ (3.14*no1*no1));
}
}

class Triangle extends Shape


{
public Triangle(int b,int h)
{
no1=b;
no2=h;
}
public void printArea()
{
System.out.println("Area of Triangle is "+ (no1*no2)/2);
}
}

class Inherit1
{
public static void main(String str[])
{
Rectangle r= new Rectangle(3,4);
r.printArea();
Circle c= new Circle(5);
c.printArea();
Triangle t= new Triangle(3,4);
t.printArea();
}
}

OUTPUT

G:\R17OOPSLAB\progs>java Inherit1
Area of Rectangle is 12
Area of Circle is 78.5
Area of Triangle is 6

ESEC/CSE/III SEMESTER B.E. CSE 20


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

Exp. No. 7. Write a Java program to implement user defined exception handling.

PROGRAM

import java.io.*;

class MobileNumberException extends Exception

{
String str;
public MobileNumberException(String test)
{
str=test;
}
public String toString()
{
return "MobileNumberException : The Mobile Number has only "+str.length()+" digits / Contains Characters";
}
}

class MobileExp
{
public static void main(String str[])
{
String num=null;
try
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Mobile Number ");
num=br.readLine();
}
catch(IOException ie)
{
System.out.println("IO Error " +ie);
}
try
{
if(num.length()==10 && num.matches("[0-9]+"))
System.out.println("Correct Mobile Number");
else
throw new MobileNumberException(num);
}
catch(MobileNumberException me)
{
System.out.println(me);
}
}
}

OUTPUT

G:\R17OOPSLAB\progs>javac MobileExp.java

G:\R17OOPSLAB\progs>java MobileExp

Enter the Mobile Number

9994244540

Correct Mobile Number

G:\R17OOPSLAB\progs>java MobileExp

Enter the Mobile Number

9382

MobileNumberException : The Mobile Number has only 4 digits / Contains Characters

G:\R17OOPSLAB\progs>java MobileExp

Enter the Mobile Number

abdef

MobileNumberException : The Mobile Number has only 5 digits / Contains Characters

G:\R17OOPSLAB\progs>
ESEC/CSE/III SEMESTER B.E. CSE 21
CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

Exp. No. 8. 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.
PROGRAM

import java.io.*;
import java.util.*;
class FileDetails
{
public static void main(String str[])
{
String fname=null;
try
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter File Name ");
fname=br.readLine();
}
catch(IOException ie)
{
System.out.println("IO Error " +ie);
}
File f= new File(fname);
if(f.exists())
System.out.println("File Exists");
else
System.out.println("File Not Available");
if(f.canWrite())
System.out.println("File has Write Permission");
if(f.canRead())
System.out.println("File has Read Permission");
if(f.canExecute())
System.out.println("File has Execute Permission");
System.out.println("File size is :"+f.length());
System.out.println("Last Modified Date :"+new Date(f.lastModified()));
}
}
OUTPUT

G:\R17OOPSLAB\progs>javac FileDetails.java

G:\R17OOPSLAB\progs>java FileDetails

Enter File Name

EBBill.java

File Exists

File has Write Permission

File has Read Permission

File has Execute Permission

File size is :2046

Last Modified Date :Mon Jun 18 19:45:59 IST 2018

G:\R17OOPSLAB\progs>

Exp. 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.

ESEC/CSE/III SEMESTER B.E. CSE 22


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

PROGRAM
import java.util.*;
class SquareThread extends Thread
{
public int n;
public SquareThread(int no)
{
this.n = no;
System.out.println("Square Thread Started");
start();
}
public void run()
{
System.out.println("The Square of the Random Number " + n + " is "+(n*n));
}
}
class CubeThread extends Thread
{
public int n;
public CubeThread(int no)
{
this.n = no;
System.out.println("Cube Thread Started");
start();
}
public void run()
{
System.out.println("The Cube of the Random Number " + n + " is "+(n*n*n));
}
}
class RandThread extends Thread
{
public RandThread()
{
start();
}
public void run()
{
int v = 0;
Random r = new Random();
try
{
for (int i = 1; i<=10; i++)
{
v = r.nextInt(100);
System.out.println("Generated Random Number is " + v);
if (v % 2 == 0)
new SquareThread(v);
else
new CubeThread(v);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Randon Number Thread Interrupted");
}
}
}
public class MultiThreadDemo
{

public static void main(String[] args)


{
RandThread r = new RandThread();
}
}

ESEC/CSE/III SEMESTER B.E. CSE 23


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

OUTPUT
G:\R17OOPSLAB\progs>java MultiThreadDemo
Generated Random Number is 25
Cube Thread Started
The Cube of the Random Number 25 is 15625
Generated Random Number is 96
Square Thread Started
The Square of the Random Number 96 is 9216
Generated Random Number is 84
Square Thread Started
The Square of the Random Number 84 is 7056
Generated Random Number is 45
Cube Thread Started
The Cube of the Random Number 45 is 91125
Generated Random Number is 92
Square Thread Started
The Square of the Random Number 92 is 8464
Generated Random Number is 40
Square Thread Started
The Square of the Random Number 40 is 1600
Generated Random Number is 90
Square Thread Started
The Square of the Random Number 90 is 8100
Generated Random Number is 56
Square Thread Started
The Square of the Random Number 56 is 3136
Generated Random Number is 30
Square Thread Started
The Square of the Random Number 30 is 900
Generated Random Number is 86
Square Thread Started
The Square of the Random Number 86 is 7396

G:\R17OOPSLAB\progs>

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

PROGRAM

ESEC/CSE/III SEMESTER B.E. CSE 24


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

import java.util.*;
class Generic1{

public static < E > void findMax(E[] elements)


{
Arrays.sort(elements);
System.out.println("The Maximum Element is " + elements[elements.length-1]);
}

public static void main( String args[] ) {


Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'J', 'A', 'V', 'A', 'T','P','O','I','N','T' };
Double[] doubleArray={1.5,2.5,3.9,22.5,9.0};

findMax( intArray );

findMax( charArray );
findMax(doubleArray);
}
}

OUTPUT

G:\R17OOPSLAB\progs>javac Generic1.java

G:\R17OOPSLAB\progs>java Generic1
The Maximum Element is 50
The Maximum Element is V
The Maximum Element is 22.5

G:\R17OOPSLAB\progs>

Exp. No. 11. Design a calculator using event-driven programming paradigm of Java with the following options.
a) Decimal manipulations
b) Scientific manipulations

ESEC/CSE/III SEMESTER B.E. CSE 25


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

PROGRAM
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;

public class ScientificCalculator extends JFrame implements ActionListener {


JTextField tfield;
double temp, temp1, result, a;
static double m1, m2;
int k = 1, x = 0, y = 0, z = 0;
char ch;
JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, zero, clr, pow2, pow3, exp,
fac, plus, min, div, log, rec, mul, eq, addSub, dot, sqrt, sin, cos, tan;
Container cont;
JPanel textPanel, buttonpanel;

ScientificCalculator() {
cont = getContentPane();
cont.setLayout(new BorderLayout());
JPanel textpanel = new JPanel();
tfield = new JTextField(25);
tfield.setHorizontalAlignment(SwingConstants.RIGHT);
tfield.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent keyevent) {
char c = keyevent.getKeyChar();
if (c >= '0' && c <= '9') {
} else {
keyevent.consume();
}
}
});
textpanel.add(tfield);
buttonpanel = new JPanel();
buttonpanel.setLayout(new GridLayout(8, 4, 2, 2));
boolean t = true;
b1 = new JButton("1");
buttonpanel.add(b1);
b1.addActionListener(this);
b2 = new JButton("2");
buttonpanel.add(b2);
b2.addActionListener(this);
b3 = new JButton("3");
buttonpanel.add(b3);
b3.addActionListener(this);

b4 = new JButton("4");
buttonpanel.add(b4);
b4.addActionListener(this);
b5 = new JButton("5");
buttonpanel.add(b5);
b5.addActionListener(this);
b6 = new JButton("6");
buttonpanel.add(b6);
b6.addActionListener(this);

b7 = new JButton("7");
buttonpanel.add(b7);
b7.addActionListener(this);
b8 = new JButton("8");
ESEC/CSE/III SEMESTER B.E. CSE 26
CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

buttonpanel.add(b8);
b8.addActionListener(this);
b9 = new JButton("9");
buttonpanel.add(b9);
b9.addActionListener(this);

zero = new JButton("0");


buttonpanel.add(zero);
zero.addActionListener(this);

plus = new JButton("+");


buttonpanel.add(plus);
plus.addActionListener(this);

min = new JButton("-");


buttonpanel.add(min);
min.addActionListener(this);

mul = new JButton("*");


buttonpanel.add(mul);
mul.addActionListener(this);

div = new JButton("/");


div.addActionListener(this);
buttonpanel.add(div);

addSub = new JButton("+/-");


buttonpanel.add(addSub);
addSub.addActionListener(this);

dot = new JButton(".");


buttonpanel.add(dot);
dot.addActionListener(this);

eq = new JButton("=");
buttonpanel.add(eq);
eq.addActionListener(this);

rec = new JButton("1/x");


buttonpanel.add(rec);
rec.addActionListener(this);
sqrt = new JButton("Sqrt");
buttonpanel.add(sqrt);
sqrt.addActionListener(this);
log = new JButton("log");
buttonpanel.add(log);
log.addActionListener(this);

sin = new JButton("SIN");


buttonpanel.add(sin);
sin.addActionListener(this);
cos = new JButton("COS");
buttonpanel.add(cos);
cos.addActionListener(this);
tan = new JButton("TAN");
buttonpanel.add(tan);
tan.addActionListener(this);
pow2 = new JButton("x^2");
buttonpanel.add(pow2);
pow2.addActionListener(this);
ESEC/CSE/III SEMESTER B.E. CSE 27
CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

pow3 = new JButton("x^3");


buttonpanel.add(pow3);
pow3.addActionListener(this);
exp = new JButton("Exp");
exp.addActionListener(this);
buttonpanel.add(exp);
fac = new JButton("n!");
fac.addActionListener(this);
buttonpanel.add(fac);

clr = new JButton("AC");


buttonpanel.add(clr);
clr.addActionListener(this);
cont.add("Center", buttonpanel);
cont.add("North", textpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void actionPerformed(ActionEvent e) {


String s = e.getActionCommand();
if (s.equals("1")) {
if (z == 0) {
tfield.setText(tfield.getText() + "1");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "1");
z = 0;
}
}
if (s.equals("2")) {
if (z == 0) {
tfield.setText(tfield.getText() + "2");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "2");
z = 0;
}
}
if (s.equals("3")) {
if (z == 0) {
tfield.setText(tfield.getText() + "3");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "3");
z = 0;
}
}
if (s.equals("4")) {
if (z == 0) {
tfield.setText(tfield.getText() + "4");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "4");
z = 0;
}
}
if (s.equals("5")) {
if (z == 0) {
tfield.setText(tfield.getText() + "5");
} else {
ESEC/CSE/III SEMESTER B.E. CSE 28
CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

tfield.setText("");
tfield.setText(tfield.getText() + "5");
z = 0;
}
}
if (s.equals("6")) {
if (z == 0) {
tfield.setText(tfield.getText() + "6");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "6");
z = 0;
}
}
if (s.equals("7")) {
if (z == 0) {
tfield.setText(tfield.getText() + "7");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "7");
z = 0;
}
}
if (s.equals("8")) {
if (z == 0) {
tfield.setText(tfield.getText() + "8");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "8");
z = 0;
}
}
if (s.equals("9")) {
if (z == 0) {
tfield.setText(tfield.getText() + "9");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "9");
z = 0;
}
}
if (s.equals("0")) {
if (z == 0) {
tfield.setText(tfield.getText() + "0");
} else {
tfield.setText("");
tfield.setText(tfield.getText() + "0");
z = 0;
}
}
if (s.equals("AC")) {
tfield.setText("");
x = 0;
y = 0;
z = 0;
}
if (s.equals("log")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
ESEC/CSE/III SEMESTER B.E. CSE 29
CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

a=

Math.log(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("1/x")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a=1/

Double.parseDouble(tfield.getText());
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("Exp")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a=

Math.exp(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("x^2")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a=

Math.pow(Double.parseDouble(tfield.getText()), 2);
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("x^3")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a=

Math.pow(Double.parseDouble(tfield.getText()), 3);
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("+/-")) {
if (x == 0) {
tfield.setText("-" + tfield.getText());
x = 1;
} else {
tfield.setText(tfield.getText());
}
}
if (s.equals(".")) {

ESEC/CSE/III SEMESTER B.E. CSE 30


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

if (y == 0) {
tfield.setText(tfield.getText() + ".");
y = 1;
} else {
tfield.setText(tfield.getText());
}
}
if (s.equals("+")) {
if (tfield.getText().equals("")) {
tfield.setText("");
temp = 0;
ch = '+';
} else {
temp = Double.parseDouble(tfield.getText());
tfield.setText("");
ch = '+';
y = 0;
x = 0;
}
tfield.requestFocus();
}
if (s.equals("-")) {
if (tfield.getText().equals("")) {
tfield.setText("");
temp = 0;
ch = '-';
} else {
x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText());
tfield.setText("");
ch = '-';
}
tfield.requestFocus();
}
if (s.equals("/")) {
if (tfield.getText().equals("")) {
tfield.setText("");
temp = 1;
ch = '/';
} else {
x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText());
ch = '/';
tfield.setText("");
}
tfield.requestFocus();
}
if (s.equals("*")) {
if (tfield.getText().equals("")) {
tfield.setText("");
temp = 1;
ch = '*';
} else {
x = 0;
y = 0;
temp = Double.parseDouble(tfield.getText());
ch = '*';
tfield.setText("");
ESEC/CSE/III SEMESTER B.E. CSE 31
CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

}
tfield.requestFocus();
}
if (s.equals("MC")) {
m1 = 0;
tfield.setText("");
}
if (s.equals("MR")) {
tfield.setText("");
tfield.setText(tfield.getText() + m1);
}
if (s.equals("M+")) {
if (k == 1) {
m1 = Double.parseDouble(tfield.getText());
k++;
} else {
m1 += Double.parseDouble(tfield.getText());
tfield.setText("" + m1);
}
}
if (s.equals("M-")) {
if (k == 1) {
m1 = Double.parseDouble(tfield.getText());
k++;
} else {
m1 -= Double.parseDouble(tfield.getText());
tfield.setText("" + m1);
}
}
if (s.equals("Sqrt")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a=

Math.sqrt(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("SIN")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a=

Math.sin(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("COS")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a=

Math.cos(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);

ESEC/CSE/III SEMESTER B.E. CSE 32


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

}
}
if (s.equals("TAN")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a=

Math.tan(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
if (s.equals("=")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
temp1 =

Double.parseDouble(tfield.getText());
switch (ch) {
case '+':
result = temp + temp1;
break;
case '-':
result = temp - temp1;
break;
case '/':
result = temp / temp1;
break;
case '*':
result = temp * temp1;
break;
}
tfield.setText("");
tfield.setText(tfield.getText() + result);
z = 1;
}
}
if (s.equals("n!")) {
if (tfield.getText().equals("")) {
tfield.setText("");
} else {
a=

fact(Double.parseDouble(tfield.getText()));
tfield.setText("");
tfield.setText(tfield.getText() + a);
}
}
tfield.requestFocus();
}

double fact(double x) {
int er = 0;
if (x < 0) {
er = 20;
return 0;
}
double i, s = 1;

ESEC/CSE/III SEMESTER B.E. CSE 33


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

for (i = 2; i <= x; i += 1.0)


s *= i;
return s;
}

public static void main(String args[]) {


try {
UIManager

.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
}
ScientificCalculator f = new ScientificCalculator();
f.setTitle("ScientificCalculator");
f.pack();
f.setVisible(true);
}
}
OUTPUT

12. Develop a mini project for any application using Java concepts.

Notepad Application in java


import java.io.*;

ESEC/CSE/III SEMESTER B.E. CSE 34


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

import java.util.Date;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

class FileOperation
{
Notepad npd;

boolean saved;
boolean newFileFlag;
String fileName;
String applicationTitle="Notepad - JavaTpoint";

File fileRef;
JFileChooser chooser;
boolean isSave(){return saved;}
void setSave(boolean saved){this.saved=saved;}
String getFileName(){return new String(fileName);}
void setFileName(String fileName){this.fileName=new String(fileName);}
FileOperation(Notepad npd)
{
this.npd=npd;

saved=true;
newFileFlag=true;
fileName=new String("Untitled");
fileRef=new File(fileName);
this.npd.f.setTitle(fileName+" - "+applicationTitle);

chooser=new JFileChooser();
chooser.addChoosableFileFilter(new MyFileFilter(".java","Java Source Files(*.java)"));
chooser.addChoosableFileFilter(new MyFileFilter(".txt","Text Files(*.txt)"));
chooser.setCurrentDirectory(new File("."));

boolean saveFile(File temp)


{
FileWriter fout=null;
try
{
fout=new FileWriter(temp);
fout.write(npd.ta.getText());
}
catch(IOException ioe){updateStatus(temp,false);return false;}
finally
{try{fout.close();}catch(IOException excp){}}
updateStatus(temp,true);
return true;
}
boolean saveThisFile()
{

if(!newFileFlag)
{return saveFile(fileRef);}

return saveAsFile();
}
boolean saveAsFile()
{
File temp=null;
chooser.setDialogTitle("Save As...");
chooser.setApproveButtonText("Save Now");
chooser.setApproveButtonMnemonic(KeyEvent.VK_S);
chooser.setApproveButtonToolTipText("Click me to save!");

ESEC/CSE/III SEMESTER B.E. CSE 35


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

do
{
if(chooser.showSaveDialog(this.npd.f)!=JFileChooser.APPROVE_OPTION)
return false;
temp=chooser.getSelectedFile();
if(!temp.exists()) break;
if( JOptionPane.showConfirmDialog(
this.npd.f,"<html>"+temp.getPath()+" already exists.<br>Do you want to replace it?<html>",
"Save As",JOptionPane.YES_NO_OPTION
)==JOptionPane.YES_OPTION)
break;
}while(true);

return saveFile(temp);
}

boolean openFile(File temp)


{
FileInputStream fin=null;
BufferedReader din=null;

try
{
fin=new FileInputStream(temp);
din=new BufferedReader(new InputStreamReader(fin));
String str=" ";
while(str!=null)
{
str=din.readLine();
if(str==null)
break;
this.npd.ta.append(str+"\n");
}

}
catch(IOException ioe){updateStatus(temp,false);return false;}
finally
{try{din.close();fin.close();}catch(IOException excp){}}
updateStatus(temp,true);
this.npd.ta.setCaretPosition(0);
return true;
}
void openFile()
{
if(!confirmSave()) return;
chooser.setDialogTitle("Open File...");
chooser.setApproveButtonText("Open this");
chooser.setApproveButtonMnemonic(KeyEvent.VK_O);
chooser.setApproveButtonToolTipText("Click me to open the selected file.!");

File temp=null;
do
{
if(chooser.showOpenDialog(this.npd.f)!=JFileChooser.APPROVE_OPTION)
return;
temp=chooser.getSelectedFile();

if(temp.exists()) break;

JOptionPane.showMessageDialog(this.npd.f,
"<html>"+temp.getName()+"<br>file not found.<br>"+
"Please verify the correct file name was given.<html>",
"Open", JOptionPane.INFORMATION_MESSAGE);

} while(true);

ESEC/CSE/III SEMESTER B.E. CSE 36


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

this.npd.ta.setText("");

if(!openFile(temp))
{
fileName="Untitled"; saved=true;
this.npd.f.setTitle(fileName+" - "+applicationTitle);
}
if(!temp.canWrite())
newFileFlag=true;

void updateStatus(File temp,boolean saved)


{
if(saved)
{
this.saved=true;
fileName=new String(temp.getName());
if(!temp.canWrite())
{fileName+="(Read only)"; newFileFlag=true;}
fileRef=temp;
npd.f.setTitle(fileName + " - "+applicationTitle);
npd.statusBar.setText("File : "+temp.getPath()+" saved/opened successfully.");
newFileFlag=false;
}
else
{
npd.statusBar.setText("Failed to save/open : "+temp.getPath());
}
}
boolean confirmSave()
{
String strMsg="<html>The text in the "+fileName+" file has been changed.<br>"+
"Do you want to save the changes?<html>";
if(!saved)
{
int x=JOptionPane.showConfirmDialog(this.npd.f,strMsg,applicationTitle,
JOptionPane.YES_NO_CANCEL_OPTION);

if(x==JOptionPane.CANCEL_OPTION) return false;


if(x==JOptionPane.YES_OPTION && !saveAsFile()) return false;
}
return true;
}
void newFile()
{
if(!confirmSave()) return;

this.npd.ta.setText("");
fileName=new String("Untitled");
fileRef=new File(fileName);
saved=true;
newFileFlag=true;
this.npd.f.setTitle(fileName+" - "+applicationTitle);
}
}// end defination of class FileOperation
/************************************/
public class Notepad implements ActionListener, MenuConstants
{

JFrame f;
JTextArea ta;
JLabel statusBar;

private String fileName="Untitled";


private boolean saved=true;

ESEC/CSE/III SEMESTER B.E. CSE 37


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

String applicationName="Javapad";

String searchString, replaceString;


int lastSearchIndex;

FileOperation fileHandler;
FontChooser fontDialog=null;
FindDialog findReplaceDialog=null;
JColorChooser bcolorChooser=null;
JColorChooser fcolorChooser=null;
JDialog backgroundDialog=null;
JDialog foregroundDialog=null;
JMenuItem cutItem,copyItem, deleteItem, findItem, findNextItem,
replaceItem, gotoItem, selectAllItem;
Notepad()
{
f=new JFrame(fileName+" - "+applicationName);
ta=new JTextArea(30,60);
statusBar=new JLabel("|| Ln 1, Col 1 ",JLabel.RIGHT);
f.add(new JScrollPane(ta),BorderLayout.CENTER);
f.add(statusBar,BorderLayout.SOUTH);
f.add(new JLabel(" "),BorderLayout.EAST);
f.add(new JLabel(" "),BorderLayout.WEST);
createMenuBar(f);
//f.setSize(350,350);
f.pack();
f.setLocation(100,50);
f.setVisible(true);
f.setLocation(150,50);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

fileHandler=new FileOperation(this);

ta.addCaretListener(
new CaretListener()
{
public void caretUpdate(CaretEvent e)
{
int lineNumber=0, column=0, pos=0;

try
{
pos=ta.getCaretPosition();
lineNumber=ta.getLineOfOffset(pos);
column=pos-ta.getLineStartOffset(lineNumber);
}catch(Exception excp){}
if(ta.getText().length()==0){lineNumber=0; column=0;}
statusBar.setText("|| Ln "+(lineNumber+1)+", Col "+(column+1));
}
});
DocumentListener myListener = new DocumentListener()
{
public void changedUpdate(DocumentEvent e){fileHandler.saved=false;}
public void removeUpdate(DocumentEvent e){fileHandler.saved=false;}
public void insertUpdate(DocumentEvent e){fileHandler.saved=false;}
};
ta.getDocument().addDocumentListener(myListener);
WindowListener frameClose=new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
if(fileHandler.confirmSave())System.exit(0);
}
};
f.addWindowListener(frameClose);
//////////////////
/*

ESEC/CSE/III SEMESTER B.E. CSE 38


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

ta.append("Hello dear hello hi");


ta.append("\nwho are u dear mister hello");
ta.append("\nhello bye hel");
ta.append("\nHello");
ta.append("\nMiss u mister hello hell");
fileHandler.saved=true;
*/
}
////////////////////////////////////
void goTo()
{
int lineNumber=0;
try
{
lineNumber=ta.getLineOfOffset(ta.getCaretPosition())+1;
String tempStr=JOptionPane.showInputDialog(f,"Enter Line Number:",""+lineNumber);
if(tempStr==null)
{return;}
lineNumber=Integer.parseInt(tempStr);
ta.setCaretPosition(ta.getLineStartOffset(lineNumber-1));
}catch(Exception e){}
}
public void actionPerformed(ActionEvent ev)
{
String cmdText=ev.getActionCommand();
if(cmdText.equals(fileNew))
fileHandler.newFile();
else if(cmdText.equals(fileOpen))
fileHandler.openFile();
else if(cmdText.equals(fileSave))
fileHandler.saveThisFile();
else if(cmdText.equals(fileSaveAs))
fileHandler.saveAsFile();
else if(cmdText.equals(fileExit))
{if(fileHandler.confirmSave())System.exit(0);}
else if(cmdText.equals(filePrint))
JOptionPane.showMessageDialog(
Notepad.this.f,
"Get ur printer repaired first! It seems u dont have one!",
"Bad Printer",
JOptionPane.INFORMATION_MESSAGE
);
else if(cmdText.equals(editCut))
ta.cut();
else if(cmdText.equals(editCopy))
ta.copy();
else if(cmdText.equals(editPaste))
ta.paste();
else if(cmdText.equals(editDelete))
ta.replaceSelection("");
else if(cmdText.equals(editFind))
{
if(Notepad.this.ta.getText().length()==0)
return; // text box have no text
if(findReplaceDialog==null)
findReplaceDialog=new FindDialog(Notepad.this.ta);
findReplaceDialog.showDialog(Notepad.this.f,true);//find
}
else if(cmdText.equals(editFindNext))
{
if(Notepad.this.ta.getText().length()==0)
return; // text box have no text

if(findReplaceDialog==null)
statusBar.setText("Use Find option of Edit Menu first !!!!");
else
findReplaceDialog.findNextWithSelection();

ESEC/CSE/III SEMESTER B.E. CSE 39


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

}
else if(cmdText.equals(editReplace))
{
if(Notepad.this.ta.getText().length()==0)
return; // text box have no text

if(findReplaceDialog==null)
findReplaceDialog=new FindDialog(Notepad.this.ta);
findReplaceDialog.showDialog(Notepad.this.f,false);//replace
}
else if(cmdText.equals(editGoTo))
{
if(Notepad.this.ta.getText().length()==0)
return; // text box have no text
goTo();
}
else if(cmdText.equals(editSelectAll))
ta.selectAll();
else if(cmdText.equals(editTimeDate))
ta.insert(new Date().toString(),ta.getSelectionStart());
else if(cmdText.equals(formatWordWrap))
{
JCheckBoxMenuItem temp=(JCheckBoxMenuItem)ev.getSource();
ta.setLineWrap(temp.isSelected());
}
////////////////////////////////////
else if(cmdText.equals(formatFont))
{
if(fontDialog==null)
fontDialog=new FontChooser(ta.getFont());

if(fontDialog.showDialog(Notepad.this.f,"Choose a font"))
Notepad.this.ta.setFont(fontDialog.createFont());
}
////////////////////////////////////
else if(cmdText.equals(formatForeground))
showForegroundColorDialog();
////////////////////////////////////
else if(cmdText.equals(formatBackground))
showBackgroundColorDialog();
////////////////////////////////////

else if(cmdText.equals(viewStatusBar))
{
JCheckBoxMenuItem temp=(JCheckBoxMenuItem)ev.getSource();
statusBar.setVisible(temp.isSelected());
}
////////////////////////////////////
else if(cmdText.equals(helpAboutNotepad))
{
JOptionPane.showMessageDialog(Notepad.this.f,aboutText,"Dedicated 2 u!",
JOptionPane.INFORMATION_MESSAGE);
}
else
statusBar.setText("This "+cmdText+" command is yet to be implemented");
}//action Performed
void showBackgroundColorDialog()
{
if(bcolorChooser==null)
bcolorChooser=new JColorChooser();
if(backgroundDialog==null)
backgroundDialog=JColorChooser.createDialog
(Notepad.this.f,
formatBackground,
false,
bcolorChooser,
new ActionListener()

ESEC/CSE/III SEMESTER B.E. CSE 40


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

{public void actionPerformed(ActionEvent evvv){


Notepad.this.ta.setBackground(bcolorChooser.getColor());}},
null);

backgroundDialog.setVisible(true);
}
void showForegroundColorDialog()
{
if(fcolorChooser==null)
fcolorChooser=new JColorChooser();
if(foregroundDialog==null)
foregroundDialog=JColorChooser.createDialog
(Notepad.this.f,
formatForeground,
false,
fcolorChooser,
new ActionListener()
{public void actionPerformed(ActionEvent evvv){
Notepad.this.ta.setForeground(fcolorChooser.getColor());}},
null);

foregroundDialog.setVisible(true);
}

JMenuItem createMenuItem(String s, int key,JMenu toMenu,ActionListener al)


{
JMenuItem temp=new JMenuItem(s,key);
temp.addActionListener(al);
toMenu.add(temp);

return temp;
}
JMenuItem createMenuItem(String s, int key,JMenu toMenu,int aclKey,ActionListener al)
{
JMenuItem temp=new JMenuItem(s,key);
temp.addActionListener(al);
temp.setAccelerator(KeyStroke.getKeyStroke(aclKey,ActionEvent.CTRL_MASK));
toMenu.add(temp);

return temp;
}
JCheckBoxMenuItem createCheckBoxMenuItem(String s,
int key,JMenu toMenu,ActionListener al)
{
JCheckBoxMenuItem temp=new JCheckBoxMenuItem(s);
temp.setMnemonic(key);
temp.addActionListener(al);
temp.setSelected(false);
toMenu.add(temp);

return temp;
}
JMenu createMenu(String s,int key,JMenuBar toMenuBar)
{
JMenu temp=new JMenu(s);
temp.setMnemonic(key);
toMenuBar.add(temp);
return temp;
}
/*********************************/
void createMenuBar(JFrame f)
{
JMenuBar mb=new JMenuBar();
JMenuItem temp;

JMenu fileMenu=createMenu(fileText,KeyEvent.VK_F,mb);
JMenu editMenu=createMenu(editText,KeyEvent.VK_E,mb);

ESEC/CSE/III SEMESTER B.E. CSE 41


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

JMenu formatMenu=createMenu(formatText,KeyEvent.VK_O,mb);
JMenu viewMenu=createMenu(viewText,KeyEvent.VK_V,mb);
JMenu helpMenu=createMenu(helpText,KeyEvent.VK_H,mb);

createMenuItem(fileNew,KeyEvent.VK_N,fileMenu,KeyEvent.VK_N,this);
createMenuItem(fileOpen,KeyEvent.VK_O,fileMenu,KeyEvent.VK_O,this);
createMenuItem(fileSave,KeyEvent.VK_S,fileMenu,KeyEvent.VK_S,this);
createMenuItem(fileSaveAs,KeyEvent.VK_A,fileMenu,this);
fileMenu.addSeparator();
temp=createMenuItem(filePageSetup,KeyEvent.VK_U,fileMenu,this);
temp.setEnabled(false);
createMenuItem(filePrint,KeyEvent.VK_P,fileMenu,KeyEvent.VK_P,this);
fileMenu.addSeparator();
createMenuItem(fileExit,KeyEvent.VK_X,fileMenu,this);

temp=createMenuItem(editUndo,KeyEvent.VK_U,editMenu,KeyEvent.VK_Z,this);
temp.setEnabled(false);
editMenu.addSeparator();
cutItem=createMenuItem(editCut,KeyEvent.VK_T,editMenu,KeyEvent.VK_X,this);
copyItem=createMenuItem(editCopy,KeyEvent.VK_C,editMenu,KeyEvent.VK_C,this);
createMenuItem(editPaste,KeyEvent.VK_P,editMenu,KeyEvent.VK_V,this);
deleteItem=createMenuItem(editDelete,KeyEvent.VK_L,editMenu,this);
deleteItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0));
editMenu.addSeparator();
findItem=createMenuItem(editFind,KeyEvent.VK_F,editMenu,KeyEvent.VK_F,this);
findNextItem=createMenuItem(editFindNext,KeyEvent.VK_N,editMenu,this);
findNextItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3,0));
replaceItem=createMenuItem(editReplace,KeyEvent.VK_R,editMenu,KeyEvent.VK_H,this);
gotoItem=createMenuItem(editGoTo,KeyEvent.VK_G,editMenu,KeyEvent.VK_G,this);
editMenu.addSeparator();
selectAllItem=createMenuItem(editSelectAll,KeyEvent.VK_A,editMenu,KeyEvent.VK_A,this);
createMenuItem(editTimeDate,KeyEvent.VK_D,editMenu,this)
.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5,0));

createCheckBoxMenuItem(formatWordWrap,KeyEvent.VK_W,formatMenu,this);

createMenuItem(formatFont,KeyEvent.VK_F,formatMenu,this);
formatMenu.addSeparator();
createMenuItem(formatForeground,KeyEvent.VK_T,formatMenu,this);
createMenuItem(formatBackground,KeyEvent.VK_P,formatMenu,this);

createCheckBoxMenuItem(viewStatusBar,KeyEvent.VK_S,viewMenu,this).setSelected(true);
/************For Look and Feel***/
LookAndFeelMenu.createLookAndFeelMenuItem(viewMenu,this.f);

temp=createMenuItem(helpHelpTopic,KeyEvent.VK_H,helpMenu,this);
temp.setEnabled(false);
helpMenu.addSeparator();
createMenuItem(helpAboutNotepad,KeyEvent.VK_A,helpMenu,this);

MenuListener editMenuListener=new MenuListener()


{
public void menuSelected(MenuEvent evvvv)
{
if(Notepad.this.ta.getText().length()==0)
{
findItem.setEnabled(false);
findNextItem.setEnabled(false);
replaceItem.setEnabled(false);
selectAllItem.setEnabled(false);
gotoItem.setEnabled(false);
}
else
{
findItem.setEnabled(true);
findNextItem.setEnabled(true);

ESEC/CSE/III SEMESTER B.E. CSE 42


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

replaceItem.setEnabled(true);
selectAllItem.setEnabled(true);
gotoItem.setEnabled(true);
}
if(Notepad.this.ta.getSelectionStart()==ta.getSelectionEnd())
{
cutItem.setEnabled(false);
copyItem.setEnabled(false);
deleteItem.setEnabled(false);
}
else
{
cutItem.setEnabled(true);
copyItem.setEnabled(true);
deleteItem.setEnabled(true);
}
}
public void menuDeselected(MenuEvent evvvv){}
public void menuCanceled(MenuEvent evvvv){}
};
editMenu.addMenuListener(editMenuListener);
f.setJMenuBar(mb);
}
/*************Constructor**************/
////////////////////////////////////
public static void main(String[] s)
{
new Notepad();
}
}
/**************************************/
//public
interface MenuConstants
{
final String fileText="File";
final String editText="Edit";
final String formatText="Format";
final String viewText="View";
final String helpText="Help";

final String fileNew="New";


final String fileOpen="Open...";
final String fileSave="Save";
final String fileSaveAs="Save As...";
final String filePageSetup="Page Setup...";
final String filePrint="Print";
final String fileExit="Exit";

final String editUndo="Undo";


final String editCut="Cut";
final String editCopy="Copy";
final String editPaste="Paste";
final String editDelete="Delete";
final String editFind="Find...";
final String editFindNext="Find Next";
final String editReplace="Replace";
final String editGoTo="Go To...";
final String editSelectAll="Select All";
final String editTimeDate="Time/Date";

final String formatWordWrap="Word Wrap";


final String formatFont="Font...";
final String formatForeground="Set Text color...";
final String formatBackground="Set Pad color...";

final String viewStatusBar="Status Bar";

ESEC/CSE/III SEMESTER B.E. CSE 43


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

final String helpHelpTopic="Help Topic";


final String helpAboutNotepad="About Javapad";

final String aboutText="Your Javapad";


}

OUTPUT

Content Beyond the Syllabus (JDBC)

13.Develop a simple OPAC system for library using even-driven and concurrent programming paradigms of Java. Use JDBC to connect to a back-end database.
Program
import java.sql.*;

ESEC/CSE/III SEMESTER B.E. CSE 44


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class Library implements ActionListener
{
JRadioButton rbauthor = new JRadioButton("Search by Author Name");
JRadioButton rbbook = new JRadioButton("Search by Book Name");
JTextField textfld = new JTextField(30);
JLabel label = new JLabel("Enter Search Key");
JButton searchbutton = new JButton("Search");
JFrame frame = new JFrame();
JTable table;
DefaultTableModel model;
String query = "select * from library";

public Library()
{
frame.setTitle("Online Public Access Catalog(OPAC)");
frame.setSize(500,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());

JPanel p1 = new JPanel();


JPanel p2 = new JPanel();
JPanel p3 = new JPanel();

p1.setLayout(new FlowLayout());
p1.add(label);
p1.add(textfld);

ButtonGroup bg = new ButtonGroup();


bg.add(rbauthor);
bg.add(rbbook);

p2.setLayout(new FlowLayout());
p2.add(rbauthor);
p2.add(rbbook);
p2.add(searchbutton);
searchbutton.addActionListener(this);

p3.setLayout(new BorderLayout());
p3.add(p1,BorderLayout.NORTH);
p3.add(p2,BorderLayout.CENTER);

frame.add(p3,BorderLayout.NORTH);
addTable(query);
frame.setVisible(true);
}
public void addTable(String s)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn =
DriverManager.getConnection("jdbc:odbc:Library","","");
Statement st = conn.createStatement();

ResultSet rs = st.executeQuery(s);
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
model = new DefaultTableModel(1,cols);
table = new JTable(model);
String[] tabledata = new String[cols];
int i=0;
while(i<cols)
{

ESEC/CSE/III SEMESTER B.E. CSE 45


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

tabledata[i] = md.getColumnName(i+1);
i++;
}
model.addRow(tabledata);
while(rs.next())
{
for(i=0;i<cols;i++)
tabledata[i] = rs.getObject(i+1).toString();
model.addRow(tabledata);
}
frame.add(table,BorderLayout.CENTER);

conn.close();
}catch(Exception e){}

}
public void actionPerformed(ActionEvent evt)
{
if(rbauthor.isSelected())
query = "select * from library where AuthorName like
'"+textfld.getText()+"%'";
if(rbbook.isSelected())
query = "select * from library where BookName like
'"+textfld.getText()+"%'";
while(model.getRowCount()>0)
model.removeRow(0);
frame.remove(table);
addTable(query);
}
public static void main(String[] args)
{
new Library();
}

OUTPUT

ESEC/CSE/III SEMESTER B.E. CSE 46


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

ESEC/CSE/III SEMESTER B.E. CSE 47


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

ESEC/CSE/III SEMESTER B.E. CSE 48


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

VIVA QUESTIONS
Java & Object Oriented Programming – Fundamentals
1. What is Abstraction?
2. What is Encapsulation?
3. What is the difference between abstraction and encapsulation?
4. What is Java?
5. What are the main features of java?
6. What is the Java Virtual Machine (JVM)?
7. What are the principle concepts of OOPS?
8. What are different types of access modifiers?
9. What is Byte Code?
10. Are JVM's platform independent?
11. How to define a constant variable in Java?
12. Why is the main method declared static?
13. What if the static modifier is removed from the signature of the main() method?
14. What if the main() method is declared as private?
15. What is the difference between a constructor and a method?
16. What is the purpose of garbage collection in Java, and when is it used?
17. What is an abstract class?
18. What is static in java?
19. What is final class?
20. What is the first argument of the String array in main() method?
21. Can an application have multiple classes having main() method?
22. What are wrapper classes?
23. What is the purpose of finalization?
24. How are this() and super() used with constructors?
25. What is the default value of the local variables?
26. How is final different from finally and finalize()?
27. What are the restriction imposed on a static method or a static block of code?
28. What modifiers can be used with a local inner class?
29. Which methods are used to destroy the objects created by the constructor methods?
30. Can an abstract class may be final?
31. Can there be an abstract class with no abstract methods in it?
32. What is static block?
33. What is Unicode?
34. Can you give few examples of final classes defined in Java API?
35. What are Inner Classes?

Inheritance
1. What is the base class of all classes?
2. Does Java support multiple inheritance?
3. What is Overriding?
4. What is Dynamic Binding?
5. How to invoke a superclass version of an Overridden method?
6. How do you prevent a method from being overridden?
7. What is the difference between method overriding and overloading?
8. What do you mean by polymorphism?
9. I don't want my class to be inherited by any other class. What should i do?
10. What is inheritance?
11. Which keyword is used to inherit a class?
12. When can subclasses not access superclass members?
13. Which method is used to call the constructors of the superclass from the subclass?
14. Can a class extnds more than one Class?

ESEC/CSE/III SEMESTER B.E. CSE 49


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

Event Handling
1. Difference between Swing and Awt?
2. What is an Applets?
3. What is the highest-level event class of the event-delegation model?
4. What class is the top of the AWT event hierarchy?
5. What event results from the clicking of a button?
6. In which package are most of the AWT events that support the event-delegation model defined?
7. What is the difference between a TextArea and a TextField?
8. What is the immediate super class of Applet class?
9. Which layout is used as their default layout by Window, Frame and Dialog classes?
10. Which event is generated when the position of a scrollbar is changed.
11. What is the difference between choice and list?
12. What is the difference between scrollbar and scrollpane?
13. Which containers use a Flow layout as their default layout?

Exception Handling
1. What are runtime exceptions?
2. What is the difference between error and an exception?
3. Is it necessary that each try block must be followed by a catch block?
4. What are the difference between throw and throws?
5. Does constructors throw exceptions?
6. What is difference between Checked Exception and Unchecked Exception?
7. What is the base class for Error and Exception?
8. What is finally block?
9. Can finally block be used without catch?
10. Can an exception be rethrown?
Threads
1. What is the difference between process and thread?
2. What are the benefits of multi-threaded programming?
3. How can we create a Thread in Java?
4. What are different states in lifecycle of Thread?
5. What is synchronization and why is it important?
6. What method must be implemented by all threads?
7. What invokes a thread's run() method?
8. What is the purpose of the wait(), notify(), and notifyAll() methods?
9. What’s the difference between the methods sleep() and wait()?
10. What is daemon thread and which method is used to create the daemon thread?
11. How can we pause the execution of a Thread for specific time?
12. What do you understand about Thread Priority?
13. What is the difference between yielding and sleeping?
14. What does join() method?
15. What is deadlock?

Packages & Interfaces


1. What is a package?
2. What is the difference between an Interface and an Abstract class?
3. What modifiers are allowed for methods in an Interface?
4. Which package is imported by default?
5. What are packages ? what is use of packages ?
6. What is interface? What is use of interface?
7. Is it is necessary to implement all methods in an interface?
8. Which is the default access modifier for an interface method?
9. Can you define a variable inside an Interface
10. How do you achieve multiple inheritance in Java?

ESEC/CSE/III SEMESTER B.E. CSE 50


CS8383 OBJECT ORIENTED PROGRAMMING LAB LAB MANUAL

11. Is it possible to use few methods of an interface in a class ?


12. Name interfaces without a method?
13. Can we instantiate an interface?

I/O Handling
1. What is serialization?
2. How do I serialize an object to a file?
3. What happens to the static fields of a class during serialization?
4. What is meant by Stream and what are the types of Streams and classes of the Streams?
5. How do I check for end-of-file when reading from a stream?
6. What class allows you to read objects directly from a stream?
7. What is the purpose of the System class?
8. What is the use of ByteArray Streams?
9. What is the use of PipedStreams?
10. Which is the super class for all the Input Stream classes?
11. Which is the super class for all the Output Stream classes?
12. What is the use of readLine() method?
13. How will you obtain size of the file?
14. What is the advantages of using Pushback streams?
15. Differentiate Character stream and Byte streams.

ESEC/CSE/III SEMESTER B.E. CSE 51

You might also like