You are on page 1of 68

TAGORE ENGINEERING COLLEGE

Rathinamangalam, Chennai-127.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CS8383 OBJECT ORIENTED PROGRAMMING LABORATORY

Name :

Reg.No :

Branch :

Year :

Semester :

Anna University:: Chennai


BATCH:2017-2021
CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

INDEX

Page
Ex.NO Name of the Experiment Signature
No.

1 Electricity Bill Generation

Currency converter , Distance converter and Time


2
converter

3 Payroll Processing

4 ADT Stack

5 String Operations

6 Abstract Class

7 Exception Handling

8 File Information

9 Multithreading

10 Generic Function

11 Calculator

12 Mini Project – Database for Student Details


Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Ex.No :
ELECTRICITY BILL GENERATION
Date:

Aim:

To develop a Java application to generate Electricity bill.

Procedure:

1. Start the program

2. Create consumer class with the following members: Consumer no.,


consumer name, previous month reading, current month reading, type of EB
connection (i.e domestic or commercial).

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

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

1
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Coding:

import java.util.Scanner;
class ElectBill
{
int ConsumerNo;
String ConsumerName;
int PrevReading;
int CurrReading;
String EBConn;
double Bill;
void input_data()
{
Scanner sc = new Scanner(System.in);
System.out.println("\n Enter Consumer Number:");
ConsumerNo=sc.nextInt();
System.out.println("\n Enter Consumer Name:");
ConsumerName=sc.next();
System.out.println("\n Enter Previous Units:");
PrevReading=sc.nextInt();
System.out.println("\n Enter Current Units consumed:");
CurrReading= sc.nextInt();
System.out.println("Enter the types of EB Connection (Domestic or
Commercial)");
EBConn=sc.next();
}
double calculate_bill()
{
int choice;
if(EBConn=="domestic")
choice=1;
else
choice=2;
switch(choice)
{
case 1:
if(CurrReading>=0 && CurrReading<=100)
Bill=CurrReading*1;
else if(CurrReading>100 && CurrReading <=200)
Bill=(100*1)+((CurrReading -100)*2.50);
else if(CurrReading>200 && CurrReading <=500)
Bill=(100*1)+(100*2.50)+((CurrReading -200)*4);
else
Bill=(100*1)+(100*2.50)+(300*4)+((CurrReading-500)*6);
break;
2
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

case 2:
if(CurrReading>=0 && CurrReading<=100)
Bill=CurrReading*2;
else if(CurrReading>100 && CurrReading <=200)
Bill=(100*1)+((CurrReading -100)*4.50);
else if(CurrReading>200 && CurrReading <=500)
Bill=(100*1)+(100*2.50)+((CurrReading -200)*6);
else
Bill=(100*1)+(100*2.50)+(300*4)+((CurrReading-500)*7);
break;
}
return Bill;
}
void display()
{
System.out.println("-------------------------------");
System.out.println("ELECTRICITY BILL");
System.out.println("--------------------------------");
System.out.println("Consumer Number:"+ConsumerNo);
System.out.println("Consumer Name:"+ConsumerName);
System.out.println("Consumer Previous Units:"+PrevReading);
System.out.println("Consumer Current Units:"+CurrReading);
System.out.println("Type of EB Connection:"+EBConn);
System.out.println("--------------------------------");
System.out.println("Total Amount(Rs.):"+Bill);
}
}
class ElectBillGen
{
public static void main(String[] args)
{
ElectBill b= new ElectBill();
b.input_data();
b.calculate_bill();
b.display();
}
}

3
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Output:

D:\Java\jdk1.8.0_102\bin>java ElectBillGen

Enter Consumer Number:


101

Enter Consumer Name:


TEC

Enter Previous Units:


100

Enter Current Units consumed:


300
Enter the types of EB Connection (Domestic or Commercial)
2
-------------------------------
ELECTRICITY BILL
--------------------------------
Consumer Number:101
Consumer Name:TEC
Consumer Previous Units:100
Consumer Current Units:300
Type of EB Connection:2
--------------------------------
Total Amount (Rs.):950.0

Result:

Thus Java application to generate Electricity bill was developed and


executed successfully.

4
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Ex.No : 2 Currency Converter, Distance Converter and Time


Date: Converter

Aim:

To develop a Java application to implement currency converter, distance


converter and time converter using packages.

Procedure:

1. Start the program

2. Create three packages for currency converter, distance converter and time
converter.

3. Create corresponding code for conversion

4. Print the converted value.

5. Stop the program

5
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Coding:

package ConversionDemo;
public class CurrencyConverter
{
double ER=0;
public CurrencyConverter(double CurrentExchange)
{
ER=CurrentExchange;
}
public double DollarToINR(double Dollars)
{
double INR=0;
INR=Dollars*ER;
return INR;
}
public double INRToDollar(double INR)
{
double Dollars=0;
Dollars=INR/ER;
return Dollars;
}
public double EuroToINR(double Euros)
{
double INR=0;
INR=Euros*ER;
return INR;
}
public double INRToEuro(double INR)
{
double Euros=0;
Euros=INR/ER;
return Euros;
}
public double YenToINR(double Yens)
{
double INR=0;
INR=Yens*ER;
return INR;
}
public double INRToYen(double INR)
{
double Yens=0;
Yens=INR/ER;
return Yens;
6
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

}
}

DistanceConverter.java

package ConversionDemo;
public class DistanceConverter
{
public double MeterToKM(double Meters)
{
double KM=0;
KM=Meters/1000;
return KM;
}
public double KMToMeter(double KM)
{
double Meters=0;
Meters=KM*1000;
return Meters;
}
public double MileToKM(double Miles)
{
double KM=0;
KM=Miles/0.621371;
return KM;
}
public double KMToMile(double KM)
{
double Miles=0;
Miles=KM*0.621371;
return Miles;
}
}

