Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
37 views

Java LAB Manual 2015

The document discusses Java programming exercises for a 5th semester BCA practical manual. It contains details about creating programs to retrieve data from a phone directory database based on user input, create and perform CRUD operations on a student database, build remote method invocation applications to perform calculations, create multithreaded programs, build packages to convert temperatures and calculate interest, and create applets and Swing applications for a calculator, billing systems, etc.

Uploaded by

Sreejith P R
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Java LAB Manual 2015

The document discusses Java programming exercises for a 5th semester BCA practical manual. It contains details about creating programs to retrieve data from a phone directory database based on user input, create and perform CRUD operations on a student database, build remote method invocation applications to perform calculations, create multithreaded programs, build packages to convert temperatures and calculate interest, and create applets and Swing applications for a calculator, billing systems, etc.

Uploaded by

Sreejith P R
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Srinivas Institute of Management Studies BCA-V Semester

SRINIVAS INSTITUTE OF MANAGEMENT STUDIES


PANDESHWAR, MANGALORE-575 001

BACKGROUND LAB MANUAL

Java Programming
B.C.A - V SEMESTER

Compiled by
Mr. Krishna Prasad K
Faculty, SIMS

2015

Java Practical Manual Page 1 of 49


Srinivas Institute of Management Studies BCA-V Semester
PART A
Ex. No. Title
1 Write a program to retrieve data from personal telephone directory in
the form of a database table. When the user hits a character the names
which start with the character & the telephone number must appear.
(For example if names are Anil, Arjun,Ashwin, Ram, Raj, Deepak etc,
When ‘A’ is hit, Anil, Arjun, Ashwin must be displayed with
respective no.s., When A is continued with ‘r’, only Arjun’ detail to be
shown from the above list)
2 Write a program to create a student database with fields Stud_no,
Stud_name, Class, Mark1 & Mark2. Perform these operations a) Input
the student information from the keyboard. b) Display Specific student
information. C) Delete Specific student information
3 Write a Java class called Tempconverter with methods for calculating
conversion operations. Have this class as a servant and create a server
program and register in the rmiregistry. Write a client program to
invoke these remote methods of the servant and do the calculations.
Accept inputs interactively
4 Write a Java class called Tax with methods for calculating Income
Tax. Have this class as a servant and create a server program and
register in the rmiregistry. Write a client program to invoke these
remote methods of the servant and do the calculations. Accept inputs
interactively
5 Write a Java class called SimpleInterest with methods for calculating
Simple Interest. Have this class as a servant and create a server
program and register in the rmiregistry. Write a client program to
invoke these remote methods of the servant and do the calculations.
Accept inputs at command prompt

PART-B
Ex.No. Title
1 Write a menu driven program to accept a Number &
Reverse and sum of individual digits
To generate N Fibonacci Numbers.
2 Design a class to represent a bank account include the following
members (Using constructors). Use menu driven program.
To deposit an amount
To withdraw an amount after checking the minimum balance of
1000/=
To display the name and balance
(Data members: Name of the Depositor, Account number, Balance
amount in the account. Methods: To assign initial values
(constructors))
3 Develop a program to produce pay slip of an employee name, code,
and designation. And another base class consisting of the data
members, such as account number, date of joining and basic pay. The
Java Practical Manual Page 2 of 49
Srinivas Institute of Management Studies BCA-V Semester
derived class consists of data member of the other earning (PF, LIC,
TAX). (Implements using interface).
4 Program to demonstrate multithreading using runnable interface.
Define three different threads, one to calculate square of first n
integers, another to calculate cube of first n integers and third thread
is to find the square root of first n integers. Apply various thread
priority
5 Create a package to convert temperature in centigrade into
Fahrenheit, and one more package to calculate the simple interest.
Implements both package in the main( ) by accepting the required
inputs for each application.

PART-C
Ex.No. Title
1 Create an applet to implement simple calculator. The integer data are
to be entered through the text box and the operation that is to be
performed (operator) (+,-,*,/)to be given through the command
buttons. When the user press the compute button result should be
displayed.
Do the validation for empty text box for numbers.
Handle “Division by Zero”
2 Write an applet program to accept the employee name, employee
number and basic salary as parameters. Find the gross and net
salaries on the following conditions
3 Using the swing components, design the frame for shopping a book
that accepts book code, book name and price. Calculate the discount
on code as follows.
Code
101
102
103
Any other 5%
Find the discount amount and Net bill amount. Display the bill
4 Using the Swing components, design the form for an electricity
office for accepting meter no. customer name, previous reading, and
current reading. Use data validation to see that current reading is
more than previous reading. Produce the bill in neat format.
Bill is calculates as follows.
Compute total number of units consumed and total amount to be paid
by each consumer the condition is
If unit consumed is <= 150 charge is 200.
For next 50 units Rs 1.50 per units.
For next 100 units charge = Rs 2.00 per unit.
For next additional units charge is Rs 3.00 per unit or Rs 500
whichever is maximum

Java Practical Manual Page 3 of 49


Srinivas Institute of Management Studies BCA-V Semester

Java Practical Manual Page 4 of 49


Srinivas Institute of Management Studies BCA-V Semester
Ex 1: Write a program to retrieve data from personal telephone directory in
the form of a database table. When the user hits a character the names which
start with the character & the telephone number must appear.
(For example if names are Anil, Arjun,Ashwin, Ram, Raj, Deepak etc, When
‘A’ is hit, Anil, Arjun, Ashwin must be displayed with respective no.s.,
When A is continued with ‘r’, only Arjun’ detail to be shown from the above
list).

Database table:
Telebill
custname Phone
Anil 65839282
Arjun 65312338
Ashwin 22848898
Deepak 23455555
Raj 57388399
Ram 22365786

Mysql
mysql -u root –p
CREATE DATABASE telephone;
USE telephone
CREATE TABLE telebill (custname VARCHAR(50), phone BIGINT));
SHOW TABLES;
INSERT INTO authors (id,name,email) VALUES(“Anil”,2345678987);
...............
SELECT * FROM telebill;

