Lab Manual Final
Lab Manual Final
No 1
ELECTRICITY BILL CALCULATOR
DATE:
Question
Develop a Java application to generate Electricity bill. Create a class with the following
members: Consumer no., consumer name, previous month reading, current month reading,
type of EB connection (i.e domestic or commercial). Compute the bill amount using the
following tariff.
If the type of the EB connection is domestic, calculate the amount to be paid as follows:
• First 100 units - Rs. 1 per unit
• 101-200 units - Rs. 2.50 per unit
• 201 -500 units - Rs. 4 per unit
• > 501 units - Rs. 6 per unit
If the type of the EB connection is commercial, calculate the amount to be paid as follows:
• First 100 units - Rs. 2 per unit
• 101-200 units - Rs. 4.50 per unit
• 201 -500 units - Rs. 6 per unit
• > 501 units - Rs. 7 per unit
Aim
To create a Java console application used to generate electricity bill based on connection
type (Domestic and Commercial) and consumption. Both are having different tariff slots.
Attributes
• Consumer Number
• Consumer Name
• Previous Month Reading
• Current Month Reading
• isDomestic [To Check with user for domestic or commercial connection]
• totalBillAmount
Methods
• getDetails [To get the user details mentioned in above attributes].
• displayCommercialFare [For user identification]
• displayDomesticFares [For user identification]
• generateBill [For calculating the bill amount according to their connection type]
• displayBill [For display the bill details to user]
• main [Default and Primary need]
Algorithm
1. Start the Process.
2. Create an Object for class Main.
3. Using Main class object get the user informations using getDatils method and read
the information using scanner object.
4. Call displayBill method
i. Call generateBill.
a. Calculate number of units consumed by current month reading -
previous month reading.
b. If current user is domestic
a. Compute with domestic scale using loop and find the sum
c. Else
a. Compute with commercial scale using loop and find the sum
d. Store final sum as totalBillAmmount
ii. Display user's details [Consumer Number, Name, Number of units
consumed].
iii. Display bill amount.
iv. Display Fare details.
a. If user is domestic display domestic scale.
b. Else display commercial scale.
5. Stop the process
Code
import java.util.Scanner;
class EBConsumer {
int consumer_number;
String consumer_name;
int previous_month_reading;
int current_month_reading;
int units_consumed;
boolean isDomestic = false;
double bill_ammount;
public void displayDomesticFares(){
System.out.println("Domestic Fare Details");
System.out.println("*********************");
System.out.println("First 100 units - Rs. 1 per unit");
System.out.println("101-200 units - Rs. 2.50 per unit");
System.out.println("201 -500 units - Rs. 4 per unit");
System.out.println("> 501 units - Rs. 6 per unit");
}
public void displayCommercialFare() {
System.out.println("Commercial Fare Details");
System.out.println("***********************");
System.out.println("First 100 units - Rs. 2 per unit");
System.out.println("101-200 units - Rs. 4.50 per unit");
System.out.println("201 -500 units - Rs. 6 per unit");
System.out.println("> 501 units - Rs. 7 per unit");
}
public void getDetails() {
Scanner inputs = new Scanner(System.in);
System.out.println("Welcome To EB Calculater\n\n");
System.out.println("Please Enter Your Name : ");
this.consumer_name = inputs.next();
System.out.println("Please Enter Your Consumer Number : ");
this.consumer_number = inputs.nextInt();
System.out.println("Please Enter Your Previous Month Reading : ");
this.previous_month_reading = inputs.nextInt();
System.out.println("Please Enter Your Current Month Reading : ");
this.current_month_reading = inputs.nextInt();
System.out.println("Is this domestic Connection (yes/no) : ");
if(inputs.next().equals("yes"))
this.isDomestic = true;
}
public void generateBill(){
int number_of_units_consumed = this.current_month_reading -
this.previous_month_reading;
this.units_consumed = number_of_units_consumed;
double sum = 0;
if(isDomestic == true) {
for (int i = 0; i <= number_of_units_consumed; i++) {
if (i <= 100)
sum = sum + 1;
else if (i > 100 && i <= 200)
sum = sum + 2.5;
else if (i > 200 && i <= 500)
sum = sum + 4;
else
sum = sum + 6;
}
}
else {
for (int i = 0; i <= number_of_units_consumed; i++) {
if (i <= 100)
sum = sum + 2;
else if (i > 100 && i <= 200)
sum = sum + 4.5;
else if (i > 200 && i <= 500)
sum = sum + 6;
else
sum = sum + 7;
}
}
this.bill_ammount = sum;
}
public void displayBill() {
generateBill();
System.out.println("The EB Bill Details");
System.out.println("*******************");
System.out.println("Consumer Number : "+this.consumer_number);
System.out.println("Consumer Name : "+this.consumer_name);
System.out.println("Consumer Units Consumed:"+this.units_consumed);
if(this.isDomestic == true){
System.out.println("Your are an Domestic Consumer\n\nFare Details ...");
displayDomesticFares();
}
else{
System.out.println("You are a Commercial Consumer\n\nFare Details ...");
displayCommercialFare();
}
System.out.println("\nAmount Payable is \u20B9: "+this.bill_ammount);
}
}
public class EBBill {
Result:
The Java console application for electricity bill generator was developed and tested
successfully.
Ex. No 2
UNIT CONVERTER APPLICATION
DATE:
Develop a java application to implement currency converter (Dollar to INR, EURO to INR,
Yen to INR and vice versa), distance converter (meter to KM, miles to KM and vice versa) ,
time converter (hours to minutes, seconds and vice versa) using packages.
Aim:
To create a Java console application that converts currency, distance, time. Converter
classes must be separated and used based on the package concept in java.
Algorithm
Code: Convert.java
import java.util.Scanner;
import converter.Currency;
import converter.Distance;
import converter.Time;
while(choice != 4){
System.out.println("Converters");
System.out.println("**********");
System.out.println("1. Currentcy\n2. Distance\n3. Time\n4. Exit\n\nEnter Your
Choice");
choice = input.nextInt();
switch(choice){
case 1:
Currency.userChoice();
break;
case 2:
Distance.userChoice();
break;
case 3:
Time.userChoice();
break;
case 4:
break;
default:
System.out.println("Please choose valid option");
break;
}
}
System.out.println("Thank You !!!!");
}
}
Currency.java
package converter;
import java.util.Scanner;
public class Currency {
public static double covertEUROtoINR(double EURO) {
return EURO * 80;
}
public static double convertDOLLARtoINR(double DOLLAR) {
return DOLLAR * 66.89;
}
public static double convertYENtoINR(double YEN) {
return YEN * 0.61;
}
public static double covertINRtoEURO(double INR) {
return INR * 0.013;
}
public static double convertINRtoDOLLAR(double DOLLAR) {
return DOLLAR * 0.015;
}
public static double convertINRtoYEN(double YEN) {
return YEN * 1.63;
}
public static void userChoice(){
Scanner input = new Scanner(System.in);
int currency_choice = 0;
double money = 0;
while(currency_choice != 7){
System.out.println("\nCurrency Converter");
System.out.println("------------------");
System.out.println("1. DOLLOR to INR\n2. EURO to INR\n3. YEN to INR\n"
+ "4. INR to DOLLOR\n5. INR to EURO\n6. INR to
YEN\n"
+ "7.Exit\n\nEnter Your Choice");
currency_choice = input.nextInt();
switch(currency_choice){
case 1:
System.out.println("Enter in DOLLER");
money = input.nextDouble();
System.out.println(money+" DOLLER is equal to
"+Currency.convertDOLLARtoINR(money)+" INR");
break;
case 2:
System.out.println("Enter in EURO");
money = input.nextDouble();
System.out.println(money+" EURO is equal to
"+Currency.covertEUROtoINR(money)+" INR");
break;
case 3:
System.out.println("Enter in YEN");
money = input.nextDouble();
System.out.println(money+" YEN is equal to
"+Currency.convertYENtoINR(money)+" INR");
break;
case 4:
System.out.println("Enter in INR");
money = input.nextDouble();
System.out.println(money+" INR is equal to
"+Currency.convertINRtoDOLLAR(money)+" DOLLORS");
break;
case 5:
System.out.println("Enter in INR");
money = input.nextDouble();
System.out.println(money+" INR is equal to
"+Currency.covertINRtoEURO(money)+" EURO");
break;
case 6:
System.out.println("Enter in INR");
money = input.nextDouble();
System.out.println(money+" INR is equal to
"+Currency.convertINRtoYEN(money)+" YEN");
break;
case 7:
break;
default:
System.out.println("Please choose valid option");
break;
}
}
}
}
Distance.java
package converters;
import java.util.Scanner;
public class Distance {
public static double convertMeterToKiloMeter(double meter) {
return meter / 1000;
}
public static double convertMilesToKiloMeter(double miles) {
return miles * 1.60934;
}
public static double convertKiloMetertoMeter(double kilometer) {
return kilometer * 1000;
}
public static double convertKiloMeterToMiles(double kilometer) {
return kilometer / 1.60934;
}
Output – Distance
Result
The java console application for converters [Currency, Distance, Time] was
developed and tested successfully.
Ex. No 3
EMPLOYEE PAYROLL MANAGEMENT
DATE:
Develop a java application with Employee class with Emp_name, Emp_id, Address, Mail_id,
Mobile no as members. Inherit the classes, Programmer, Assistant Professor, Associate
Professor and Professor from employee class. Add Basic Pay (BP) as the member of all the
inherited classes with 97% of BP as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1% of BP for
staff club fund. Generate pay slips for the employees with their gross and net salary.
Algorithm:
Code
Payroll.java
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
class EmployeeDetail {
String emp_name;
String emp_id;
String emp_address;
String emp_mail_id;
String emp_mobile_no;
int basic_pay;
int per_day_pay;
int current_basic_pay;
int da, hra, pf, gross_pay;
int net_pay;
int no_of_days_in_current_month;
int no_of_days_worked;
Calendar cal;
Scanner input;
EmployeeDetail() {
input = new Scanner(System.in);
cal = new GregorianCalendar();
no_of_days_in_current_month =
cal.getActualMaximum(Calendar.DAY_OF_MONTH);
getUserBasicDetails();
}
public Programmer() {
super();
computeProgrammerPay();
}
}
class AssistantProfessor extends EmployeeDetail {
public AssistantProfessor() {
super();
computeAssistantProfessorPay();
}
computeCurrentBasicPay("AssociateProfessor");
generatePaySlip();
displayPaySlip();
}
}
public class Payroll {
while (n_choice != 5) {
System.out.println("\n\nEmployee Payroll System");
System.out.println("***********************\n");
System.out.println("1. Programmer\n2. Assistant Professor\n" + "3.
Associate Professor\n4. Professor\n"
+ "5. Exit\n\nEnter Your Choice");
choice = new BufferedReader(new
InputStreamReader(System.in)).readLine();
n_choice = Integer.parseInt(choice);
switch (n_choice) {
case 1:
System.out.println("Programmer Selected");
aProgrammer = new Programmer();
break;
case 2:
System.out.println("AssistantProfessor Selected");
aAssistantProfessor = new AssistantProfessor();
break;
case 3:
System.out.println("AssociateProfessor Selected");
aAssociateProfessor = new AssociateProfessor();
break;
case 4:
System.out.println("Professor Selected");
aProfessor = new Professor();
case 5:
System.out.println("Thank You !!!");
userInput.close();
break;
default:
System.out.println("Enter valid choice !!!");
break;
}
}
}
}
Output
Result:
The java console application for employee payroll system was developed and
tested successfully.
Ex. No 4
STACK ADT using JAVA –Interface and Exception Handling
DATE:
Design a Java interface for ADT Stack. Implement this interface using array. Provide
necessary exception handling in both the implementations.
Aim:
To create a Java console application using interface concepts of java for abstract data type
stack. Stack operations must be controlled by exception handling techniques.
Algorithm:
import java.util.Scanner;
interface StackOperations {
boolean push(int number); boolean pop();
void peek();
void display();
}
public class Stack {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of stack :");
CustomStack mystack = new CustomStack(input.nextInt());
int choice = 0;
while (choice != 5) {
System.out.println("\n1.PUSH\n2.POP\n3.PEEK\n4.DISPLAY\n5.EXIT");
System.out.println("Please Enter Your Choice : ");
choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("Enter the Element to PUSH : ");
mystack.push(input.nextInt());
break;
case 2:
mystack.pop();
break;
case 3:
mystack.peek();
break;
case 4:
mystack.display();
break;
case 5:
System.out.println("!!! Thank You !!!");
break;
}
}
input.close();
System.exit(0);
}
}
class CustomStack implements StackOperations {
int[] stack_array;
int limit;
int current_position = 0;
Output
Result:
The java console application for abstract data type stack using java interface
concepts is developed and tested successfully.
Ex. No 5
String Operations using ArrayList
DATE:
Write a program to perform string operations using ArrayList.
Write functions for the following
a. Append - add at end b. Insert – add at particular index c. Search d. List all
string starts with given letter
Aim:
To create a Java console application for string list operations [Append, Insert at particular
Index, Search a string in a list, Display all the strings that begins with a character] using
ArrayList in java.
Algorithm:
public StringList() {
listOfStrings = new ArrayList<String>();
}
public boolean addString(String aString) {
boolean result = listOfStrings.add(aString);
return result;
}
public void insertStringAt(int position, String aString) {
int list_size = listOfStrings.size();
int cur_pos = 0;
ArrayList<String> templist = new ArrayList<String>();
if (position > list_size)
System.out.println("Sorry Position is not in the list limit");
else {
for (String elememt : listOfStrings) {
if (cur_pos == position)
templist.add(aString);
templist.add(elememt);
cur_pos++;
}
}
listOfStrings = templist;
}
public void displayList() {
int i = 0;
for (String element : listOfStrings) {
System.out.println(i + "." + element);
i++;
}
}
public void searchString(String aString) {
int cur_pos = 0;
int foundAt = -1;
for (String element : listOfStrings) {
if (element.equalsIgnoreCase(aString)) {
foundAt = cur_pos;
break;
} else
cur_pos++;
}
if (foundAt >= 0)
System.out.println("Your string " + aString + " found at position " +
cur_pos);
else
System.out.println("String not found in the list");
}
Output
Result:
The java console application for string list operations was developed and tested
successfully.
Ex. No 6
Programs using JAVA Abstract Class
DATE:
Write a Java Program to create an abstract class named Shape that contains two integers
and an empty method named print Area(). Provide three classes named Rectangle, Triangle
and Circle such that each one of the classes extends the class Shape. Each one of the classes
contains only the method print Area () that prints the area of the given shape.
Aim:
To create a Java console application to find the area of different shapes using
abstract class concept in java.
Algorithm:
}
Output
Result:
The Java console application to find the area of different shapes using abstract
class concept in java was developed and tested successfully.
Ex. No 7
User Defined Exception Handling in JAVA- Banking Application
DATE:
Write a Java program to implement user defined exception handling.
Aim:
To create a Java console application for banking transaction system that helps the
users to do their credit and debit transactions and it raises user defined exception while
encountering errors in transaction and also it should be solved using exception handling
techniques.
Algorithm:
Step 1 Start the Process
Step 2 Prompt user with List Operation Choices
1. Add Money 2. Get Money
3. Details 4. Exit
Get the choice from user.
Step 3 If user selects Add Money
Step 3.1 Get the amount to be added to balance from the user
Step 3.2 If the amount is less than 0 then throw Invalid Credit Exception
and goto step 3.4
Step 3.3 Else add amount to balance and goto step 2
Step 3.4 Prompt user with “Enter valid credit amount” and goto step 3.1
Step 4 If user selects Get Money
Step 4.1 Get the amount to be debited to balance from the user
Step 4.2 If the amount is greater than existing balance then throw
Invalid Debit Exception and goto step 4.4
Step 4.3 Else deduct amount from balance and goto step 2
Step 4.4 Prompt user with “Enter valid debit amount” and goto step 4.1
Step 5 If user selects Details then display Customer Details [Name, Account
Number, Current Balance]
Step 6 If user wants to exit display “Thank You !!!” and end process
Step 7 Stop the Process
Code
import java.util.Scanner;
class InvalidDebit extends Exception {
public InvalidDebit() {
System.out.print("Please enter valid debit amount");
}
}
class InvalidCredit extends Exception {
public InvalidCredit() {
System.out.print("Please enter valid credit amount");
}
}
class CustomerEx {
String name;
int accNo;
int balance;
public CustomerEx(String name, int accNo) {
this.name = name;
this.accNo = accNo;
this.balance = 0;
}
public void creditTransaction(int amount) {
Scanner input = new Scanner(System.in);
try {
if (amount < 0)
throw new InvalidCredit();
else
balance = balance + amount;
} catch (InvalidCredit e) {
amount = input.nextInt();
creditTransaction(amount);
}
}
public void debitTransaction(int amount) {
Scanner input = new Scanner(System.in);
try {
if (amount > balance)
throw new InvalidDebit();
else
balance = balance - amount;
} catch (InvalidDebit e) {
amount = input.nextInt();
debitTransaction(amount);
}
}
public void displayDetails() {
System.out.println("Customer Details");
System.out.println("****************");
System.out.println("Customer Name : " + this.name);
System.out.println("Customer AccNo : " + this.accNo);
System.out.println("Customer Current Balance : " + this.balance);
}
}
public class User_Defined_Exception {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String name;
int acc_no;
System.out.println("Enter Customer Name");
name = input.next();
System.out.println("Enter account number");
acc_no = input.nextInt();
CustomerEx aCustomer = new CustomerEx(name, acc_no);
int choice = 0;
while (choice != 4) {
System.out.println("\n1. Add Money\n2. Get Money\n3. Details\n4.
Exit");
choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("Enter the amount");
aCustomer.creditTransaction(input.nextInt());
break;
case 2:
System.out.println("Enter the amount");
aCustomer.debitTransaction(input.nextInt());
break;
case 3:
aCustomer.displayDetails();
break;
case 4:
System.out.println("Thank You !!!");
break;
}
}
}
}
import java.util.Scanner;
class InvalidDebit extends Exception {
public InvalidDebit() {
System.out.print("Please enter valid debit amount");
}
}
class InvalidCredit extends Exception {
public InvalidCredit() {
System.out.print("Please enter valid credit amount");
}
}
class CustomerEx {
String name;
int accNo;
int balance;
public CustomerEx(String name, int accNo) {
this.name = name;
this.accNo = accNo;
this.balance = 0;
}
public void creditTransaction(int amount) {
Scanner input = new Scanner(System.in);
try {
if (amount < 0)
throw new InvalidCredit();
else
balance = balance + amount;
} catch (InvalidCredit e) {
amount = input.nextInt();
creditTransaction(amount);
}
}
public void debitTransaction(int amount) {
Scanner input = new Scanner(System.in);
try {
if (amount > balance)
throw new InvalidDebit();
else
balance = balance - amount;
} catch (InvalidDebit e) {
amount = input.nextInt();
debitTransaction(amount);
}
}
public void displayDetails() {
System.out.println("Customer Details");
System.out.println("****************");
System.out.println("Customer Name : " + this.name);
System.out.println("Customer AccNo : " + this.accNo);
System.out.println("Customer Current Balance : " + this.balance);
}
}
public class User_Defined_Exception {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String name;
int acc_no;
System.out.println("Enter Customer Name");
name = input.next();
System.out.println("Enter account number");
acc_no = input.nextInt();
CustomerEx aCustomer = new CustomerEx(name, acc_no);
int choice = 0;
while (choice != 4) {
System.out.println("\n1. Add Money\n2. Get Money\n3. Details\n4.
Exit");
choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("Enter the amount");
aCustomer.creditTransaction(input.nextInt());
break;
case 2:
System.out.println("Enter the amount");
aCustomer.debitTransaction(input.nextInt());
break;
case 3:
aCustomer.displayDetails();
break;
case 4:
System.out.println("Thank You !!!");
break;
}
}
}
}
import java.util.Scanner;
class InvalidDebit extends Exception {
public InvalidDebit() {
System.out.print("Please enter valid debit amount");
}
}
class InvalidCredit extends Exception {
public InvalidCredit() {
System.out.print("Please enter valid credit amount");
}
}
class CustomerEx {
String name;
int accNo;
int balance;
public CustomerEx(String name, int accNo) {
this.name = name;
this.accNo = accNo;
this.balance = 0;
}
public void creditTransaction(int amount) {
Scanner input = new Scanner(System.in);
try {
if (amount < 0)
throw new InvalidCredit();
else
balance = balance + amount;
} catch (InvalidCredit e) {
amount = input.nextInt();
creditTransaction(amount);
}
}
public void debitTransaction(int amount) {
Scanner input = new Scanner(System.in);
try {
if (amount > balance)
throw new InvalidDebit();
else
balance = balance - amount;
} catch (InvalidDebit e) {
amount = input.nextInt();
debitTransaction(amount);
}
}
public void displayDetails() {
System.out.println("Customer Details");
System.out.println("****************");
System.out.println("Customer Name : " + this.name);
System.out.println("Customer AccNo : " + this.accNo);
System.out.println("Customer Current Balance : " + this.balance);
}
}
public class User_Defined_Exception {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String name;
int acc_no;
System.out.println("Enter Customer Name");
name = input.next();
System.out.println("Enter account number");
acc_no = input.nextInt();
CustomerEx aCustomer = new CustomerEx(name, acc_no);
int choice = 0;
while (choice != 4) {
System.out.println("\n1. Add Money\n2. Get Money\n3. Details\n4.
Exit");
choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("Enter the amount");
aCustomer.creditTransaction(input.nextInt());
break;
case 2:
System.out.println("Enter the amount");
aCustomer.debitTransaction(input.nextInt());
break;
case 3:
aCustomer.displayDetails();
break;
case 4:
System.out.println("Thank You !!!");
break;
}
}
}
}
Output
Result:
The java console application that uses user defined exception handling techniques was
developed and tested successfully.
Ex. No 8
File Operations in JAVA
DATE:
Write a Java program that reads a file name from the user, displays information about
whether the file exists, whether the file is readable, or writable, the type of file and the
length of the file in bytes.
Aim:
To create a Java console application to handle the files and find the file properties
[Availability, Readable or Writeable or Both, Length of the File].
Algorithm:
Code
import java.io.File;
import java.io.File;
import java.util.Scanner;
class UserFileHandler {
File aFile;
boolean isReadable = false;
boolean isWriteable = false;
boolean isExists = false;
int length = 0;
public UserFileHandler(String path) {
aFile = new File(path);
this.isExists = aFile.exists();
this.isReadable = aFile.canRead();
this.isWriteable = aFile.canWrite();
this.length = (int) aFile.length();
}
Output
Result:
The java console application for handling files was developed and tested successfully.
Ex. No 9
Multithreading Application in JAVA
DATE:
Write a java program that implements a multi-threaded application that has three threads.
First thread generates a random integer every 1 second and if the value is even, second
thread computes the square of the number and prints. If the value is odd, the third thread
will print the value of cube of the number.
Aim:
To create a Java console application the uses the multi threading concepts in java. The
application has 3 threads one creates random number, one thread computes square of that
number and another one computes the cube of that number.
Algorithm:
Code
import java.util.Random;
class RandomNumberThread extends Thread {
Random num = new Random();
int value;
@Override
public void run() {
while (true) {
try {
this.sleep(1000);
} catch (InterruptedException e) {
}
value = num.nextInt(1000);
System.out.println("RandomNumberThread generated a number " +
value);
if (value % 2 == 0)
new SquareGenThread(value).start();
else
new CubeGenThread(value).start();
}
}
}
@Override
public void run() {
try {
this.sleep(3000);
} catch (InterruptedException e) {
}
this.squre = this.number * this.number;
System.out.println("SquareGenThread--> Square of " + number + " is " +
squre);
}
}
@Override
public void run() {
try {
this.sleep(2000);
} catch (InterruptedException e) {
}
this.squre = this.number * this.number * this.number;
System.out.println("CubeGenThread--> Square of " + number + " is " + squre);
}
}
public class MultiThreadingDemo {
public static void main(String[] args) {
new RandomNumberThread().start();
}
Output
Result:
The java console application for multithreading was developed and tested successfully.
Ex. No 10
Generic Programming and Generic Classes in JAVA
DATE:
Write a java program to find the maximum value from the given type of elements using a
generic function.
Aim:
To create a Java console application that finds the maximum in a array based on the type of
the elements using generic functions in java.
Algorithm:
Code
class GenericMax {
public <T extends Comparable<T>> void maxFinder(T[] array) {
T max = array[0];
for (T element : array) {
System.out.println(element);
if (element.compareTo(max) > 0)
max = element;
}
System.out.println("Max is : " + max);
}
}
public class Generic_Demo {
public static void main(String[] args) {
GenericMax max = new GenericMax();
Integer[] numbers = { 14, 3, 42, 5, 6, 10 };
String[] strings = { "Shanmugha", "Priya", "VEC-CSE" };
max.maxFinder(numbers);
max.maxFinder(strings);
}
Output
Result:
The java console application for finding generic max of given elements was
developed and tested successfully.
Ex. No 11
Scientific Calculator using Event Driven Programming in JAVA
DATE:
Design a calculator using event-driven programming paradigm of Java with the following
options. a) Decimal manipulations b) Scientific manipulations
Aim:
To create a Java GUI application that mimics the basic and advanced functionalities of a
scientific calculator.
Algorithm:
@Override
public void actionPerformed(ActionEvent e) {
data = getDisplayText();
switch (e.getActionCommand()) {
case "zero":
setDisplay(data + "0");
break;
case "one":
setDisplay(data + "1");
break;
case "two":
setDisplay(data + "2");
break;
case "three":
setDisplay(data + "3");
break;
case "four":
setDisplay(data + "4");
break;
case "five":
setDisplay(data + "5");
break;
case "six":
setDisplay(data + "6");
break;
case "seven":
setDisplay(data + "7");
break;
case "eight":
setDisplay(data + "8");
break;
case "nine":
setDisplay(data + "9");
break;
case "plus":
op1 = data;
op_flag = "plus";
clearDisplay();
break;
case "minus":
op1 = data;
op_flag = "minus";
clearDisplay();
break;
case "multiply":
op1 = data;
op_flag = "multiply";
clearDisplay();
break;
case "divide":
op1 = data;
op_flag = "divide";
clearDisplay();
break;
case "clear":
clearDisplay();
break;
case "advanced":
if (flag_advanced) {
changeAdvanced(true);
flag_advanced = false;
} else {
changeAdvanced(false);
flag_advanced = true;
}
break;
case "sin":
op1 = data;
setDisplay(String.valueOf(Math.sin(Double.valueOf(op1))));
break;
case "cos":
op1 = data;
setDisplay(String.valueOf(Math.cos(Double.valueOf(op1))));
break;
case "tan":
op1 = data;
setDisplay(String.valueOf(Math.tan(Double.valueOf(op1))));
break;
case "log":
op1 = data;
setDisplay(String.valueOf(Math.log(Double.valueOf(op1))));
break;
case "equal":
switch (op_flag) {
case "plus":
op2 = data;
clearDisplay();
dop1 = Double.parseDouble(op1);
dop2 = Double.parseDouble(op2);
dresult = dop1 + dop2;
result = String.valueOf(dresult);
setDisplay(result);
op_flag = "";
break;
case "minus":
op2 = data;
clearDisplay();
dop1 = Double.parseDouble(op1);
dop2 = Double.parseDouble(op2);
dresult = dop1 - dop2;
result = String.valueOf(dresult);
setDisplay(result);
op_flag = "";
break;
case "multiply":
op2 = data;
clearDisplay();
dop1 = Double.parseDouble(op1);
dop2 = Double.parseDouble(op2);
dresult = dop1 * dop2;
result = String.valueOf(dresult);
setDisplay(result);
op_flag = "";
break;
case "divide":
op2 = data;
clearDisplay();
dop1 = Double.parseDouble(op1);
dop2 = Double.parseDouble(op2);
dresult = dop1 / dop2;
result = String.valueOf(dresult);
setDisplay(result);
op_flag = "";
break;
}
}
}
}
public Calculator() {
display = new TextField();
display.setFont(new Font("Times New Roman", Font.BOLD, 50));
setLayout(new BorderLayout());
add(new Numpan(display), BorderLayout.CENTER);
add(display, BorderLayout.NORTH);
setVisible(true);
setSize(500, 500);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
}
Output
ADDITION
DIVISION
On Clicking ADV – We Will Get all the Scientific Operations - Highlighted
SINE
Result:
The java GUI application for calculator with basic and advanced functionalities was
developed and tested successfully.
Ex. No 12
JDBC Connectivity
DATE:
Aim:
To create a Java application with JDBC connectivity
ALGORITHM:
1. Import the packages containing the JDBC classes needed for database programming. Most
often, using import java.sql.* will suffice.
2. Then register the JDBC driver to open a communication channel with the database.
3. To open a connection use the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with the database.
4. Then execute a query by building and submitting an SQL statement to the database.
5. Extract data from result set by using the appropriate ResultSet.getXXX() method to retrieve
the data from the result set.
6. Clean up the environment explicitly for closing all database resources versus relying on the
JVM's garbage collection.
Program:-
ConnectionUtil.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionUtil
{
public static Connection getConnection() throws SQLException
{
Connection connection = null;
try
{
Class.forName("com.mysql.jdbc.Connection");
connection = DriverManager.getConnection("jdbc:mysql://192.168.216.250:3306/vijju","root",
"root");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
e.printStackTrace();
}
System.out.println("message for connection open"+connection);
return connection;
}
}
StudentDetails.java
public class StudentDetails
{
private long st_id;
private String st_name;
private long st_mobile;
public StudentDetails(long st_id,String st_name,long st_mobile)
{
this.st_id = st_id;
this.st_name = st_name;
this.st_mobile = st_mobile;
}
public long getSt_id()
{
return st_id;
}
public void setSt_id(long st_id)
{
this.st_id = st_id;
}
public String getSt_name()
{
return st_name;
}
public void setSt_name(String st_name)
{
this.st_name = st_name;
}
public long getSt_mobile()
{
return st_mobile;
}
public void setSt_mobile(long st_mobile)
{
this.st_mobile = st_mobile;
}
}
Prog6.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Prog6
{
String createTableQuery = "create table test.student_details (st_namevarchar(50), st_mobile
numeric(10), st_id numeric(10))";
public static void main(String[] args)
{ Connection conn = null;
try
{
conn = ConnectionUtil.getConnection();
Prog6 prog6 = new Prog6();
System.out.println("Student_details table data before inserting:");
prog6.retrieveData(conn);
StudentDetails st1 = new StudentDetails(1, "GNIT", 23232323);
StudentDetails st2 = new StudentDetails(2, "GNEC", 24242424);
StudentDetails st3 = new StudentDetails(3, "GNITC", 25252525);
prog6.insertData(conn, st1);
prog6.insertData(conn, st2);
prog6.insertData(conn, st3);
System.out.println("Student_details table data after inserting:");
prog6.retrieveData(conn);
prog6.deleteARow(conn,2);
System.out.println("Student_details table data after deleting:");
prog6.retrieveData(conn);
prog6.modifyData(conn, 26262626, 3);
System.out.println("Student_details table data after modifying:");
prog6.retrieveData(conn);
} catch (SQLException e)
{
e.printStackTrace();
} finally
{
try {
conn.close();
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
private void modifyData(Connection conn, long st_mobile, long st_id)
{
String query = "update student_details set st_mobile=? wherest_id=?";
try {
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setLong(1, st_mobile);
pstmt.setLong(2, st_id);
int row = pstmt.executeUpdate();
//System.out.println(row);
} catch (SQLException e)
{ e.printStackTrace();
}
}
private void deleteARow(Connection conn, long st_id)
{
String query = "delete from student_details where st_id=?" ;
try
{
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setLong(1, st_id);
int row = pstmt.executeUpdate();
//System.out.println(row);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
private void insertData(Connection conn, StudentDetails details)
{
String query = "insert into test.student_details values (?,?,?)";
try
{
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1,details.getSt_name());
pstmt.setLong(2, details.getSt_mobile());
pstmt.setLong(3, details.getSt_id());
int row = pstmt.executeUpdate();
//System.out.println(row);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
private void retrieveData(Connection conn)
{
try {
String query = "select * from test.student_details";
PreparedStatement pstmt = conn.prepareStatement(query);
ResultSet rs = pstmt.executeQuery();
System.out.println("ST_ID\tST_NAME\t\tST_MOBILE");
while(rs.next())
{
System.out.println(rs.getString("st_id")+"\t"+rs.getString("st_name")+"\t\t"+rs.getString(
"st_mobile"));
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
Result:
The java application with JDBC Connectivity was developed and tested successfully.