TimeConverter.java

package ConversionDemo;
public class TimeConverter
{
public double HrToMin(double Hours)
{
double Minutes=0;
Minutes=Hours*60;
return Minutes;
}
7
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

public double MinToHr(double Minutes)


{
double Hours=0;
Hours=Minutes/60;
return Hours;
}
public double HrToSec(double Hours)
{
double Seconds=0;
Seconds=Hours*3600;
return Seconds;
}
public double SecToHr(double Seconds)
{
double Hours=0;
Hours=Seconds/3600;
return Hours;
}
}

Main Program
import ConversionDemo.CurrencyConverter;
import ConversionDemo.DistanceConverter;
import ConversionDemo.TimeConverter;
import java.util.Scanner;
class Converter
{
public static void main(String[] args) throws NoClassDefFoundError
{
double CurrentExchange;
int choice,choice1,choice2,choice3;
double inr;
double km;
double hr;
char ans='y';
do
{
System.out.println("\nMain Menu");
System.out.println("1. Currency Converter \n2. Distance Converter \n3. Time
Converter");
System.out.println("Enter your choice:");
Scanner input = new Scanner(System.in);
choice=input.nextInt();
switch(choice)
{
8
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

case 1:
System.out.println("\tCurrency Conversion");
do
{
System.out.println("Menu For Currency Conversion");
System.out.println("1. Dollar to INR");
System.out.println("2. INR to Dollar");
System.out.println("3. Euro to INR");
System.out.println("4. INR to Euro");
System.out.println("5. Yen to INR");
System.out.println("6. INR to Yen");
System.out.println("Enter your choice:");
choice1=input.nextInt();
System.out.println("Please enter the current exchange rate:");
CurrentExchange=input.nextDouble();
CurrencyConverter cc=new CurrencyConverter(CurrentExchange);
switch(choice1)
{
case 1:
System.out.println("Enter Dollars:");
double dollar=input.nextDouble();
System.out.println(dollar+"Dollars are converted
to"+cc.DollarToINR(dollar)+"Rs.");
break;
case 2:
System.out.println("Enter INR:");
inr=input.nextDouble();
System.out.println(inr+"Rs. are converted to"+cc.INRToDollar(inr)+"Dollars");
break;
case 3:
System.out.println("Enter Euro:");
double euro=input.nextDouble();
System.out.println(euro+"Euros are converted to"+cc.EuroToINR(euro)+"Rs.");
break;
case 4:
System.out.println("Enter INR:");
inr=input.nextDouble();
System.out.println(inr+"Rs. are converted to"+cc.INRToEuro(inr)+"Euros");
break;
case 5:
System.out.println("Enter Yens:");
double yen=input.nextDouble();
System.out.println(yen+"Yens are converted to"+cc.YenToINR(yen)+"Rs.");
break;
case 6:
9
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

System.out.println("Enter INR:");
inr=input.nextDouble();
System.out.println(inr+"Rs. are converted to"+cc.INRToYen(inr)+"Yens");
break;
}
System.out.println("Do you want to go to Currency Conversion Menu?(y/n)");
ans = input.next().charAt(0);
}while(ans=='y');
break;
case 2:
System.out.println("\t Distance Conversion");
do
{
System.out.println("Menu For Distance Conversion");
System.out.println("1. Meter to KM");
System.out.println("2. KM to Meter");
System.out.println("3. Miles to KM");
System.out.println("4. KM to Miles");
System.out.println("Enter your choice:");
choice2=input.nextInt();
DistanceConverter dc=new DistanceConverter();
switch(choice2)
{
case 1:
System.out.println("Enter meters to convert to km:");
double meter=input.nextDouble();
System.out.println(meter+"Meters are converted
to"+dc.MeterToKM(meter)+"Km");
break;
case 2:
System.out.println("Enter km to convert to meter:");
km=input.nextDouble();
System.out.println(km+"Km are converted to"+dc.KMToMeter(km)+"Meters");
break;
case 3:
System.out.println("Enter miles to convert to km:");
double miles=input.nextDouble();
System.out.println(miles+"Miles are converted to"+dc.MileToKM(miles)+"Km");
break;
case 4:
System.out.println("Enter km to convert to Miles:");
km=input.nextDouble();
System.out.println(km+"Km are converted to"+dc.KMToMile(km)+"Miles");
break;
}
10
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

System.out.println("Do you want to go to Distance Conversion Menu?(y/n)");


ans = input.next().charAt(0);
}while(ans=='y');
break;
case 3:
System.out.println("\t Time Conversion");
do
{
System.out.println("Menu For Time Conversion");
System.out.println("1. Hour to Minutes");
System.out.println("2. Minutes to Hour");
System.out.println("3. Hour to Seconds");
System.out.println("4. Seconds to Hour");
System.out.println("Enter your choice:");
choice3=input.nextInt();
TimeConverter tc=new TimeConverter();
switch(choice3)
{
case 1:
System.out.println("Enter hours to convert to minutes:");
hr=input.nextDouble();
System.out.println(hr+"Hours are converted to"+tc.HrToMin(hr)+"min");
break;
case 2:
System.out.println("Enter minutes to convert to hours:");
double minutes=input.nextDouble();
System.out.println(minutes+"minutes are converted
to"+tc.MinToHr(minutes)+"Hours");
break;
case 3:
System.out.println("Enter hours to convert to seconds:");
hr=input.nextDouble();
System.out.println(hr+"Hours are converted to"+tc.HrToSec(hr)+"seconds");
break;
case 4:
System.out.println("Enter seconds to convert to hours:");
double seconds=input.nextDouble();
System.out.println(seconds+"Seconds are converted
to"+tc.SecToHr(seconds)+"Hours");
break;
}
System.out.println("Do you want to go to Time Conversion Menu?(y/n)");
ans = input.next().charAt(0);
}while(ans=='y');
break;
11
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

}
System.out.println("Do you want to go back to Main Menu?(y/n)");
ans=input.next().charAt(0);
}while(ans=='y');
}
}

12
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Output:

D:\Java\jdk1.8.0_102\bin>javac Converter.java

D:\Java\jdk1.8.0_102\bin>java Converter

Main Menu
1. Currency Converter
2. Distance Converter
3. Time Converter
Enter your choice:
1
Currency Conversion
Menu For Currency Conversion
1. Dollar to INR
2. INR to Dollar
3. Euro to INR
4. INR to Euro
5. Yen to INR
6. INR to Yen
Enter your choice:
1
Please enter the current exchange rate:
12
Enter Dollars:
12
12.0Dollars are converted to144.0Rs.
Do you want to go to Currency Conversion Menu?(y/n)
2
Do you want to go back to Main Menu?(y/n)
y

Main Menu
1. Currency Converter
2. Distance Converter
3. Time Converter
Enter your choice:
2
Distance Conversion
Menu For Distance Conversion
1. Meter to KM
2. KM to Meter
3. Miles to KM
4. KM to Miles
Enter your choice:
13
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

2
Enter km to convert to meter:
23
23.0Km are converted to23000.0Meters
Do you want to go to Distance Conversion Menu?(y/n)
n
Do you want to go back to Main Menu?(y/n)
y

Main Menu
1. Currency Converter
2. Distance Converter
3. Time Converter
Enter your choice:
3
Time Conversion
Menu For Time Conversion
1. Hour to Minutes
2. Minutes to Hour
3. Hour to Seconds
4. Seconds to Hour
Enter your choice:
3
Enter hours to convert to seconds:
23
23.0Hours are converted to82800.0seconds
Do you want to go to Time Conversion Menu?(y/n)
n
Do you want to go back to Main Menu?(y/n)
n
D:\Java\jdk1.8.0_102\bin>

Result:

Thus Java application to implement currency converter, distance


converter and time converter using packages was developed and executed
successfully.

14
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Ex.No : 3
PAYROLL PROCESSING
Date:

Aim:

To develop a Java application with employee class and generate pay slips
for the employees with their gross and net salary.

Procedure:

1. Start the program

2. Create Employee class with Emp_name, Emp_id, Address, Mail_id, Mobile_no


as
members.

3.Inherit the classes, Programmer, Assistant Professor, Associate Professor and


Professor
from employee class.

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

5. Generate pay slips for the employees with their gross and net salary.

6. Stop the program

15
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Coding:

import java.util.Scanner;
class Employee
{
int Emp_id;
String Emp_name;
String Address;
String Mail_Id;
String Mobile_No;
Employee() {}
Employee(int id,String name,String addr,String mail,String mob)
{
this.Emp_id=id;
this.Emp_name=name;
this.Address=addr;
this.Mail_Id=mail;
this.Mobile_No=mob;
}
}
class Programmer extends Employee
{
double BP,Gross_salary,Net_salary;
public Programmer(int id,String name,String addr,String mail,String mob)
{
super(id,name,addr,mail,mob);
}
void computePay()
{
System.out.println("Enter Basic Pay:");
Scanner input=new Scanner(System.in);
BP=input.nextDouble();
double DA,HRA,PF,Fund;
DA=(BP*97/100);
HRA=(BP*10/100);
PF=(BP*12/100);
Fund=(BP*0.1/100);
Gross_salary=BP+DA+HRA;
Net_salary=BP+DA+HRA-(PF+Fund);
System.out.println("Emp_Id:"+Emp_id);
System.out.println("Emp_Name:"+Emp_name);
System.out.println("Address:"+Address);
System.out.println("Mail_Id:"+Mail_Id);
System.out.println("Mobile Number:"+Mobile_No);
System.out.println("Gross Pay:"+Gross_salary);
16
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

System.out.println("Net Pay:"+Net_salary);
}
}

class Asst_Professor extends Employee


{
double BP,Gross_salary,Net_salary;
public Asst_Professor(int id,String name,String addr,String mail,String mob)
{
super(id,name,addr,mail,mob);
}
void computePay()
{
System.out.println("Enter Basic Pay:");
Scanner input=new Scanner(System.in);
BP=input.nextDouble();
double DA,HRA,PF,Fund;
DA=(BP*97/100);
HRA=(BP*10/100);
PF=(BP*12/100);
Fund=(BP*0.1/100);
Gross_salary=BP+DA+HRA;
Net_salary=BP+DA+HRA-(PF+Fund);
System.out.println("Emp_Id:"+Emp_id);
System.out.println("Emp_Name:"+Emp_name);
System.out.println("Address:"+Address);
System.out.println("Mail_Id:"+Mail_Id);
System.out.println("Mobile Number:"+Mobile_No);
System.out.println("Gross Pay:"+Gross_salary);
System.out.println("Net Pay:"+Net_salary);
}
}
class Associate_Professor extends Employee
{
double BP,Gross_salary,Net_salary;
public Associate_Professor(int id,String name,String addr,String mail,String
mob)
{
super(id,name,addr,mail,mob);
}
void computePay()
{
System.out.println("Enter Basic Pay:");
Scanner input=new Scanner(System.in);
BP=input.nextDouble();
17
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

double DA,HRA,PF,Fund;
DA=(BP*97/100);
HRA=(BP*10/100);
PF=(BP*12/100);
Fund=(BP*0.1/100);
Gross_salary=BP+DA+HRA;
Net_salary=BP+DA+HRA-(PF+Fund);
System.out.println("Emp_Id:"+Emp_id);
System.out.println("Emp_Name:"+Emp_name);
System.out.println("Address:"+Address);
System.out.println("Mail_Id:"+Mail_Id);
System.out.println("Mobile Number:"+Mobile_No);
System.out.println("Gross Pay:"+Gross_salary);
System.out.println("Net Pay:"+Net_salary);
}
}
class Professor extends Employee
{
double BP,Gross_salary,Net_salary;
public Professor(int id,String name,String addr,String mail,String mob)
{
super(id,name,addr,mail,mob);
}
void computePay()
{
System.out.println("Enter Basic Pay:");
Scanner input=new Scanner(System.in);
BP=input.nextDouble();
double DA,HRA,PF,Fund;
DA=(BP*97/100);
HRA=(BP*10/100);
PF=(BP*12/100);
Fund=(BP*0.1/100);
Gross_salary=BP+DA+HRA;
Net_salary=BP+DA+HRA-(PF+Fund);
System.out.println("Emp_Id:"+Emp_id);
System.out.println("Emp_Name:"+Emp_name);
System.out.println("Address:"+Address);
System.out.println("Mail_Id:"+Mail_Id);
System.out.println("Mobile Number:"+Mobile_No);
System.out.println("Gross Pay:"+Gross_salary);
System.out.println("Net Pay:"+Net_salary);
}
}
public class PaySlip
18
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

{
public static void main(String[] args)
{
Programmer p=new
Programmer(10,"AAA","xxx","aaa_xxx@gmail.com","22121221");
System.out.println("-------Programmer---------");
p.computePay();
Asst_Professor Ap=new
Asst_Professor(20,"BBB","yyy","bbb_yyy@gmail.com","21322442213");
System.out.println("-------Assistant Professor---------");
Ap.computePay();
Associate_Professor As=new
Associate_Professor(30,"ccc","zzz","ccc_zzz@gmail.com","213224427913");
System.out.println("-------Associate Professor---------");
As.computePay();
Professor pf=new
Professor(40,"DDD","abc","ddd_abc@gmail.com","213312442213");
System.out.println("-------Professor---------");
pf.computePay();
}
}

19
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Output:

D:\software\Java\jdk1.7.0_25\bin>java PaySlip
-------Programmer---------
Enter Basic Pay:
5000
Emp_Id:10
Emp_Name:AAA
Address:xxx
Mail_Id:aaa_xxx@gmail.com
Mobile Number:22121221
Gross Pay:10350.0
Net Pay:9745.0
-------Assistant Professor---------
Enter Basic Pay:
10000
Emp_Id:20
Emp_Name:BBB
Address:yyy
Mail_Id:bbb_yyy@gmail.com
Mobile Number:21322442213
Gross Pay:20700.0
Net Pay:19490.0
-------Associate Professor---------
Enter Basic Pay:
29999
Emp_Id:30
Emp_Name:ccc
Address:zzz
Mail_Id:ccc_zzz@gmail.com
Mobile Number:213224427913
Gross Pay:62097.93
Net Pay:58468.051
-------Professor---------
Enter Basic Pay:

423142
Emp_Id:40
Emp_Name:DDD
Address:abc
Mail_Id:ddd_abc@gmail.com
Mobile Number:213312442213
Gross Pay:875903.94
20
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Net Pay:824703.7579999999

D:\software\Java\jdk1.7.0_25\bin>

Result:

Thus Java application with employee class and generate pay slips for the
employees with their gross and net salary was developed and executed
successfully.

21
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Ex.No : 4
ADT STACK
Date:

Aim

To design a Java interface for ADT Stack using array.

Procedure:

1. Start the program

2. Define the interface.

3. Read the elements using array.

4. Initialize stackTop pointer as zero,

5. Define and use the method Push() to insert the elements into the stack with
‘STACK
OVERFLOW’ condition.

6. Define and use the method pop() to remove an element from an array with
‘STACK
UNDERFLOW’ condition

7. Display the output.

22
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Coding:

import java.io.*;
interface stackoperation
{
public void push(int i);
public void pop();
}
class Astack implements stackoperation
{
int stack[];
int top;
Astack()
{
stack=new int[10];
top=0;
}
public void push(int item)
{
if(stack[top]==10)
System.out.println("Overflow");
else
{
stack[++top]=item;
System.out.println("Item pushed");
}
}
public void pop()
{
if(stack[top]<=0)
System.out.println("Underflow");
else
{
stack[top]=top--;
System.out.println("Item popped");
}
}
public void display()
{
for(int i=1;i<=top;i++)
System.out.println("Element:" +stack[i]);
}
}
class liststack implements stackoperation
{
23
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

node top,q;
int count;
public void push(int i)
{
node n = new node(i);
n.link=top;
top=n;
count++;
}
public void pop()
{
if(top==null)
System.out.println("Underflow");
else
{
int p=top.data;
top=top.link;
count--;
System.out.println("popped element: "+p);
}
}
void display()
{
for(q=top;q!=null;q=q.link)
{
System.out.println("The elements are: "+q.data);
}
}
class node
{
int data;
node link;
node(int i)
{
data=i;
link=null;
}
}
}
class sample
{
public static void main(String args[]) throws IOException
{
int ch,x=1,p=0,t=0;
DataInputStream in= new DataInputStream(System.in);
24
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

do
{
try
{
System.out.println("-------------------------------");
System.out.println("1.Arraystack 2.ListStack 3.Exit");
System.out.println("-------------------------------");
System.out.println("Enter ur choice:");
int c=Integer.parseInt(in.readLine());
Astack s = new Astack();
switch(c)
{
case 1:
do
{
if(p==1)
break;
System.out.println("ARRAY STACK");
System.out.println("1.Push 2.Pop 3.Display 4.Exit");
System.out.println("Enter ur choice:");
ch=Integer.parseInt(in.readLine());
switch(ch)
{
case 1:
System.out.println("Enter the value to push:");
int i=Integer.parseInt(in.readLine());
s.push(i);
break;
case 2:
s.pop();
break;
case 3:
System.out.println("The Elements are:");
s.display();
break;
case 4:
p=1;
continue;
}
}while(x!=0);
break;
case 2:
liststack l=new liststack();
do
{
25
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

if(t==1)
break;
System.out.println("LIST STACK");
System.out.println("1.Push 2.Pop 3.Display 4.Exit");
System.out.println("Enter your choice:");
ch=Integer.parseInt(in.readLine());
switch(ch)
{
case 1:
System.out.println("Enter the value for push:");
int a=Integer.parseInt(in.readLine());
l.push(a);
break;
case 2:
l.pop();
case 3:
l.display();
break;
case 4:
t=1;
continue;
}
}
while(x!=0);
break;
case 3:
System.exit(0);
}
}
catch(IOException e)
{
System.out.println("IO Error");
}
}
while(x!=0);
}
}

26
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Output:

D:\Java\jdk1.8.0_102\bin>java sample
-------------------------------
1.Arraystack 2.ListStack 3.Exit
-------------------------------
Enter ur choice:
1
ARRAY STACK
1.Push 2.Pop 3.Display 4.Exit
Enter ur choice:
1
Enter the value to push:
1
Item pushed
ARRAY STACK
1.Push 2.Pop 3.Display 4.Exit
Enter ur choice:
1
Enter the value to push:
2
Item pushed
ARRAY STACK
1.Push 2.Pop 3.Display 4.Exit
Enter ur choice:
1
Enter the value to push:
3
Item pushed
ARRAY STACK
1.Push 2.Pop 3.Display 4.Exit
Enter ur choice:
3
The Elements are:
Element:1
Element:2
Element:3
ARRAY STACK
1.Push 2.Pop 3.Display 4.Exit
Enter ur choice:
2
Item popped
ARRAY STACK
1.Push 2.Pop 3.Display 4.Exit
Enter ur choice:
27
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

3
The Elements are:
Element:1
Element:2
ARRAY STACK
1.Push 2.Pop 3.Display 4.Exit
Enter ur choice:
4
-------------------------------
1.Arraystack 2.ListStack 3.Exit
-------------------------------
Enter ur choice:
2
LIST STACK
1.Push 2.Pop 3.Display 4.Exit
Enetr your choice:
1
Enter the value for push:
1
LIST STACK
1.Push 2.Pop 3.Display 4.Exit
Enetr your choice:
1
Enter the value for push:
2
LIST STACK
1.Push 2.Pop 3.Display 4.Exit
Enetr your choice:
1
Enter the value for push:
3
LIST STACK
1.Push 2.Pop 3.Display 4.Exit
Enetr your choice:
3
The elements are: 3
The elements are: 2
The elements are: 1
LIST STACK
1.Push 2.Pop 3.Display 4.Exit
Enetr your choice:
2
popped element: 3
The elements are: 2
The elements are: 1
28
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

LIST STACK
1.Push 2.Pop 3.Display 4.Exit
Enetr your choice:
3
The elements are: 2
The elements are: 1
LIST STACK
1.Push 2.Pop 3.Display 4.Exit
Enetr your choice:
4
-------------------------------
1.Arraystack 2.ListStack 3.Exit
-------------------------------
Enter ur choice:
3

D:\Java\jdk1.8.0_102\bin>

Result:

Thus a Java interface for ADT Stack using array was developed and
executed successfully.

29
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Ex.No : 5
STRING OPERATIONS
Date:

Aim

To write a program to perform string operations using ArrayList.

Procedure:

1. Start the program

2. Add the String as an object to List.

3. Get the choice from the user and do according to the choice

a. Append-add at end

b. Insert-add at particular index

c. Search

d. List all string starts with given letter.

3. Display the result

4. Stop the program.

30
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Coding:

import java.util.ArrayList;
class Test_ArrayList
{
public static void main(String[] args)
{
ArrayList arlTest = new ArrayList();
System.out.println("Size of ArrayList at creation: "+arlTest.size());
arlTest.add("Chennai");
arlTest.add("Kolkata");
System.out.println("List of all elements: "+arlTest);
System.out.println("Size of ArrayList after adding elements: "+arlTest.size());
arlTest.add("Delhi"); /* add at the end */
System.out.println("List of all elements: "+arlTest);
System.out.println("Size of ArrayList after adding elements: "+arlTest.size());
arlTest.add(0,"Mumbai");
arlTest.add(1,"Bangalore");
System.out.println("List of all elements: "+arlTest);
System.out.println("Size of ArrayList after adding elements: "+arlTest.size());
arlTest.remove(1);
System.out.println("List of all elements: "+arlTest);
System.out.println("Size of ArrayList after removing element: "+arlTest.size());
boolean isFound = arlTest.contains("Bangalore");
if(isFound==false)
System.out.println("Element not found");
else
System.out.println("Element found");
boolean isFound1 = arlTest.contains("Chennai");
if(isFound1==false)
System.out.println("Element not found");
else
System.out.println("Element found");

}
}

31
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Output:

Size of ArrayList at creation: 0


List of all elements: [Chennai, Kolkata]
Size of ArrayList after adding elements: 2
List of all elements: [Chennai, Kolkata, Delhi]
Size of ArrayList after adding elements: 3
List of all elements: [Mumbai, Bangalore, Chennai, Kolkata, Delhi]
Size of ArrayList after adding elements: 5
List of all elements: [Mumbai, Chennai, Kolkata, Delhi]
Size of ArrayList after removing element: 4
Element not found
Element found

Result:

Thus a program to perform string operations using ArrayList was


developed and executed successfully.

32
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Ex.No : 6
ABSTRACT CLASSES
Date:

Aim

To write a Java Program to create an abstract class named Shape and


provide three classes named Rectangle, Triangle and Circle such that each one
of the classes extends the class Shape.

Procedure:

1. Start the program

2. Define the abstract class shape.

3. Define the class Rectangle with PrintArea() method that extends(makes use
of) Shape.

4. Define the class Triangle with PrintArea() method that extends(makes use
of) Shape.

5. Define the class Circle with PrintArea() method that extends(makes use of)
Shape.

6. Print the area of the Rectangle,Triangle and Circle .

7.Stop the Program.

33
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Coding:

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 of rectangle is:"+area_rect);
}
}
class triangle extends shape
{
public int area_tri;

public void print_area()


{
area_tri=(int)(0.5*a*b);
System.out.println("The area of triangle is:"+area_tri);
}
}
class circle extends shape
{
public int area_circle;

public void print_area()


{
area_circle=(int)(3.14*a*a);
System.out.println("The area of circle is:"+area_circle);
}
}
public class JavaApplication
{
public static void main(String[] args)
{
rectangle r = new rectangle();
r.print_area();
triangle t = new triangle();
t.print_area();
34
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

circle r1 = new circle();


r1.print_area();
}
}

Output:

The area of rectangle is: 12


The area of triangle is: 6
The area of circle is: 28

Result:

Thus a Java Program for an abstract class named Shape was created and
three classes named Rectangle, Triangle and Circle such that each one of the
classes extends the class Shape was developed and executed successfully.

35
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Ex.No : 7
EXCEPTION HANDLING
Date:

Aim

To write a Java program to implement user defined exception handling.

Procedure:

1. Start the program

2. Define the exception for getting a number from the user.

3. If the number is positive print the number as such.

4. If the number is negative throw the exception to the user as ‘Number must
be
positive’.

5. Stop the Program.

36
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Coding:

import java.io.*;
class JavaException
{
public static void main(String args[])
{
int n;
System.out.println("Enter n value:");
n=Integer.parseInt(System.console().readLine());
try
{
if (n<0)
{
throw new MyException(n);
}
else
{
System.out.println("The number is = " +n);
}
}
catch(MyException e)
{
System.out.println("In the catch block due to exception = " +e);
System.out.println("End of Main");
}
}
}
class MyException extends Exception
{

MyException (int b)
{
System.out.println("This line will not be executed - The number must be
positive");
}
}

37
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Output

D:\Java\jdk1.8.0_102\bin>javac JavaException.java

D:\Java\jdk1.8.0_102\bin>java JavaException
Enter n value:
24
The number is = 24

D:\Java\jdk1.8.0_102\bin>javac JavaException.java

D:\Java\jdk1.8.0_102\bin>java JavaException
Enter n value:
-4
This line will not be executed - The number must be positive
In the catch block due to exception = MyException
End of Main

D:\Java\jdk1.8.0_102\bin>

Result:

Thus a Java program for user defined exception handling was


implemented successfully.

38
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Ex.No : 8
FILE INFORMATION
Date:

Aim

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

Procedure:

1. Start the program

2. Read the filename from the user.

3. Use getName() Method to display the filename.

4. Use getPath() Method to display the path of the file.

5. Use getParent() Method to display its parent’s information.

6. Use exists() Method to display whether the file exist or not

7. Use isFile() and isDirectory() Methods to display whether the file is file or
directory.

8.Use canRead() and canWrite) methods to display whether the file is readable
or writable.

9. Use lastModified() Method to display the modified information.

10. Use length() method to display the size of the file.

11. Use isHiddden() Method to display whether the file is hidden or not.

39
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Coding:

import java.io.*;
import javax.swing.*;
class FileDemo
{
public static void main(String args[])
{
String filename=JOptionPane.showInputDialog("Enter filename :");
File f = new File(filename);
System.out.println("File exists: "+f.exists());
System.out.println("File is readable: "+f.canRead());
System.out.println("File is writable: "+f.canWrite());
System.out.println("Is a directory: "+f.isDirectory());
System.out.println("Length of the file: "+f.length()+"bytes");
try
{
char ch;
StringBuffer buff=new StringBuffer("");
FileInputStream fis=new FileInputStream(filename);
while(fis.available()!=0)
{
ch=(char)fis.read();
buff.append(ch);
}
System.out.println("\nContents of the file are: ");
System.out.println(buff);
fis.close();
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find the specified file...");
}
catch(IOException i)
{
System.out.println("Cannot read file....");
}
}
}

40
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Output:

File exists:True
File is readable: true
File is writable: true
Is a directory: False
Length of the file: 20 bytes
Contents of the file are:
Hi, Welcome to java

Result:

Thus 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 was implemented
successfully.

41
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Ex.No : 9
MULTITHREADING
Date:

Aim

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

Procedure:

1. Start the program

2. Design the first thread that generates a random integer for every 1 second.

3. If the first thread value is even, design the second thread as the square of
the number and then print it.

4. If the first thread value is odd, then third thread will print the value of cube
of the number.

5. Stop the program.

42
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Coding:

import java.util.*;
class NumberGenerate
{
private int value;
private boolean flag;
public synchronized void put()
{
while(flag)
{
try
{
wait();
}
catch(InterruptedException e)
{}
}
flag=true;
Random random = new Random();
this.value=random.nextInt(10);
System.out.println("The generated number is:"+value);
notifyAll();
}
public synchronized void get1()
{
while(!flag)
{
try
{
wait();
}
catch(InterruptedException e)
{}
}
if(value%2==0)
{
System.out.println("Second is executing now...");
int ans=value*value;
System.out.println(value+"is Even number and its square is:"+ans);
}
flag=false;
notifyAll();
}
public synchronized void get2()
43
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

{
while(!flag)
{
try
{
wait();
}
catch(InterruptedException e)
{}
}
if(value%2!=0)
{
System.out.println("Third is executing now...");
int ans=value*value*value;
System.out.println(value+"is Odd number and its cube is:"+ans);
}
flag=false;
notifyAll();
}
}
public class TestNumber
{
public static void main(String[] args)
{
final NumberGenerate obj = new NumberGenerate();
Thread producerThread = new Thread()
{
public void run()
{
for(int i=1;i<=6;i++)
{
System.out.println("Main thread started.....");
obj.put();
try
{
Thread.sleep(1000);
}
catch(InterruptedException e) { }
}
}
};
Thread consumerThread1= new Thread()
{
public void run()
{
44
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

for(int i=1;i<=3;i++)
{
obj.get1();
try
{
Thread.sleep(2000);
}
catch(InterruptedException e) { }
}
}
};
Thread consumerThread2= new Thread()
{
public void run()
{
for(int i=1;i<=3;i++)
{
obj.get2();
try
{
Thread.sleep(3000);
}
catch(InterruptedException e) { }
}
}
};
producerThread.start();
consumerThread1.start();
consumerThread2.start();
}
}

45
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Output:

D:\Java\jdk1.8.0_102\bin>javac TestNumber.java

D:\Java\jdk1.8.0_102\bin>java TestNumber
Main thread started.....
The generated number is:8
Main thread started.....
The generated number is:2
Second is executing now...
2is Even number and its square is:4
Main thread started.....
The generated number is:5
Main thread started.....
The generated number is:5
Third is executing now...
5is Odd number and its cube is:125
Main thread started.....
The generated number is:0
Main thread started.....
Second is executing now...
0is Even number and its square is:0
The generated number is:7
Third is executing now...
7is Odd number and its cube is:343

D:\Java\jdk1.8.0_102\bin>

Result:

Thus java program that implements a multi-threaded application was


developed and executed successfully.

46
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Ex.No : 10
GENERIC FUNCTION
Date:

Aim

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

Procedure:

1. Start the program

2. Define the array with the elements

3. Sets the first value in the array as the current maximum

4. Find the maximum value by comparing each elements of the array

5. Display the maximum value

6. Stop the program.

47
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Coding:

import java.util.*;
public class Test
{
public static <T extends Object & Comparable<? super T>> T max(Collection<?
extends T>coll)
{
Iterator <? extends T> MyList=coll.iterator();
T element = MyList.next();
while (MyList.hasNext())
{
T next_element=MyList.next();
if(next_element.compareTo(element)>0)
element=next_element;
}
return element;
}
public static void main(String[] args)
{
List<Integer> ints=new ArrayList<Integer>(Arrays.asList(1,55,4,12,24,64,5));
int max=Collections.max(ints);
System.out.println(ints);
System.out.println("Maximum Value is:"+max);
List<Character> chars= new
ArrayList<Character>(Arrays.asList('a','e','i','o','u'));
char maxc=Collections.max(chars);
System.out.println(chars);
System.out.println("Maximum Value is:"+maxc);
}
}

48
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Output:

[1,55,4,12,24,64,5]
Maximum value is:64
[a, e, i, o, u]
Maximum Value is:u

Result:

Thus a java program to find the maximum value from the given type of
elements using a generic function was executed successfully.

49
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Ex.No : 11
CALCULATOR
Date:

Aim

To design a calculator using event-driven programming paradigm of Java


for Decimal manipulations and scientific manipulations.

Procedure:

1. Start the program

2. Using the swing components design the buttons of the calculator

3. Use key events and key listener to listen the events of the calculator.

4. Do the necessary manipulations.

5. Stop the program.

50
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Coding:

import java.awt.*;
import java.awt.event.*;
public class Calcu
{
private TextField display;
private Button
back,clear,b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,bdiv,bmul,bsub,bdot,badd,bequal;
private boolean s;
private double result;
private String last;
public Calcu()
{
display = new TextField(50);
back=new Button("back");
clear=new Button("clear");
b0 = new Button("0");
b1 = new Button("1");
b2 = new Button("2");
b3 = new Button("3");
b4=new Button("4");
b5=new Button("5");
b6=new Button("6");
b7=new Button("7");
b8=new Button("8");
b9=new Button("9");
bdiv=new Button("/");
bmul = new Button("*");
bsub=new Button("-");
bequal=new Button("=");
bdot=new Button(".");
badd=new Button("+");
s=true;
result=0;
last="=";
}
public void launch()
{
Panel down=new Panel();
down.setLayout(new GridLayout(1,1));
down.add(back);
down.add(clear);
Panel centerdown = new Panel();
centerdown.setLayout(new GridLayout(4,5,5,5));
51
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

centerdown.add(b7);
centerdown.add(b8);
centerdown.add(b9);
centerdown.add(bdiv);
centerdown.add(b4);
centerdown.add(b5);
centerdown.add(b6);
centerdown.add(bmul);
centerdown.add(b1);
centerdown.add(b2);
centerdown.add(b3);
centerdown.add(bsub);
centerdown.add(b0);
centerdown.add(bdot);
centerdown.add(bequal);
centerdown.add(badd);
Panel center = new Panel();
center.setLayout(new BorderLayout(10,5));
center.add(centerdown,BorderLayout.CENTER);
Frame frame = new Frame("Calculator---DHIVYAA");
frame.setLayout(new BorderLayout(5,5));
frame.add(display,BorderLayout.NORTH);
frame.add(center,BorderLayout.CENTER);
frame.add(down,BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent event)
{
System.exit(0);
}
});
b0.addActionListener(new NuAction());
b1.addActionListener(new NuAction());
b2.addActionListener(new NuAction());
b3.addActionListener(new NuAction());
b4.addActionListener(new NuAction());
b5.addActionListener(new NuAction());
b6.addActionListener(new NuAction());
b7.addActionListener(new NuAction());
b8.addActionListener(new NuAction());
b9.addActionListener(new NuAction());
bdot.addActionListener(new NuAction());
bdiv.addActionListener(new CoAction());
52
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

badd.addActionListener(new CoAction());
bsub.addActionListener(new CoAction());
bmul.addActionListener(new CoAction());
bequal.addActionListener(new CoAction());
back.addActionListener(new NuAction());
clear.addActionListener(new NuAction());
}
public class NuAction implements ActionListener
{
String i;
public void actionPerformed(ActionEvent e)
{
i=e.getActionCommand();
if(i.equals("back"))
{
String a=display.getText();
a=a.substring(0,a.length()-1);
display.setText(a);
}
else if(i.equals("clear"))
display.setText("");
else
{
if(s)
{
display.setText("");
s=false;
}
display.setText(display.getText()+i);
}
}
}
public class CoAction implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String i=e.getActionCommand();
if(s)
{
if(i.equals("-"))
{
display.setText(i);
s=false;
}
else last=i;
53
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

}
else
{
if(last.equals("+"))
result+=Double.parseDouble(display.getText());
else if(last.equals("-"))
result-=Double.parseDouble(display.getText());
else if(last.equals("/"))
result/=Double.parseDouble(display.getText());
else if(last.equals("*"))
result*=Double.parseDouble(display.getText());
else if(last.equals("="))
result=Double.parseDouble(display.getText());
display.setText(""+result);
last=i;
s=true;
}
}
}
public static void main(String [] args)
{
Calcu c= new Calcu();
c.launch();
}}