Program:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.*;
public class Telephone
{
/* static block is executed when a class is loaded into memory
* this block loads MySQL's JDBC driver
*/
static
{

Java Practical Manual Page 5 of 49


Srinivas Institute of Management Studies BCA-V Semester
try
{
// loads com.mysql.jdbc.Driver into memory
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException cnf)
{
System.out.println("Driver could not be loaded: " + cnf);
}
}

public static void main(String[] args)


{
String connectionUrl = "jdbc:mysql://localhost:3306/telephone";
String dbUser = "root";
String dbPwd = "password";
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
String ch;
int flag=0;

try
{
Connection con = DriverManager.getConnection(connectionUrl, dbUser, dbPwd);
Statement st= con.createStatement();
System.out.print("Enter the first few characters of the name of the user:");
ch=in.readLine();
ResultSet rec=st.executeQuery("select * from telebill where custname like
'"+ch+"%'");
while(rec.next())
{
System.out.print(rec.getString("custname"));
System.out.println("\t"+rec.getString("phone"));
flag=1;
}
if(flag==0)
System.out.print("No record found");
}
catch (SQLException sqle)
{
System.out.println("SQL Exception thrown: " + sqle);
}
catch (IOException exp)
{
System.out.println("SQL Exception thrown: " + exp);
}
}

Java Practical Manual Page 6 of 49


Srinivas Institute of Management Studies BCA-V Semester
} //Telephone here

Output:
E:\Krishna>javac telephone.java
E:\Krishna>java telephone
Enter the first few characters of the name of the user: A
Arjun 65312338
Ashwin 22848898
Anil 65839282
E:\Krishna>java telephone
Enter the first few characters of the name of the user: ar
Arjun 65312338
E:\Krishna>java telephone
Enter the first few characters of the name of the user: Li
No record found

Java Practical Manual Page 7 of 49


Srinivas Institute of Management Studies BCA-V Semester
Ex 2: Write a program to create a student database with fields Stud_no,
Stud_name, Class, Mark1 & Mark2. Perform these operations a) Input the
student information from the keyboard. b) Display Specific student
information. C) Delete Specific student information.

Database table:
Stud
stud_no name Clas mark1 mark2
101 Ajith First BCA 70 55
103 Tom Third BCA 89 97
104 Raj Second BCom 77 45
105 Reena Second BCA 56 90
Mysql
mysql -u root –p
CREATE DATABASE student;
USE telephone
CREATE TABLE stud (stud_no int, name varchar(50), clas varchar(20), mark1 int,
mark2 int));
SHOW TABLES;
INSERT INTO stud (stud_no,name,clas,mark1,mark2) VALUES(101,”Ajith”,”First
BCA”, 70, 55);
...............
SELECT * FROM stud;