54
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Output:

C:\Program Files\java\jdk1.6.0\bin>javac Calcu.java


C:\Program Files\java\jdk1.6.0\bin>java Calcu

Result:

Thus a calculator using event-driven programming paradigm of Java for


Decimal manipulations and scientific manipulations was designed.
55
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Ex.No : 12
MINI PROJECT
Date:

Aim:

To develop a database for student details and use JDBC to connect to


back-end database.

Procedure:

Step 1: Click start->control panel->administrative tools.


Step 2: Select Date Sources (ODBC) from the list.

The dialog appears as below

Step 3: Select the System DSN tab.


Step 4: Click the add button.

56
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Step 5: Select Driver do Microsoft Access(*.mdb) in it.

57
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Step 6: Click Finish Button.

The following dialog opens as below


Step 7: Enter the data source name and click OK button.

Step 8: Now Double click the student data source and click Create button.

58
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Step 9: Enter the database name in the space provided and save it in the
desired
destination.

59
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Step 10: Click Ok button.


The database is created.

60
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Step 11: Now click start->All Programs->Microsoft Office->Microsoft Office


Access.
Step 12: Click File->Open.

Step 13: Select the database (student1) which was created from the desired
folder.

Step 14: Click Open button.

61
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Step 15: Select Create Table in Design View.

62
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Step 16: Create the table with necessary field and corresponding data types.

Step 17: Save the table.

Step 18: Click OK button.

63
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Step 19: Open the table and insert the values.

64
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

Step 20: Save the table.


Step 21: Establish the connection through the program.
Step 21: Retrieve the values form the database and calculate the total
and average of each student.

Coding:

import java.sql.*;
class JdbcTest
{
static String name[]=new String[50];
static int m1[]=new int[50],m2[]=new int[50],m3[]=new int[50],m4[]=new
int[50],m5[]=new int[50],tot[]=new int[50],avg[]=new int[50],id[]=new
int[50];
public static void main (String[] args)
{
int i=1;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:student";
Connection conn = DriverManager.getConnection(url,"user1","password");
System.out.println("Connection Established");
Statement st= conn.createStatement();
ResultSet rs=st.executeQuery("select * from details");
System.out.println("ID \tNAME MAT PHY CHEM ENG CS
TOTAL AVERAGE");
while(rs.next())
{
id[i]=Integer.parseInt(rs.getString(1));
name[i]=rs.getString(2);
m1[i]=Integer.parseInt(rs.getString(3));
m2[i]=Integer.parseInt(rs.getString(4));
m3[i]=Integer.parseInt(rs.getString(5));
m4[i]=Integer.parseInt(rs.getString(6));
m5[i]=Integer.parseInt(rs.getString(7));
tot[i]=m1[i]+m2[i]+m3[i];
avg[i]=tot[i]/3;
System.out.println(id[i]+"\t"+name[i]+"\t"+m1[i]+"\t"+m2[i]+"\t"+m3[i]+
"\t"+m4[i]+"\t"+m5[i]+"\t\t"+tot[i]+"\t"+avg[i]);
i++;
}
}
catch (Exception r)
{
65
Tagore Engineering College CSE CS8383 – OBJECT ORIENTED PROGRAMMING LABORATORY

System.err.println("Got an exception! ");


System.err.println(r.getMessage());
}
}
}

Output:

E:\java>javac JdbcTest.java

E:\java>java JdbcTest

Connection Established

ID NAME MAT PHY CHEM ENG CS TOTAL AVERAGE


1 Abi 95 95 95 90 100 285 95
2 Sagar 100 65 98 96 89 263 87
3 Geetha 89 75 84 96 75 248 82
4 Hari 65 87 74 62 51 226 75
5 Sapna 70 75 78 96 89 223 74

Result:

Thus database for student details and use JDBC to connect to back-end
database was developed and executed successfully.

66

You might also like