Program:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.*;
public class Student
{
/* static block is executed when a class is loaded into memory
* this block loads MySQL's JDBC driver
*/
static
{
try
{
// loads com.mysql.jdbc.Driver into memory
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException cnf)

Java Practical Manual Page 8 of 49


Srinivas Institute of Management Studies BCA-V Semester
{
System.out.println("Driver could not be loaded: " + cnf);
}
}

public static void main(String[] args)


{
String connectionUrl = "jdbc:mysql://localhost:3306/student";
String dbUser = "root";
String dbPwd = "general";
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int no,m1,m2,m3,n,ch,num,i;
String name,clas;
Connection con;

try
{
con= DriverManager.getConnection(connectionUrl, dbUser, dbPwd);
Statement st= con.createStatement();
do
{
i=0;
System.out.println("\nMENU\n1.Input student information\n2.Delete
specific student information\n3.Display\n4.Exit");
System.out.println("Enter your choice:");
ch=Integer.parseInt(in.readLine());
switch(ch)
{
case 1: System.out.println("How many students you want to
enter?");
n=Integer.parseInt(in.readLine());
while(i<n)
{
System.out.println("Enter the student number:");
no=Integer.parseInt(in.readLine());
System.out.println("Enter the student name:");
name=in.readLine();
System.out.println("Enter the student class:");
clas=in.readLine();
System.out.println("Enter the 1st mark:");
m1=Integer.parseInt(in.readLine());
System.out.println("Enter the 2nd mark:");
m2=Integer.parseInt(in.readLine());
num=st.executeUpdate("insert into stud
values("+no+",'"+name+"','"+clas+"',"+m1+","+m2+")");
i++;

Java Practical Manual Page 9 of 49


Srinivas Institute of Management Studies BCA-V Semester
}
break;
case 2: System.out.println("Enter the student number whose
details you want to delete:");
no=Integer.parseInt(in.readLine());
st.executeUpdate("delete from stud where stud_no="+no);
break;
case 3: System.out.println("Enter the student number whose
details you want:");
num=Integer.parseInt(in.readLine());
ResultSet rec=st.executeQuery("select * from stud
where stud_no="+num);
if(rec.next())
{
System.out.println("Student
number="+rec.getString("stud_no"));
System.out.println("Student
name="+rec.getString("stud_name"));
System.out.println("Student
class="+rec.getString("clas"));
System.out.println("Student
Mark1="+rec.getString("mark1"));
System.out.println("Student
Mark2="+rec.getString("mark2"));
}
else
System.out.println("Record not found");
break;
case 4: System.exit(0); }
}
while(ch<=4);
}
catch (SQLException sqle)
{
System.out.println("SQL Exception thrown: " + sqle);
}
catch (IOException exp)
{
System.out.println("SQL Exception thrown: " + exp);
}
}
} //Student here

Output:
E:\Krishna>javac student.java
E:\Krishna>java student

Java Practical Manual Page 10 of 49


Srinivas Institute of Management Studies BCA-V Semester
MENU
1.Input student information
2.Delete specific student information
3.Display
4.Exit
Enter your choice:
1
How many students you want to enter?
5
Enter the student number:
101
Enter the student name:
Ajith
Enter the student class:
First BCA
Enter the 1st mark:
70
Enter the 2nd mark:
55
Enter the student number:
102
Enter the student name:
Rani
Enter the student class:
Third BBM
Enter the 1st mark:
67
Enter the 2nd mark:
50
Enter the student number:
103
Enter the student name:
Tom
Enter the student class:
Third BCA
Enter the 1st mark:
89
Enter the 2nd mark:
97
Enter the student number:
104
Enter the student name:
Raj
Enter the student class:
Second BCom
Enter the 1st mark:

Java Practical Manual Page 11 of 49


Srinivas Institute of Management Studies BCA-V Semester
77
Enter the 2nd mark:
45
Enter the student number:
105
Enter the student name:
Reena
Enter the student class:
Second BCA
Enter the 1st mark:
56
Enter the 2nd mark:
90

MENU
1.Input student information
2.Delete specific student information
3.Display
4.Exit
Enter your choice:
3
Enter the student number whose details you want:
104
Student number=104
Student name=Raj
Student class=Second BCom
Student Mark1=77
Student Mark2=45

MENU
1.Input student information
2.Delete specific student information
3.Display
4.Exit
Enter your choice:
2
Enter the student number whose details you want to delete:
102

MENU
1.Input student information
2.Delete specific student information
3.Display
4.Exit
Enter your choice:
3

Java Practical Manual Page 12 of 49


Srinivas Institute of Management Studies BCA-V Semester
Enter the student number whose details you want:
102
Record not found

MENU
1.Input student information
2.Delete specific student information
3.Display
4.Exit
Enter your choice:
4

Java Practical Manual Page 13 of 49


Srinivas Institute of Management Studies BCA-V Semester
Ex 3: Write a Java class called Tempconverter with methods for calculating
conversion operations. Have this class as a servant and create a server
program and register in the rmiregistry. Write a client program to invoke
these remote methods of the servant and do the calculations. Accept inputs
interactively.

Interface Code:
import java.rmi.*;
public interface tempintf extends Remote
{
double ctof(double c)throws RemoteException;
double ftoc(double f)throws RemoteException;
}
Implementation code:
import java.rmi.*;
import java.rmi.server.*;
public class tempimp extends UnicastRemoteObject implements tempintf
{
public double ctof(double c)throws RemoteException
{
double f=c*180.0/100+32.0;
return f;
}
public double ftoc(double f)throws RemoteException
{
double c=(f-32)*100/180.0;
return c;
}
public tempimp() throws RemoteException{};
}
Server code:
import java.rmi.*;
import java.net.*;
public class tempserver
{
public static void main(String args[])
{
try
{
tempimp x=new tempimp();
Naming.rebind("tempserver",x);
}
catch(Exception e){}
}
}

Java Practical Manual Page 14 of 49


Srinivas Institute of Management Studies BCA-V Semester
Client code:
import java.rmi.*;
import java.io.*;
public class tempclient
{
public static void main(String args[])
{
try
{
BufferedReader in=new BufferedReader(new
InputStreamReader(System.in));
Tempintf t=(tempintf)Naming.lookup("rmi://localhost/tempserver");
System.out.println("\n\f\tTEMPERATURE CONVERSION\n");
System.out.print("Enter the celsius value:");
float c=Float.valueOf(in.readLine());
System.out.println("Celsius to fahrenhit is:"+t.ctof(c));
System.out.print("Enter the fahrenhit value:");
float f=Float.valueOf(in.readLine());
System.out.println("Fahrenhit to celsius is:"+t.ftoc(f));
}
catch(Exception e){}
}
}

Output:
E:\krishna>rmic tempimp
E:\krishna>rmiregistry &
E:\krishna>java tempserver
E:\krishna>java tempclient

TEMPERATURE CONVERSION
Enter the celsius value:38
Celsius to fahrenhit is:100.4
Enter the fahrenhit value:100.4
Fahrenhit to celsius is:38.0000008477105

Java Practical Manual Page 15 of 49


Srinivas Institute of Management Studies BCA-V Semester
Ex 4: Write a Java class called Tax with methods for calculating Income
Tax. Have this class as a servant and create a server program and register in
the rmiregistry. Write a client program to invoke these remote methods of
the servant and do the calculations. Accept inputs interactively.

Interface Code:
import java.rmi.*;
public interface taxintf extends Remote
{
double tax(double t)throws RemoteException;
}
Implementation code:
import java.rmi.*;
import java.rmi.server.*;
public class taximp extends UnicastRemoteObject implements taxintf
{
public double tax(double t)throws RemoteException
{
double tax=0;
if(t<10000)
tax=0;
if((t>=10000)&&(t<=25000))
tax=0.025*t;
if((t>=25000)&&(t<=100000))
tax=0.05*t;
if((t>=100000)&&(t<=1000000))
tax=0.075*t;
if(t>1000000)
tax=0.10*t;
return tax;
}
public taximp()throws RemoteException{};
}
Server code:
import java.rmi.*;
import java.net.*;
public class taxserver
{
public static void main(String args[])
{
try
{
taximp x=new taximp();
Naming.rebind("taxserver",x);
}
catch(Exception e)

Java Practical Manual Page 16 of 49


Srinivas Institute of Management Studies BCA-V Semester
{
System.out.println("ERROR:"+e);
}
}
}
Client code:
import java.rmi.*;
import java.io.*;
public class taxclient
{
public static void main(String args[])
{
try
{
BufferedReader in=new BufferedReader(new
InputStreamReader(System.in));
taxintf x=(taxintf)Naming.lookup("rmi://localhost/taxserver");
System.out.print("Enter the salary:");
double t=Double.valueOf(in.readLine()).doubleValue();
double it=x.tax(t);
if(it==0)
{
System.out.println("\n\tAs our salary needs more than 10000.....!");
System.out.println("\n\tNo tax deducted.....!");
System.exit(0);
}
System.out.println("\nThe tax is:"+it);
}
catch(Exception e)
{
System.out.println("ERROR:"+e);
}
}
}
Output:
E:\krishna>rmic taximp
E:\krishna>start rmiregistry
E:\krishna>java taxserver
E:\krishna>java taxclient
Enter the salary:10000
The tax is:250.0
E:\krishna>java taxclient
Enter the salary:1000
As our salary needs more than 10000.....!
No tax deducted.....!

Java Practical Manual Page 17 of 49


Srinivas Institute of Management Studies BCA-V Semester
Ex 5: Write a Java class called SimpleInterest with methods for calculating
Simple Interest. Have this class as a servant and create a server program and
register in the rmiregistry. Write a client program to invoke these remote
methods of the servant and do the calculations. Accept inputs at command
prompt.

Interface Code:
import java.rmi.*;
public interface simpintf extends Remote
{
double simpleint(double p,double t,double r)throws RemoteException;
}
Implementation code:
import java.rmi.*;
import java.rmi.server.*;
public class simpimp extends UnicastRemoteObject implements simpintf
{
public double simpleint(double p,double t,double r)throws
RemoteException
{
double f=p*t*r/100;
return f;
}
public simpimp() throws RemoteException{};
}
Server code:
import java.rmi.*;
import java.net.*;
public class simpserver
{
public static void main(String args[])
{
try
{
simpimp x=new simpimp();
Naming.rebind("simpserver",x);
}
catch(Exception e)
{
System.out.println("ERROR:"+e);

Java Practical Manual Page 18 of 49


Srinivas Institute of Management Studies BCA-V Semester
}
}
}
Client code:
import java.rmi.*;
import java.io.*;
public class simpclient
{
public static void main(String args[])
{
try
{
BufferedReader in=new BufferedReader(new
InputStreamReader(System.in));
simpintf
s=(simpintf)Naming.lookup("rmi://localhost/simpserver");
double p=Double.valueOf(args[0]).doubleValue();
double t=Double.valueOf(args[1]).doubleValue();
double r=Double.valueOf(args[2]).doubleValue();
System.out.println("\nThe Simple Interest
is:"+s.simpleint(p,t,r));
}
catch(Exception e)
{
System.out.println("ERROR:"+e);
}
}
}
Output:
E:\Krishna>rmic simpimp
E:\Krishna>start rmiregistry
E:\Krishna>java simpserver
E:\Krishna>java simpclient 1000 3 5
The Simple Interest is:150.0

Java Practical Manual Page 19 of 49


Srinivas Institute of Management Studies BCA-V Semester

Java Practical Manual Page 20 of 49


Srinivas Institute of Management Studies BCA-V Semester
Ex 1 : Write a menu driven program to accept a Number &
Reverse and sum of individual digits
To generate N Fibonacci Numbers.

Program:
import java.io.*;
class s_r_f
{
public static void main(String args[])
{
try
{
String atr;
int i,n,num,sum=0,rem,rev;
int ch=1,n1,fib1,fib2,fib3;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("****");
System.out.println("MENU");
System.out.println("---------------");
System.out.println("\n1.Sum and Reverse \n 2. Fibonacci series");
System.out.println("__________________________");
while(ch<=2)
{
System.out.println("Enter your choice");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1: System.out.println("Enter the number for Sum and
Reverse");
num=Integer.parseInt(br.readLine());
n=num;
rev=0;
sum=0;
while(n!=0)
{
rem=n%10;
rev=rev*10+rem;
sum=sum+rem;
n=n/10;
}
System.out.println("The reverse is : "+rev);
System.out.println("The sum of is : "+sum);
break;
case 2: System.out.println("Enter the first number for
fibonacci series");

Java Practical Manual Page 21 of 49


Srinivas Institute of Management Studies BCA-V Semester
n1=Integer.parseInt(br.readLine());
fib1=0;
fib2=1;
System.out.println("First n fibonacci series :");
System.out.println(fib1+"\t");
System.out.println(fib2+"\t");
i=3;
while(i<=n1)
{
fib3=fib1+fib2;
fib1=fib2;
fib2=fib3;
System.out.println(fib3+"\t");
i=i+1;
}
System.out.print("\n");
}
}
}

catch(Exception e) {}
}
}
Output:
E:\krishna>java s_r_f
****
MENU
---------------
1.Sum and Reverse
2. Fibonacci series
____________
Enter your choice
1
Enter the number for Sum and Reverse
121
The reverse is : 121
The sum of is : 4
Enter your choice
2
Enter the first number for fibonacci series
5
First n fibonacci series :
0 11 2 3

Java Practical Manual Page 22 of 49


Srinivas Institute of Management Studies BCA-V Semester
Ex 2: Design a class to represent a bank account include the following
members (Using constructors). Use menu driven program.
To deposit an amount
To withdraw an amount after checking the minimum balance of 1000/=
To display the name and balance
(Data members: Name of the Depositor, Account number, Balance amount
in the account. Methods: To assign initial values (constructors))

Program:
Bank.java:
import java.io.*;
class bank
{
String name;
int acc_no;
long balance;
bank(String name,int acc_no,long balance)
{
this.name=name;
this.acc_no=acc_no;
this.balance=balance;
}
void deposit(long amount)
{
balance=balance+amount;
}
void withdraw(long amount)
{
if(balance>amount)
{
if((balance-amount)>=1000)
{
balance-=amount;
System.out.println("Amount is successfully withdrawn");
}
else
System.out.println("Unsufficient balance(Minimum
balance=1000)");
}
else
System.out.println("Amount should be less than the
balance(Unsufficient balance)");
}
void display()
{

Java Practical Manual Page 23 of 49


Srinivas Institute of Management Studies BCA-V Semester
System.out.print("Name:"+name+"\n");
System.out.print("Balance is:"+balance+"\n");
}
}
Bank_trans.java:
import java.io.*;
class bank_trans
{
public static void main(String args[])
{
int acc_no,i,op=1;
long balance,amount;
String name;
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("***********************");
System.out.println("Enter the account number:");
acc_no=Integer.parseInt(br.readLine());
System.out.println("Enter the name of account holder:");
name=br.readLine();
System.out.println("Enter the initial amount of deposit:");
balance=Long.parseLong(br.readLine());
bank b = new bank(name,acc_no,balance);
while(op!=4)
{
System.out.println("*************************");
System.out.println("1.Deposit"+"\n"+"2.Withdrawal"+"\n
"+"3.Display"+"\n"+"4.Exit");
System.out.println("*************************");
System.out.println("Enter your option:");
op=Integer.parseInt(br.readLine());
switch(op)
{
case 1: System.out.println("Enter the amount to be
deposited:");
amount=Long.parseLong(br.readLine());
b.deposit(amount);
break;
case 2: System.out.println("Enter the amount to be
withdrawn:");
amount=Long.parseLong(br.readLine());
b.withdraw(amount);
break;
case 3: b.display();

Java Practical Manual Page 24 of 49


Srinivas Institute of Management Studies BCA-V Semester
break;
case 4: System.exit(0);

}
}
}
catch(Exception e){}
}
}

Output:
E:\jeslin>java bank_trans
***********************
Enter the account number:
101
Enter the name of account holder:
Ram
Enter the initial amount of deposit:
2000
*************************
1.Deposit
2.Withdrawal
3.Display
4.Exit
*************************
Enter your option:
1
Enter the amount to be deposited:
1000
*************************
1.Deposit
2.Withdrawal
3.Display
4.Exit
*************************
Enter your option:
3
Name:Ram
Balance is:3000
*************************
1.Deposit
2.Withdrawal
3.Display
4.Exit
*************************
Enter your option:

Java Practical Manual Page 25 of 49


Srinivas Institute of Management Studies BCA-V Semester
2
Enter the amount to be withdrawn:
1000
Amount is successfully withdrawn
*************************
1.Deposit
2.Withdrawal
3.Display
4.Exit
*************************
Enter your option:
3
Name:Ram
Balance is:2000
*************************
1.Deposit
2.Withdrawal
3.Display
4.Exit
*************************
Enter your option:
2
Enter the amount to be withdrawn:
3000
Amount should be less than the balance(Unsufficient balance)
*************************
1.Deposit
2.Withdrawal
3.Display
4.Exit
Enter your option:
4

Java Practical Manual Page 26 of 49


Srinivas Institute of Management Studies BCA-V Semester
Ex 3: Develop a program to produce pay slip of an employee name, code,
and designation. And another base class consisting of the data members,
such as account number, date of joining and basic pay. The derived class
consists of data member of the other earning (PF, LIC, TAX). (Implements
using interface).

Program:
Emp1.java:
import java.io.*;
class emp1
{
String name;
int code;
String desig;
void getdata1()
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter employee name : ");
name=br.readLine();
System.out.println("Enter employee code : ");
code=Integer.parseInt(br.readLine());
System.out.println("Enter deisgnatiom : ");
desig=br.readLine();
}

catch(Exception e)
{}
}

void putdata1()
{
System.out.println("Name "+name);
System.out.println("Code :"+code);
System.out.println("Designation :"+desig);
}
}
class emp2 extends emp1
{
int acc_no;
String doj;
int pay;
void getdata2()

Java Practical Manual Page 27 of 49


Srinivas Institute of Management Studies BCA-V Semester
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter employee account number : ");
acc_no=Integer.parseInt(br.readLine());
System.out.println("Enter employee DOJ: ");
doj=br.readLine();
System.out.println("Enter salary : ");
pay=Integer.parseInt(br.readLine());
}
catch(Exception e)
{}
}
void putdata2()
{
System.out.println("Account number : "+acc_no);
System.out.println("DOJ"+doj);
System.out.println("Salary "+pay);
}
}

class emp3 extends emp2


{
int da,hra,cca,pf,lic,tax;
void getdata3()
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter employee DA : ");
da=Integer.parseInt(br.readLine());
System.out.println("Enter employee HRA : ");
hra=Integer.parseInt(br.readLine());
System.out.println("Enter employee CCA : ");
cca=Integer.parseInt(br.readLine());
System.out.println("Enter employee PF : ");
pf=Integer.parseInt(br.readLine());
System.out.println("Enter employee LIC : ");
lic=Integer.parseInt(br.readLine());
System.out.println("Enter employee TAX : ");
tax=Integer.parseInt(br.readLine());
}
catch(Exception e) {}

Java Practical Manual Page 28 of 49


Srinivas Institute of Management Studies BCA-V Semester
}
void putdata3()
{
System.out.println("DA :"+da);
System.out.println("HRA :"+hra);
System.out.println("CCA :"+cca);
System.out.println("PF :"+pf);
System.out.println("LIC :"+lic);
System.out.println("TAX :"+tax);
}
}
interface employee
{
void putwt();
}
class emp4 extends emp3 implements employee
{
public void putwt()
{
getdata1();
getdata2();
getdata3();
System.out.println("\nEMPLOYEE DETAILS\n");
System.out.println("_________________________________");
putdata1();
putdata2();
putdata3();
}
int gross()
{
return((pay+da+hra+cca)-(pf+lic+tax));
}
public void display()
{
putwt();
}
}
Employeebio.java:
import java.io.*;
class employeebio
{
public static void main(String args[])
{
int r;
emp4 c4=new emp4();
c4.display();

Java Practical Manual Page 29 of 49


Srinivas Institute of Management Studies BCA-V Semester
r=c4.gross();
System.out.println("Gross pay : "+r);
}
}

Output:
E:\Krishna>java employeebio
Enter employee name :
Raj
Enter employee code :
1001
Enter deisgnatiom :
Manager
Enter employee account number
2234
Enter employee DOJ:
14 May
Enter salary :
60000
Enter employee DA :
100
Enter employee HRA :
250
Enter employee CCA :
150
Enter employee PF :
300
Enter employee LIC :
210
Enter employee TAX :
130
EMPLOYEE DETAILS
______________________________
Name Raj
Code :1001
Designation :Manager
Account number : 2234
DOJ: 14 May
Salary: 60000
DA :100
HRA :250
CCA :150
PF :300
LIC :210
TAX :130
Gross pay : 59860

Java Practical Manual Page 30 of 49


Srinivas Institute of Management Studies BCA-V Semester
Ex 4: Program to demonstrate multithreading using runnable interface.
Define three different threads, one to calculate square of first n integers,
another to calculate cube of first n integers and third thread is to find the
square root of first n integers. Apply various thread priority.

Program:
import java.io.*;
class sqr implements Runnable
{
int n, i;
sqr(int no)
{
n=no;
}
public void run()
{
for (i=1;i<=n;i++)
System.out.println("square of " + i + "is: " + (i*i));
System.out.println("\n");
}
}
class cube implements Runnable
{
int n, j;
cube(int no)
{
n = no;
}
public void run()
{
for(j=1;j<=n;j++)
System.out.println("cube of "+j+"is: "+(j*j*j));
System.out.println("\n");
}
}
class str implements Runnable
{
int n,k;
str(int no)
{
n=no;
}
public void run()
{
for(k=1;k<=n;k++)

Java Practical Manual Page 31 of 49


Srinivas Institute of Management Studies BCA-V Semester
System.out.println("square root of the no: "+k+" is:
"+Math.sqrt(k));
System.out.println("\n");
}
}
class multithread
{
public static void main(String args[])
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter the maximum no:");
int n=Integer.parseInt(br.readLine());
sqr s=new sqr(n);
cube c=new cube(n);
str st=new str(n);
Thread t1=new Thread(s);
Thread t2=new Thread(c);
Thread t3=new Thread(st);
t3.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(t1.getPriority()+1);
t1.setPriority(Thread.MIN_PRIORITY);
System.out.println("start thread +1");
t1.start();
System.out.println("start thread +2");
t2.start();
System.out.println("start thread +3");
t3.start();
System.out.println("\n");
}
catch(Exception e){}
}
}
Output:
enter the maximum no: 3
start thread +1
start thread +2
start thread +3
cube of 1is: 1
cube of 2is: 8
cube of 3is: 27
square of 1is: 1
square of 2is: 4
square of 3is: 9

Java Practical Manual Page 32 of 49


Srinivas Institute of Management Studies BCA-V Semester
square root of the no: 1 is: 1.0
square root of the no: 2 is: 1.4142135623730951
square root of the no: 3 is: 1.7320508075688772

Java Practical Manual Page 33 of 49


Srinivas Institute of Management Studies BCA-V Semester
Ex 5: Create a package to convert temperature in centigrade into Fahrenheit,
and one more package to calculate the simple interest. Implements both
package in the main() by accepting the required inputs for each application.

Package to Covert temperature:


package pack1;
import java.io.*;
public class converter
{
public void cf()
{
double r = 0.0;
double c = 0.0;
try
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the value of centigrade:");
c = Double.parseDouble(br.readLine());
}
catch (Exception e) { }
r = (c * 9) / 5 + 32;
System.out.println("Fahrenheit value of given centigrade is " + r);
}
public void fc()
{
double f = 0.0;
double t = 0.0;
try
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the value of fahrenheit:");
f = Double.parseDouble(br.readLine());
}
catch (Exception e) { }
t = (f - 32) * 5 / 9;
System.out.println("Centigrade value of given fahrenheit is " + t);
}
}

Package to Calculate simple interest:


package pack2;
import java.io.*;
public class simpleinterest
{

Java Practical Manual Page 34 of 49


Srinivas Institute of Management Studies BCA-V Semester
float principle,time,interest,si;
public void element()
{
try
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("enter the principal");
principle = Float.parseFloat(br.readLine());
System.out.println("enter the time:");
time = Float.parseFloat(br.readLine());
System.out.println("enter the rate of interest");
interest = Float.parseFloat(br.readLine());
}
catch (Exception e) { }
}
public void calculate()
{
si=(principle*time*interest)/100;
}
public void display()
{
System.out.println("principle is:"+principle);
System.out.println("time is:"+time);
System.out.println("interest is:"+interest);
System.out.println("simple interest is:"+si);
}
}

Main program:
import pack1.*;
import pack2.*;
class simple
{
public static void main(String args[])
{
System.out.println("Program output");
System.out.println("*****************");
converter con = new converter();
System.out.println("Temperature conversion: ");
con.cf();
System.out.println("");
con.fc();
System.out.println("");
simpleinterest simp = new simpleinterest();
System.out.println("");

Java Practical Manual Page 35 of 49


Srinivas Institute of Management Studies BCA-V Semester
System.out.println("Simple Interest: ");
simp.element();
simp.calculate();
simp.display();
System.out.println("");
}
}

Output:
Program output
*****************
Temperature conversion:
Enter the value of centigrade:
34
Fahrenheit value of given centigrade is 93.2
Enter the value of fahrenheit:
93.2
Centigrade value of given fahrenheit is 34.0
Simple Interest:
enter the principal
1000
enter the time: 5
enter the rate of interest
3
principle is:1000.0
time is:5.0
interest is:3.0
simple interest is:150.0

Java Practical Manual Page 36 of 49


Srinivas Institute of Management Studies BCA-V Semester

Java Practical Manual Page 37 of 49


Srinivas Institute of Management Studies BCA-V Semester
Ex 1: Create an applet to implement simple calculator. The integer data are
to be entered through the text box and the operation that is to be performed
(operator) (+,-,*,/)to be given through the command buttons. When the user
press the compute button result should be displayed.
Do the validation for empty text box for numbers.
Handle “Division by Zero”

Program:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class cal extends Applet implements ActionListener
{
int num1,num2;
int result=0;
String r;
TextField txt1;
TextField txt2;
Label l1;
Label l2;
Label l3;
Label l4;
Button plus;
Button minus;
Button mul;
Button div;
Button compute;
Button clear;
public void init()
{
txt1=new TextField();
txt2=new TextField();
l1=new Label("ENTER THE FIRST NUMBER");
l2=new Label("ENTER THE SECOND NUMBER");
l3=new Label("Result");
l4=new Label("");
plus=new Button("+");
minus=new Button("-");
mul=new Button("*");
div=new Button("/");
compute=new Button("Compute");
setLayout(null);
add(txt1);
add(txt2);
add(l1);

Java Practical Manual Page 38 of 49


Srinivas Institute of Management Studies BCA-V Semester
add(l2);
add(l3);
add(l4);
add(plus);
add(minus);
add(plus);
add(minus);
add(mul);
add(div);
add(compute);
txt1.setBounds(300,20,80,20);
txt2.setBounds(300,50,80,20);
plus.setBounds(100,80,40,20);
minus.setBounds(150,80,40,20);
mul.setBounds(200,80,40,20);
div.setBounds(250,80,40,20);
l1.setBounds(100,20,200,25);
l2.setBounds(100,50,200,25);
l3.setBounds(100,100,100,25);
l4.setBounds(200,100,200,25);
compute.setBounds(290,150,80,25);
compute.addActionListener(this);
plus.addActionListener(this);
minus.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
repaint();
}
public void actionPerformed(ActionEvent d)
{
try
{
num1=Integer.parseInt(txt1.getText());
num2=Integer.parseInt(txt2.getText());
if(d.getSource()==plus)
{
result=num1+num2;
}

if(d.getSource()==minus)
{
result=num1-num2;

}
if(d.getSource()==mul)

Java Practical Manual Page 39 of 49


Srinivas Institute of Management Studies BCA-V Semester
{
result=num1*num2;

}
if(d.getSource()==div)
{
try
{
result=num1/num2;
}
catch(ArithmeticException e1)
{
l4.setText("Division by zero is invalid");
}
}
if(d.getSource()==compute)
{

r=Integer.toString(result);
l4.setText(r);

}
}
catch(NumberFormatException e)
{
l4.setText("Invalid Number");
}
}
}
HTML file for applet:
<html>
<head>
<title>
Calculator
</title>
</head>
<body>
<applet code=cal.class
width=400
height=400>
</applet>
</body>
</html>
Output:
E:\krishna>appletviewer cal.html

Java Practical Manual Page 40 of 49


Srinivas Institute of Management Studies BCA-V Semester

Java Practical Manual Page 41 of 49


Srinivas Institute of Management Studies BCA-V Semester
Ex 2: Write an applet program to accept the employee name, employee
number and basic salary as parameters. Find the gross and net salaries on the
following conditions.

Program:
import java.awt.*;
import java.applet.*;
public class employee extends Applet
{
String ename;
int enumber;
double bsalary;
double netsalary;
double grosssalary;
double da,hra,pf,pt;
public void init()
{

ename = getParameter("param1");
enumber = Integer.parseInt(getParameter("param2"));
bsalary = Double.parseDouble(getParameter("param3"));
calculate();
}
public void paint(Graphics g)
{
g.drawString("Employee Name is: " + ename,20,20);
g.drawString("Employee Number is: " + enumber,20,40);
g.drawString("Basic Salary is: " + bsalary,20,60);
g.drawString("DA is: " + da,20,80);
g.drawString("HRA is: " + hra,20,100);
g.drawString("Gross Salary is: " + grosssalary,20,120);
g.drawString("PF is: " + pf,20,140);
g.drawString("PT is: " + pt,20,160);
g.drawString("Net Pay is: " + netsalary,20,180);
}
public void calculate()
{
if (bsalary <= 20000)
{
da=.40*bsalary;
hra=.10*bsalary;
grosssalary=da+hra;
pf=.12*grosssalary;
pt=100;
netsalary=grosssalary-(pf+pt);
}

Java Practical Manual Page 42 of 49


Srinivas Institute of Management Studies BCA-V Semester
if (bsalary > 20000)
{
da=.50*bsalary;
hra=.15*bsalary;
grosssalary=da+hra;
pf=.12*grosssalary;
pt=150;
netsalary=grosssalary-(pf+pt);
}
}
}
HTML file for applet:
<html>
<head>
<title>
Employee Pay Slip
</title>
</head>
<body>
<applet code=employee.class width=500 height=500>
<param name="param1" value="Ganesh">
<param name="param2" value="1001">
<param name="param3" value="19500">
</applet>
</body>
</html>
Output:
E:\jeslin>appletviewer employee.html

Java Practical Manual Page 43 of 49


Srinivas Institute of Management Studies BCA-V Semester
Ex 3: Using the swing components, design the frame for shopping a book
that accepts book code, book name and price. Calculate the discount on code
as follows.
Code Discount rate
101 15%
102 20%
103 25%
Any other 5%
Find the discount amount and Net bill amount. Display the bill.

Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Shoppingbook1 implements ActionListener
{
JLabel lcode;
JLabel lname;
JLabel lprice;
JLabel ldiscount;
JLabel lnetbill;
JTextField tcode;
JTextField tname;
JTextField tprice;
JTextField tdiscount;
JTextField tnetbill;
JButton bill;
Shoppingbook1 ( )
{
JFrame jfrm=new JFrame("BOOK SHOPPING BILL");
jfrm.setLayout(null);
jfrm.setSize(300,300);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
lcode = new JLabel("BooK Code:");
tcode= new JTextField ( );
lname = new JLabel("Book Name:");
tname = new JTextField ( );
lprice = new JLabel("Book Price:");
tprice = new JTextField ( );
ldiscount = new JLabel("Discount: ");
tdiscount = new JTextField ( );
lnetbill = new JLabel("Final Price:");
tnetbill = new JTextField ( );
bill=new JButton("Bill");
lcode.setBounds(20,20,80, 10);
Java Practical Manual Page 44 of 49
Srinivas Institute of Management Studies BCA-V Semester
tcode.setBounds(100,18,100,20);
lname.setBounds(20,50,80,10);
tname.setBounds(100,48,100,20);
lprice.setBounds(20,80,80,10);
tprice.setBounds(100,78,100,20);
ldiscount.setBounds(20,110,80,10);
tdiscount.setBounds(100,108,100,20);
lnetbill.setBounds(20,140,80,10);
tnetbill.setBounds(100,138,100,20);
bill.setBounds(100,180,60,30);
jfrm.add(lcode);
jfrm.add(tcode);
jfrm.add(lname);
jfrm.add(tname);
jfrm.add(lprice);
jfrm.add(tprice);
jfrm.add(ldiscount);
jfrm.add(tdiscount);
jfrm.add(lnetbill);
jfrm.add(tnetbill);

bill.addActionListener(this);
jfrm.add(bill);
jfrm.setVisible(true);
tdiscount.setEditable(false);
tnetbill.setEditable(false);

}
public void actionPerformed(ActionEvent ae)
{
double discount;
String discountamt,netbillamt;
double price;
double netbill;
try
{
int codeval=Integer.parseInt(tcode.getText());
if (codeval==101)
discount=15;
else if(codeval==102)
discount=20;
else if(codeval==103)
discount=25;
else
discount=5;
discountamt=Double.toString(discount);

Java Practical Manual Page 45 of 49


Srinivas Institute of Management Studies BCA-V Semester
if (!(tcode.getText().equals("")) && !(tname.getText( ).equals("")) &&
!(tprice.getText().equals("")))
//tdiscount.setText("");
//else
tdiscount.setText(discountamt+"%");
price=Integer.parseInt(tprice.getText());
netbill=price-(price*discount/100);
netbillamt=Double.toString(netbill);
tnetbill.setText(netbillamt);
}
catch(NumberFormatException e)
{
tnetbill.setText("Invalid Number");
}

}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable ( ) {
public void run() {
new Shoppingbook1( );
}
});
}
}
Output:
E:\Krishna>java Shoppingbook1

Java Practical Manual Page 46 of 49


Srinivas Institute of Management Studies BCA-V Semester
Ex 4: Using the Swing components, design the form for an electricity office
for accepting meter no. customer name, previous reading, and current
reading. Use data validation to see that current reading is more than previous
reading. Produce the bill in neat format.
Bill is calculates as follows.
Compute total number of units consumed and total amount to be paid by
each consumer the condition is
If unit consumed is <= 150 charge is 200.
For next 50 units Rs 1.50 per units.
For next 100 units charge = Rs 2.00 per unit.
For next additional units charge is Rs 3.00 per unit or Rs 500 whichever is
maximum.

Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;

public class Electricity1 implements ActionListener


{
JLabel lmeterno;
JLabel lcname;
JLabel lpreading;
JLabel lcreading;
JLabel lamount;
JTextField tmeterno;
JTextField tcname;
JTextField tpreading;
JTextField tcreading;
JTextField tamount;
JButton bill;

Electricity1( )
{
JFrame jfrm=new JFrame("ELECTRICITY BILL");
jfrm.setLayout(null);
jfrm.setSize(300,300);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
lmeterno = new JLabel("Meter No: ");
tmeterno= new JTextField ( );
lcname = new JLabel("Customer Name:");
tcname = new JTextField ( );
lpreading = new JLabel("Previous Reading:");

Java Practical Manual Page 47 of 49


Srinivas Institute of Management Studies BCA-V Semester
tpreading = new JTextField ( );
lcreading = new JLabel("Current Reading:");
tcreading = new JTextField ( );
lamount = new JLabel("Amount to be paid:");
tamount = new JTextField ( );
bill=new JButton("Bill");
lcname.setBounds(20,20,120, 20);
tcname.setBounds(140,18,100,20);
lpreading.setBounds(20,50,120,20);
tpreading.setBounds(140,48,100,20);
lcreading.setBounds(20,80,120,20);
tcreading.setBounds(140,78,100,20);
lamount.setBounds(20,110,120,20);
tamount.setBounds(140,108,100,20);
bill.setBounds(100,140,80,30);
jfrm.add(lmeterno);
jfrm.add(tmeterno);
jfrm.add(lcname);
jfrm.add(tcname);
jfrm.add(lpreading);
jfrm.add(tpreading);
jfrm.add(lcreading);
jfrm.add(tcreading);
jfrm.add(lamount);
jfrm.add(tamount);
bill.addActionListener(this);
jfrm.add(bill);
jfrm.setVisible(true);
tamount.setEditable(false);
}
public void actionPerformed(ActionEvent ae)
{
int unit, creading,preading;
double charge=0;
String netamount;
try
{
preading=Integer.parseInt(tpreading.getText());
creading=Integer.parseInt(tcreading.getText());
if (creading > preading)
{
unit=creading-preading;
if (unit<=150)
charge=200;
else if(unit>150 && unit<=200)
charge=unit*1.50;

Java Practical Manual Page 48 of 49


Srinivas Institute of Management Studies BCA-V Semester
else if(unit>200 && unit<=300)
charge=unit*2;
else
charge=Math.max(unit*3,500);
netamount=Double.toString(charge);
tamount.setText(netamount);
}
else
{
tamount.setText("Invalid Reading");
}

}
catch(NumberFormatException e)
{
tamount.setText("Invalid Number");
}

}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable ( ) {
public void run() {
new Electricity1( );
}
}
);
}
}
Output:
E:\Krishna>java Electricity1

Java Practical Manual Page 49 of 49

You might also like