[go: up one dir, main page]

0% found this document useful (0 votes)
22 views29 pages

Se2 Group4 11

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 29

THE UNIVERSITY OF DODOMA

COLLEGE OF INFORMATICS AND VIRTUAL EDUCATION


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING (CSE)
COURSE: OBJECT ORIENTED PROGRAMMING IN JAVA
COURSE CODE: CP 215
GROUP ASSIGNMENT

REGISTRATION SIGNATURE SCORE


STUDENT NAME
NUMBER

EMMANUEL G. CHUWA T22-03-10711

MICHAEL A. MVUMA T22-03-02451

AUGUSTINO MWALYEGO T22-03-07043

BRIAN PHILIPO T22-03-08257

SULEIMAN A. MACHANO T22-03-04440

FRANCIS R. KOBELO T22-03-08176

AGNES MKWAMA T22-03-10714

WALTER G. MTUI T22-03-08661

HAFIDHI A. MKORI T22-03-04660

EMMANUEL MAHONA T22-03-09888

REBECA SAMANDA T21-03-04721


Order of Attempted Questions:

• Lab Practical 4
• Lab Practical 5
• Lab Practical 6
• Lab Practical 8 (Exception Handling)
• JDBC Activity

LAB PRACTICAL 4:

1. Write a java class containing main method and another method called display. The method
display shall be called within main method to output Hello CP 215 Class to the screen. Method
display should not have parameters or return type.

public class MyClass {


public static void main(String[] args) {
display();
}
public static void display() {
System.out.println("Hello CP 215 Class");
}}

2. Write java class containing main method and other two methods called addition and
myMethod. Method addition should display the sum of two integers passed through its
parameters a and b. myMethod should display title “Adding two Integers:” which is passed
through its string parameter called title. All the methods should be called within main method.
Note: Arguments should be hardcoded or embedded with the code.

public class MyClass {


public static void main(String[] args) {
addition(1, 2);
myMethod("Adding two Integers:");
}
public static void addition(int a, int b) {
System.out.println("The sum of " + a + " and " + b + " is " + (a + b));
}
public static void myMethod(String title) {
System.out.println(title);
}}

3. Modify question 2 to allow a user to pass arguments to the methods using Scanner class.

import java.util.Scanner; public


class MyClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first integer: ");
int a = sc.nextInt();
System.out.print("Enter the second integer: ");
int b = sc.nextInt();
addition(a, b);
System.out.print("Enter the title: ");
String title = sc.next();
myMethod(title);
}
public static void addition(int a, int b) {
System.out.println("The sum of " + a + " and " + b + " is " + (a + b));
}
public static void myMethod(String title) {
System.out.println(title);
}}

4. Write a java class containing three methods; main, display, and addition methods. Method display
should be responsible for outputting results to the screen. Method addition should add two
integers passed through its parameters a and b and return the sum to method display. Method
display should be called by the main method.

import java.util.Scanner; public


class MyClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first integer: ");
int a = sc.nextInt();
System.out.print("Enter the second integer: ");
int b = sc.nextInt();
display(addition(a, b));
}
public static int addition(int a, int b) {
return a + b;}
public static void display(int sum) {
System.out.println("The sum of the two integers is " + sum);
}}

5. Write a java class that contains two methods; main and addition. Method addition should be
overloaded to perform addition of two integers, addition of two double, addition of three
integers and concatenation of two strings. Results should be displayed in main method. All
values should be supplied by user via keyboard.

import java.util.Scanner; public


class MyClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first integer: ");
int a = sc.nextInt();
System.out.print("Enter the second integer: ");
int b = sc.nextInt();
System.out.println("The sum of the two integers is " + addition(a, b));
System.out.print("Enter the first double: "); double c =
sc.nextDouble();
System.out.print("Enter the second double: ");
double d = sc.nextDouble();
System.out.println("The sum of the two doubles is " +
addition(c, d)); System.out.print("Enter the first integer: ");
int e = sc.nextInt();
System.out.print("Enter the second integer: ");
int f = sc.nextInt();
System.out.print("Enter the third integer: ");
int g = sc.nextInt();
System.out.println("The sum of the three integers is " + addition(e, f, g));
System.out.print("Enter the first string: ");
String h = sc.next();
System.out.print("Enter the second string: ");
String i = sc.next();
System.out.println("The concatenation of the two strings is " + addition(h, i));
}
public static int addition(int a, int b) {return a + b;}

public static double addition(double a, double b) {return a + b;}

public static int addition(int a, int b, int c) {return a + b + c;}

public static String addition(String a, String b) {return a + b;}

6. Create a class called Student with four instance variables; name, regNumber, yearOfStudy, and
gender. Create set and get methods for inserting and returning values from the instance
variables respectively. Values to the variable should be hardcoded through the parentheses of
the method during the call.

public class Student {


private String name;
private String regNumber;
private int yearOfStudy;
private String gender;
public void setName(String name) {this.name = name;}
public String getName() {return name;}
public void setRegNumber(String regNumber) {this.regNumber = regNumber;}
public String getRegNumber() {return regNumber;}
public void setYearOfStudy(int yearOfStudy) {this.yearOfStudy = yearOfStudy;}
public int getYearOfStudy() {return yearOfStudy;} public void setGender(String
gender) {this.gender = gender;} public String getGender() {return gender;}}

7. Modify question number 6 by separating it into two classes; Class Student and class myMain.
Class student should have four instance variables; name, regNumber, yearOfStudy, and gender.
While class myMain should be used to define main method, create object of class student and
display values. Values to the variable should be supplied by the user and passed through the
parentheses of the class’s object.
import java.util.Scanner; public
class myMain {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Student student = new Student();
System.out.print("Enter the name: ");
student.setName(sc.nextLine());
System.out.print("Enter the registration number: ");
student.setRegNumber(sc.nextLine()); System.out.print("Enter
the year of study: "); student.setYearOfStudy(sc.nextInt());
sc.nextLine();
System.out.print("Enter the gender: ");
student.setGender(sc.nextLine());
System.out.println("Name: " + student.getName());
System.out.println("Registration Number: " + student.getRegNumber());
System.out.println("Year of Study: " + student.getYearOfStudy());
System.out.println("Gender: " + student.getGender()); sc.close();}}

8. Write java program(s) that illustrate declaration and usage of local variables, instance variables,
instance methods, class variables and class methods. Use comments to locate local, instance,
and class variables and methods declared.

public class Example {


private static int classVariable = 0;
private int instanceVariable = 0; public
static void main(String[] args) {
int localVariable = 0;
Example example = new Example();
example.instanceMethod();
classMethod();}
public void instanceMethod() {
int localVariable = 0;
instanceVariable = 1;} public
static void classMethod() {
int localVariable = 0;
classVariable = 1;}}

9. Write java class that has one instance variable, a programmer defined constructor which
initializes that instance variable of the class and one method that accepts an integer value. Write
another java class that instantiates an object of the class that was created and calls the method
defined in the class. Use comments to indicate a parameter and an argument.

public class MyClass {


private int myVariable;
public MyClass(int value) {
myVariable = value;}
public void myMethod(int value) {
int myLocalVariable = value;
myVariable = myLocalVariable;}}
public class MyMain {
public static void main(String[] args) {
MyClass myObject = new MyClass(10);
myObject.myMethod(5);}}

10. (Employee Class) Create a class called Employee that includes three instance variables—a first
name (type String), a last name (type String) and a monthly salary (double). Provide a
constructor that initializes the three instance variables. Provide a set and a get method for each
instance variable. If the monthly salary is not positive, do not set its value. Write a test app
named EmployeeTest that demonstrates class Employee’s capabilities. Create two Employee
objects and display each object’s yearly salary. Then give each Employee a 10% raise and display
each Employee’s yearly salary again.

public class Employee {


private String firstName;
private String lastName;
private double monthlySalary;
public Employee(String firstName, String lastName, double monthlySalary) {
this.firstName = firstName; this.lastName = lastName; if
(monthlySalary > 0) {
this.monthlySalary = monthlySalary;}
public void setFirstName(String firstName) {this.firstName = firstName;}
public String getFirstName() {return firstName;}
public void setLastName(String lastName) {this.lastName = lastName;}
public String getLastName() {return lastName;} public void
setMonthlySalary(double monthlySalary) { if (monthlySalary > 0)
{this.monthlySalary = monthlySalary;}} public double
getMonthlySalary() {return monthlySalary;} public double
getYearlySalary() {return monthlySalary * 12;} public void
raiseSalary(double percentage) {
monthlySalary += monthlySalary * percentage / 100;}}

public class EmployeeTest {


public static void main(String[] args) {
Employee employee1 = new Employee("Lionel", "Messi", 30000);
Employee employee2 = new Employee("Cristiano", "Ronaldo", 90000);
System.out.printf("%s %s's yearly salary is %2f%n", employee1.getFirstName(),
employee1.getLastName(), employee1.getYearlySalary());
System.out.printf("%s %s's yearly salary is %2f%n", employee2.getFirstName(),
employee2.getLastName(), employee2.getYearlySalary());
employee1.raiseSalary(10);
employee2.raiseSalary(10);
System.out.printf("%s %s's yearly salary after a 10%% raise is %.2f%n",
employee1.getFirstName(), employee1.getLastName(), employee1.getYearlySalary());
System.out.printf("%s %s's yearly salary after a 10%% raise is %.2f%n",
employee2.getFirstName(), employee2.getLastName(), employee2.getYearlySalary());}}

11. (Invoice Class) Create a class called Invoice that a hardware store might use to represent an
invoice for an item sold at the store. An Invoice should include four pieces of information as
instance variables—a part number (type String), a part description (type String), a quantity of
the item being purchased (type int) and a price per item (double). Your class should have a
constructor that initializes the four instance variables. Provide a set and a get method for each
instance variable. In addition, provide a method named getInvoiceAmount that calculates the
invoice amount (i.e., multiplies the quantity by the price per item), then returns the amount as a
double value. If the quantity is not positive, it should be set to 0. If the price per item is not
positive, it should be set to 0.0. Write a test app named InvoiceTest that demonstrates class
Invoice’s capabilities.

public class Invoice {


private String partNumber;
private String partDescription;
private int quantity;
private double pricePerItem;
public Invoice(String partNumber, String partDescription, int quantity, double pricePerItem) {
this.partNumber = partNumber;
this.partDescription = partDescription;
if (quantity > 0) {
this.quantity = quantity;}
if (pricePerItem > 0.0) {
this.pricePerItem = pricePerItem;}}
public void setPartNumber(String partNumber) {
this.partNumber = partNumber;}
public String getPartNumber() {
return partNumber;}

public void setPartDescription(String partDescription) {


this.partDescription = partDescription;}
public String getPartDescription() {
return partDescription;}
public void setQuantity(int quantity) {
if (quantity > 0) {
this.quantity = quantity;}}
public int getQuantity() {
return quantity;}
public void setPricePerItem(double pricePerItem) {
if (pricePerItem > 0.0) {
this.pricePerItem = pricePerItem;}}
public double getPricePerItem() {
return pricePerItem;}
public double getInvoiceAmount() {
return quantity * pricePerItem;}}
public class InvoiceTest {
public static void main(String[] args) {
Invoice invoice1 = new Invoice("12345", "Maestro", 12, 6.0);
Invoice invoice2 = new Invoice("67890", "Chuwa", 10, 9.0);
System.out.printf("Invoice 1 amount: $%.2f%n", invoice1.getInvoiceAmount());
System.out.printf("Invoice 2 amount: $%.2f%n", invoice2.getInvoiceAmount());

invoice1.setQuantity(-1);
invoice2.setPricePerItem(-1.0);
System.out.printf("Invoice 1 amount after setting quantity to -1: $%.2f%n",
invoice1.getInvoiceAmount());
System.out.printf("Invoice 2 amount after setting price per item to -1.0: $%.2f%n",
invoice2.getInvoiceAmount());}}

LAB PRACTICAL 5:

1. Write a java app that contains a version of class Account that maintains an instance variables
name and balance of a bank account. A typical bank services many accounts, each with its own
balance. Every instance (i.e., object) of class Account contains its own copies of both the name
and the balance. Provide constructor to initialice instance variables. Provide method setName,
getName, deposite and getBalance to set name, get name, deposite money to balance and get
balance respectively. Then provide another class called AccountTest and create two objects to
test the Account class.

public class Account {


private String name;
private double balance;
public Account(String name, double balance) {
this.name = name;
this.balance = balance;}
public void setName(String name) {this.name = name;}
public String getName() {return name;}
public void deposit(double amount) {balance += amount;}
public double getBalance() {return balance;}}
public class AccountTest {
public static void main(String[] args) {
Account account1 = new Account("Rasmus", 100000.0);
Account account2 = new Account("Elanga", 200000.0);
System.out.printf("%s's balance is $%.2f%n", account1.getName(), account1.getBalance());
System.out.printf("%s's balance is $%.2f%n", account2.getName(), account2.getBalance());
account1.deposit(500.0);
account2.deposit(1000.0);
System.out.printf("%s's balance after depositing $500.0 is $%.2f%n", account1.getName(),
account1.getBalance());
System.out.printf("%s's balance after depositing $1000.0 is $%.2f%n", account2.getName(),
account2.getBalance());}}

2. Modify class Account (in question 1) to provide a method called withdraw that withdraws
money from an Account. Ensure that the withdrawal amount does not exceed the Account’s
balance. If it does, the balance should be left unchanged and the method should print a message
indicating "Withdrawal amount exceeded account balance." Modify class AccountTest to test
method withdraw.

public class Account {


private String name;
private double balance;
public Account(String name, double balance) {
this.name = name;
this.balance = balance;}
public void setName(String name) {this.name = name;}
public String getName() {return name;}
public void deposit(double amount) {balance += amount;}
public void withdraw(double amount) {
if (amount > balance) {
System.out.println("Withdrawal amount exceeded account balance.");
} else {
balance -= amount;}}
public double getBalance() {return balance;}}
public class AccountTest {
public static void main(String[] args) {
Account account1 = new Account("David", 1000.0);
Account account2 = new Account("Kendrick", 20000.0);
System.out.printf("%s's balance is $%.2f%n", account1.getName(), account1.getBalance());
System.out.printf("%s's balance is $%.2f%n", account2.getName(), account2.getBalance());
account1.withdraw(500.0);
account2.withdraw(3000.0);
System.out.printf("%s's balance after withdrawing $500.0 is $%.2f%n",
account1.getName(), account1.getBalance());
System.out.printf("%s's balance after withdrawing $3000.0 is $%.2f%n",
account2.getName(), account2.getBalance());}}

3. Write a java program that declares two classes—Employee and EmployeeTest. Class
Employee declares private static variable count and public static method getCount. The static
variable count maintains a count of the number of objects of class Employee that have been
created so far. This class variable has to be initialized to zero. If a static variable is not initialized,
the compiler assigns it a default value—in this case 0, the default value for type int.
EmployeeTest method main instantiates two Employee objects to test the Employee class.

public class Employee {


private static int count = 0;
public Employee() {count++;}
public static int getCount() {return count;}}
public class EmployeeTest {
public static void main(String[] args) {
Employee employee1 = new Employee();
Employee employee2 = new Employee();
System.out.printf("Number of employees created so far: %d%n", Employee.getCount());}}

4. Create a class Rectangle with attributes length and width, each of which defaults to 1. Provide
methods that calculate the rectangle’s perimeter and area. It has set and get methods for both
length and width. The set methods should verify that length and width are each floating-point
numbers larger than 0.0 and less than 20.0. Write a program to test class Rectangle.
public class Rectangle { private double
length = 1; private double width = 1;
public void setLength(double length) {
if (length > 0.0 )
if (length < 20.0) {this.length = length;}}
public double getLength() {return length;}
public void setWidth(double width) {if (width > 0.0) if
(width < 20.0) {this.width = width;}}
public double getWidth() {return width;}
public double getPerimeter() {return 2 * (length + width);}
public double getArea() {return length * width;}}
public class RectangleTest {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle();
rectangle.setLength(5.0);
rectangle.setWidth(3.0);
System.out.println("Length: " + rectangle.getLength());
System.out.println("Width: " + rectangle.getWidth());
System.out.println("Perimeter: " + rectangle.getPerimeter());
System.out.println("Area: " + rectangle.getArea());}}

5. Create class SavingsAccount. Use a static variable annualInterestRate to store the


annual interest rate for all account holders. Each object of the class contains a private instance
variable savingsBalance indicating the amount the saver currently has on deposit. Provide
method calculateMonthlyInterest to calculate the monthly interest by multiplying the
savingsBalance by annualInterestRate divided by 12—this interest should be added to savings-
Balance. Provide a static method modifyInterestRate that sets the annualInterestRate to a new
value. Write a program to test class SavingsAccount. Instantiate two savingsAccount objects,
saver1 and saver2, with balances of $2000.00 and $3000.00, respectively. Set
annualInterestRate to 4%, then calculate the monthly interest for each of 12 months and print
the new balances for both savers. Next, set the annualInterestRate to 5%, calculate the next
month’s interest and print the new balances for both savers.

public class SavingsAccount {


private double savingsBalance;
private static double annualInterestRate;
public SavingsAccount(double savingsBalance) {this.savingsBalance = savingsBalance;}
public void calculateMonthlyInterest() {
double monthlyInterestRate = annualInterestRate / 12;
double monthlyInterest = savingsBalance * monthlyInterestRate;
savingsBalance += monthlyInterest;}
public static void modifyInterestRate(double newInterestRate) {
annualInterestRate = newInterestRate;}
public double getSavingsBalance() {return savingsBalance;}}
public class SavingsAccountTest { public static void
main(String[] args) {
SavingsAccount saver1 = new SavingsAccount(200000.00);
SavingsAccount saver2 = new SavingsAccount(300000.00);
SavingsAccount.modifyInterestRate(0.04);
for (int i = 1; i <= 12; i++) {
saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();
System.out.printf("Month %d - Saver 1 balance: $%.2f, Saver 2 balance: $%.2f%n", i,
saver1.getSavingsBalance(), saver2.getSavingsBalance());}
SavingsAccount.modifyInterestRate(0.05);
saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();
System.out.printf("Next month - Saver 1 balance: $%.2f, Saver 2 balance: $%.2f%n",
saver1.getSavingsBalance(), saver2.getSavingsBalance()); }}

LAB PRACTICAL 6:

1. (Composition)Write a java program that contains classes Date, Employee and


EmployeeTest.Class Date declares instance variables month, day and year to represent a date.
Create a constructor that receives three int parameters for initializing the objects. Provide a
toString method to obtain the object’s String representation. Class Employee has instance
variables firstName, lastName, birthDate and hireDate. Members firstName and lastName are
references to String objects. Members birthDate and hireDate are references to Date objects.
Create Employee constructor that takes four parameters representing the first name, last name,
birth date and hire date for initializing the objects. Provide a toString to returns a String
containing the employee’s name and the String representations of the two Date objects. Class
EmployeeTest creates two Date objects to represent an Employee’s birthday and hire date,
respectively. It creates an Employee’s object and initializes its instance variables by passing to
the constructor two Strings (representing the Employee’s first and last names) and two Date
objects (representing the birthday and hire date).

public class Date {


private int month;
private int day;
private int year;
public Date(int month,
int day, int year) {
this.month = month;
this.day = day;
this.year = year;}
public String toString() {return String.format("%d/%d/%d", month, day, year);}}
public class Employee {
private String firstName;
private String lastName;
private Date birthDate;
private Date hireDate;
public Employee(String firstName, String lastName, Date birthDate, Date hireDate) {
this.firstName = firstName;
this.lastName = lastName;
this.birthDate = birthDate;
this.hireDate = hireDate;}

public String toString() {


return String.format("%s %s%nBirth date: %s%nHire date: %s%n", firstName, lastName,
birthDate, hireDate);}}
public class EmployeeTest {
public static void main(String[] args) {
Date birthDate = new Date(1, 1, 2000);
Date hireDate = new Date(1, 1, 2020);
Employee employee = new Employee("Leandro, "Paredes", birthDate, hireDate);
System.out.println(employee);}}

2. (Composition)Modify question 1 to perform validation of the month and day. Validate the
month—if it’s out-of-range, display error report. Validate the day, if the day is incorrect based
on the number of days in the particular month (except February 29th which requires special
testing for leap years), display error report. Perform the leap year testing for February, if the
month is February and the day is 29 and the year is not a leap year, display error report.

public class Date {


private int month;
private int day;
private int year;
public Date(int month, int day, int year) {
if (month < 1 || month > 12) {
System.out.println("Invalid month.");
} else {this.month = month;}
if (day < 1 || day > daysInMonth(month, year)) {
System.out.println("Invalid day.");
} else {this.day = day;}
this.year = year;}
public String toString() {
return
String.format("%d/%d/%d",
month, day, year);}
private int daysInMonth(int
month, int year) { if
(month == 2) {
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {return 29;}
else {return 28;}
}else if (month == 4 || month == 6 || month == 9 || month == 11) {return 30;}
else {return 31;}}}

3. (Single Inheritance) Write a java app that contains classes Polygon, Rectangle, and myMain.
Class Polygon declares instance variables height and width and defines a method setValues for
setting height and width values supplied by user. Class rectangle extends class Poygon and
defines method area for calculating and returning area of a rectangle. Class myMain defines
main method, creates an object and calls other methods for demonstrating their capabilities.

public class Polygon {


protected double height;
protected double width;
public void setValues(double height, double width) {
this.height = height;
this.width = width;}}
public class Rectangle extends Polygon {
public double area() {return height * width;}}
public class myMain {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle();
rectangle.setValues(5.0, 3.0);
System.out.println("Area of rectangle: " + rectangle.area());}}

4. (Multilevel Inheritance) Write a java app that contains classes EmployeeA, EmployeeB,
EmployeeC and EmployeesTest. Class EmployeeA should declare float variable salary initialized
with an arbitrary value. Class EmployeeB declares float variable bonusB initialized with an
arbitrary value and extends class EmployeeA. Class EmployeeC declares float variable bonusC
initialized with an arbitrary value and extends class EmployeeB. Class EmployeesTest should
define main method, create object of class EmployeeC and display the earning of each
employee.

public class EmployeeA {protected float salary = 1000.0f;}


public class EmployeeB extends EmployeeA {protected float bonusB = 100.0f;}
public class EmployeeC extends EmployeeB {protected float bonusC = 10.0f;}
public class EmployeesTest {
public static void main(String[] args) {
EmployeeC employeeC = new EmployeeC();
float totalEarning = employeeC.salary + employeeC.bonusB + employeeC.bonusC;
System.out.println("Employee A's salary: " + employeeC.salary);
System.out.println("Employee B's bonus: " + employeeC.bonusB);
System.out.println("Employee C's bonus: " + employeeC.bonusC);
System.out.println("Total earning: " + totalEarning);}}

5. (Hierarchical Inheritance) Write a java app that contains classes Polygon, Rectangle, Rectangle
and myMain. Class Polygon declares instance variables height and width and defines a method
setValues for setting height and width values supplied by user. Class Rectangle defines method
areaR for calculating and returning area of a rectangle and extends class Poygon. Class Triangle
defines method areaT for calculating and returning area of a triangle and extends class Polygon.
Class myMain defines main method, creates Rectangle and Triangle’s objects and calls the
methods for demonstrating their capabilities.

public class Polygon {


protected double height;
protected double width;
public void setValues(double height, double width) {
this.height = height;
this.width = width;}}
public class Rectangle extends Polygon {
public double areaR() {return height * width;}}
public class Triangle extends Polygon {
public double areaT() {return 0.5 * height * width;}}
public class myMain {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle();
rectangle.setValues(5.0, 3.0);
System.out.println("Area of rectangle: " + rectangle.areaR());
Triangle triangle = new Triangle();
triangle.setValues(5.0, 3.0);
System.out.println("Area of triangle: " + triangle.areaT());}}

6. (Abstraction and Overriding) Write a java app that contains classes Polygon, Rectangle, Triangle
and myMain. Class Polygon declares instance variables height and width and defines a method
setValues for setting height and width values supplied by user. It should also define abstract
method area. Class Rectangle extends class Polygon and implements method area for calculating
and returning area of a rectangle. Class Triangle extends class Polygon and implements method
area for calculating and returning area of a triangle. Class myMain defines main method, creates
Rectangle and Triangle’s objects and calls the methods for demonstrating their capabilities.

public abstract class Polygon {


protected double height;
protected double width;
public void setValues(double height, double width) {
this.height = height; this.width = width;}
public abstract double area()}
public class Rectangle extends Polygon {
public double area() {return height * width;}}
public class Triangle extends Polygon {
public double area() {return 0.5 * height * width;}}
public class myMain {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle();
rectangle.setValues(5.0, 3.0);
System.out.println("Area of rectangle: " + rectangle.area());
Triangle triangle = new Triangle(); triangle.setValues(4.0,
8.0);
System.out.println("Area of triangle: " + triangle.area());}}

7. (Hierarchical Inheritance) Write a java app that contains classes Employee, Programmer,
Accountant and MyMain. Class Employee should declare double variable salary initialized with
an arbitrary value. Class Programmer declares double variable bonusP initialized with an
arbitrary value and extends class Employee. Class Accountant declares double variable bonusA
initialized with an arbitrary value and extends class Employee. Class MyMain should define main
methdod, create objects of classes Programmer and Accountant and display the earning of each
employee.

public class Employee {protected double salary = 1000.0;}


public class Programmer extends Employee {protected double bonusP = 100.0;}
public class MyMain {
public static void main(String[] args) {
Programmer programmer = new Programmer();
Accountant accountant = new Accountant();
System.out.println("Programmer's earning: " + (programmer.salary + programmer.bonusP));
System.out.println("Accountant's earning: " + (accountant.salary + accountant.bonusA));}}

8. In this question we use an inheritance hierarchy containing types of employees in a company’s


payroll application to understand the relationship between a superclass and its subclass. In this
company, commission employees (who will be represented as objects of a superclass) are paid a
percentage of their sales, while base-salaried commission employees (who will be represented
as objects of a subclass) receive a base salary plus a percentage of their sales. We divide our
problem into five parts. a. Declare class CommissionEmployee, which directly inherits from class
Object and declares as private instance variables a first name, last name, social security number,
commission rate and gross (i.e., total) sales amount. b. Declare class
BasePlusCommissionEmployee, which also directly inherits from class Object and declares as
private instance variables a first name, last name, social security number, commission rate, gross
sales amount and base salary. You create this class by writing every line of code the class
requires. What problem did you note regarding relationship between class
BasePlusCommissionEmployee and CommissionEmployee? c. Declare a new
BasePlusCommissionEmployee class that extends class CommissionEmployee (i.e., a
BasePlusCommissionEmployee is a CommissionEmployee who also has a base salary). Why the
code is not running? d. Change CommissionEmployee’s instance variables to protected. Now
BasePlusCommissionEmployee subclass can access that data directly. What is tha drawbacks of
using protected instance variables? e. Set the CommissionEmployee instance variables back to
private to enforce good software engineering. Then show how the
BasePlusCommissionEmployee subclass can use CommissionEmployee’s public methods to
manipulate (in a controlled manner) the private instance variables inherited from
CommissionEmployee. What are advantages of using private instance variables in this case?

public class CommissionEmployee {


private String firstName;
private String lastName;
private String socialSecurityNumber;
private double commissionRate;
private double grossSales;
public CommissionEmployee(String firstName, String lastName, String socialSecurityNumber,
double commissionRate, double grossSales) {
this.firstName = firstName;
this.lastName = lastName;
this.socialSecurityNumber = socialSecurityNumber;
this.commissionRate = commissionRate;
this.grossSales = grossSales;}}
public class BasePlusCommissionEmployee {
private String firstName;
private String lastName;
private String socialSecurityNumber;
private double commissionRate;
private double grossSales;
private double baseSalary;
public BasePlusCommissionEmployee(String firstName, String lastName, String
socialSecurityNumber, double commissionRate, double grossSales, double baseSalary) {
this.firstName = firstName;
this.lastName = lastName;
this.socialSecurityNumber = socialSecurityNumber;
this.commissionRate = commissionRate;
this.grossSales = grossSales;
this.baseSalary = baseSalary;}}

public class BasePlusCommissionEmployee extends CommissionEmployee {


private double baseSalary;
public BasePlusCommissionEmployee(String firstName, String lastName, String
socialSecurityNumber, double commissionRate, double grossSales, double baseSalary) {
super(firstName, lastName, socialSecurityNumber, commissionRate, grossSales);
this.baseSalary = baseSalary;}}
public class CommissionEmployee {protected String firstName; protected String
lastName; protected String socialSecurityNumber; protected double
commissionRate;
protected double grossSales;

public CommissionEmployee(String firstName, String lastName, String socialSecurityNumber,


double commissionRate, double grossSales) {
this.firstName = firstName;
this.lastName = lastName;
this.socialSecurityNumber = socialSecurityNumber;
this.commissionRate = commissionRate;
this.grossSales = grossSales;}}
public class CommissionEmployee {
private String firstName; private
String lastName; private String
socialSecurityNumber; private
double commissionRate; private
double grossSales;
public CommissionEmployee(String firstName, String lastName, String socialSecurityNumber,
double commissionRate, double grossSales) {
this.firstName = firstName;
this.lastName = lastName;
this.socialSecurityNumber = socialSecurityNumber;
this.commissionRate = commissionRate;
this.grossSales = grossSales;}
public String getFirstName() {return firstName;}
public String getLastName() {return lastName;}
public String getSocialSecurityNumber() {return socialSecurityNumber;}
public double getCommissionRate() {return commissionRate;}
public double getGrossSales() {return grossSales;}
public void setFirstName(String firstName) {this.firstName = firstName;}
public void setLastName(String lastName) {this.lastName = lastName;}
public void setSocialSecurityNumber(String socialSecurityNumber) {
this.socialSecurityNumber = socialSecurityNumber;} public void
setCommissionRate(double commissionRate) { this.commissionRate =
CommissionRate;}
public void setgrossSales(double grossSales) {this.grossSales = grossSales;}
9. (Abstraction)A company pays its employees on a weekly basis. The employees are of four types:
Salaried employees are paid a fixed weekly salary regardless of the number of hours worked,
hourly employees are paid by the hour and receive overtime pay (i.e., 1.5 times their hourly
salary rate) for all hours worked in excess of 40 hours, commission employees are paid a
percentage of their sales and base-salaried-commission-employees receive a base salary plus a
percentage of their sales. For the current pay period, the company has decided to reward
salaried-commission employees by adding 10% to their base salaries. The company wants you to
write an application that performs its payroll calculations. Use an abstract superclass Employee
that includes firstName, lastName, socialSecurityNumber, getFirstName, getLastName,
getSocialSecurityNumber, toString, constructor and an abstract method earning.

public abstract class Employee {


private String firstName;
private String lastName;
private String socialSecurityNumber;
public Employee(String firstName, String lastName, String socialSecurityNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.socialSecurityNumber = socialSecurityNumber;}
public String getFirstName() {return firstName;}
public String getLastName() {return lastName;}
public String getSocialSecurityNumber() {return socialSecurityNumber;}
public String toString() {
return String.format("%s %s%nSocial Security Number: %s", getFirstName(), getLastName(),
getSocialSecurityNumber());} public abstract double earning();}
public class SalariedEmployee extends Employee {
private double weeklySalary;
public SalariedEmployee(String firstName, String lastName, String socialSecurityNumber,
double weeklySalary) {super(firstName, lastName, socialSecurityNumber);
this.weeklySalary = weeklySalary;}
public double earning() }
return weeklySalary;}}
public class CommissionEmployee extends Employee {
private double grossSales;
private double commissionRate;
public CommissionEmployee(String firstName, String lastName, String socialSecurityNumber,
double grossSales, double commissionRate) {
super(firstName, lastName, socialSecurityNumber);
this.grossSales = grossSales;
this.commissionRate = commissionRate;}
public double earning() {return grossSales * commissionRate;}}
public class HourlyEmployee extends Employee {
private double wage;
private double hours;
public HourlyEmployee(String firstName, String lastName, String socialSecurityNumber, double
wage, double hours) {
super(firstName, lastName, socialSecurityNumber);
this.wage = wage;
this.hours = hours;}
public double earning() {if (hours <= 40) {
return wage * hours;
} else {
return wage * 40 + (wage * 1.5 * (hours - 40));
}}}
public class BasePlusCommissionEmployee extends CommissionEmployee {
private double baseSalary;
public BasePlusCommissionEmployee(String firstName, String lastName, String
socialSecurityNumber, double grossSales, double commissionRate, double baseSalary) {
super(firstName, lastName, socialSecurityNumber, grossSales, commissionRate);
this.baseSalary = baseSalary;}
public double earning() {return super.earning() + baseSalary * 1.1;}}
public class MyMain {
public static void main(String[] args) {
SalariedEmployee salariedEmployee = new SalariedEmployee("mike", "leonella", "123-45-
6789", 1000.0);
CommissionEmployee commissionEmployee = new CommissionEmployee("abbas ",
"mvuma", "987-65-4321", 5000.0, 0.1);
HourlyEmployee hourlyEmployee = new HourlyEmployee("alan", "makanale", "111-223333",
10.0, 50.0);
BasePlusCommissionEmployee basePlusCommissionEmployee = new
BasePlusCommissionEmployee("Uswaggy", “Mtabe", "444-55-6666", 10000.0, 0.05, 500.0);
System.out.printf("%s earned $%.2f%n", salariedEmployee.getFirstName(),
salariedEmployee.earning());
System.out.printf("%s earned $%.2f%n", commissionEmployee.getFirstName(),
commissionEmployee.earning());
System.out.printf("%s earned $%.2f%n", hourlyEmployee.getFirstName(),
commissionEmployee.earning()); }

LAB PRACTICAL 8(EXCEPTION HANDLING):


1. (Catching Exceptions with Superclasses) Use inheritance to create an exception superclass (called
ExceptionA) and exception subclasses ExceptionB and ExceptionC, where ExceptionB inherits
from ExceptionA and ExceptionC inherits from ExceptionB. Write a program to demonstrate that
the catch block for type ExceptionA catches exceptions of types ExceptionB and ExceptionC.

class ExceptionA extends Exception { public ExceptionA(String message) {


super(message);
}
}
class ExceptionB extends ExceptionA {
public ExceptionB(String message) {
super(message);
}
}
class ExceptionC extends ExceptionB {
public ExceptionC(String message) {
super(message);
}
}
public class Main { public static void
main(String[] args) { try {
throw new ExceptionC("ExceptionC occurred");
} catch (ExceptionA e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
}

2. (Catching Exceptions Using Class Exception) Write a program that demonstrates how various
exceptions are caught with catch (Exception exception). Define classes ExceptionA (which
inherits from class Exception) and ExceptionB (which inherits from class ExceptionA). In your
program, create try blocks that throw exceptions of types ExceptionA, ExceptionB,
NullPointerException and IOException. All exceptions should be caught with catch blocks
specifying type Exception.

import java.io.IOException; class


ExceptionA extends Exception {
public ExceptionA(String message) {
super(message);
}
}
class ExceptionB extends ExceptionA {
public ExceptionB(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
try {
throw new ExceptionA("ExceptionA occurred");
} catch (Exception exception) {
System.out.println("Caught exception: " + exception.getMessage());
}
try {
throw new ExceptionB("ExceptionB occurred");
} catch (Exception exception) {
System.out.println("Caught exception: " + exception.getMessage());
}
try {
throw new NullPointerException("NullPointerException occurred");
} catch (Exception exception) {
System.out.println("Caught exception: " + exception.getMessage());
}
try {
throw new IOException("IOException occurred");
} catch (Exception exception) {
System.out.println("Caught exception: " + exception.getMessage());
}
}
}

3. (Order of catch Blocks) Write a program demonstrating that the order of catch blocks is
important. If you try to catch a superclass exception type before a subclass type, the compiler
should generate errors.

import java.io.IOException;

public class Main {


public static void main(String[] args) {
try {
throw new IOException("IOException occurred");
} catch (Exception e) {
System.out.println("Caught Exception: " + e.getMessage());
} catch (IOException ioException) {
System.out.println("Caught IOException: " + ioException.getMessage());
}
}
}

4. (Constructor Failure) Write a program that shows a constructor passing information about
constructor failure to an exception handler. Define class SomeClass, which throws an Exception
in the constructor. Your program should try to create an object of type SomeClass and catch the
exception that’s thrown from the constructor.

class SomeClass {
public SomeClass() throws Exception {

throw new Exception("Constructor failed to initialize

SomeClass");

}
}

public class Main {


public static void main(String[] args) {
try {
SomeClass obj = new SomeClass();
} catch (Exception e) {
System.out.println("Exception caught: " + e.getMessage());
}
}}

5. (Rethrowing Exceptions) Write a program that illustrates rethrowing an exception. Define


methods someMethod and someMethod2. Method someMethod2 should initially throw an
exception. Method someMethod should call someMethod2, catch the exception and rethrow it.
Call someMethod from method main, and catch the rethrown exception. Print the stack trace of
this exception.

public class Main {


public static void main(String[] args) {
try {
ourMethod();
} catch (Exception e) {

System.out.println("Exception caught in main method:");


e.printStackTrace();
}
}

public static void ourMethod() throws Exception {

try {
ourMethod2();
} catch (Exception e) {
System.out.println("Exception caught in ourMethod:");
throw e;
}
}

public static void ourMethod2() throws Exception {


throw new Exception("Exception thrown from ourMethod2");
}
}

6. (Catching Exceptions Using Outer Scopes) Write a program showing that a method with its own
try block does not have to catch every possible error generated within the try. Some exceptions
can slip through to, and be handled in, other scopes.

public class Main {


public static void main(String[] args) {
try {
methodWithTryBlock();
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught in main method: " + e.getMessage());
}
}

public static void methodWithTryBlock() {


try {
int result = divideByZero();
System.out.println("Result: " + result);
} catch (NullPointerException e) {
System.out.println("NullPointerException caught in methodWithTryBlock: " +
e.getMessage());
}
}

public static int divideByZero() {


return 5 / 0;
}
}

7. Write a program that illustrates exception propagation. Define methods propagator1 and
propagator2. Method propagator1 should initially throw an ArithmeticException exception.
Method propagator2 should call propagator1, re-throw the exception. Call propagator2 from
method main, and catch and handle the re-thrown exception by printing the stack trace of the
exception.

public class Main {


public static void main(String[] args) {
try {
propagator2();
} catch (ArithmeticException e) {
e.printStackTrace();
}
}

public static void propagator1() {


throw new ArithmeticException("ArithmeticException thrown from propagator1");
}

public static void propagator2() {


try {
propagator1();
} catch (ArithmeticException e) {
throw e;
}
}
}
JDBC ACTIVITY:

1. The following diagram shows the relationship between Java code, JDBC API
and Database Driver.

2. Requirements necessary to use JDBC and MySQL SERVER:


i. Java Development Kit (JDK): JDBC is a Java API, so you will need a JDK
installed on your machine to use JDBC.
ii. MySQL database: You will need a MySQL database up and running
that you can connect to.
iii. MySQL Connector/J JDBC driver: You will need to download and
include the MySQL Connector/J JDBC driver in your project classpath
to be able to connect to a MySQL database
jdbc:mysql://hostname:port/databaseName using JDBC.
iv. Database URL: You will need to know the database URL in iv.
the appropriate format to connect to the MySQL database.
v. Database credentials: You will need the database username and
password to connect to the database.
vi. Java code: Finally, you will need to write Java code to establish the
connection and perform database operations using JDBC.

3. Steps involved when using JDBC to connect to the DBMS and retrieve data
from database into command line, or inserting/update data into tables (i.e
packages, classes, methods, object etc):

i. Load the JDBC driver class: The first step is to load the JDBC driver
class for the database you want to connect to, for example,
Class.forName("com.mysql.jdbc.Driver").

ii. Open a connection to the database: Use the


DriverManager.getConnection method to establish a connection to the
database, providing the URL, username, and password as arguments.

iii. Create a statement object: Use the Connection.createStatement


method to create a Statementobject that you can use to execute SQL
statements.

iv. Execute a query: Use the Statement.executeQuery method to


execute a SQL query and retrieve the result set.

v. Process the result set: Use the ResultSet object returned by the
query to iterate through the rows of the result set and retrieve the data.

vi. Close the connection: Finally, close the connection to the


database using the Connection.close method.

For inserting/updating data into tables, use the Statement.executeUpdate method


instead of executeQuery, and pass it a SQL INSERT or UPDATE statement. The method
returns the number of rows affected by the operation.
4. SQL query for:
a) To create database called StudentData:

b) To create table called Student and Course.


c) Java code to Insert/ update in your code / retrieve on command line
data into/ from database tables.

i. INSERT INTO COURSES

ii. RETRIEVE FROM COURSES

iii. UPDATE CODE


5. Prepared statement to insert, select, update and delete operation:

i. INSERTION OPERATION

ii. SELECT OPERATION

iii. UPDATE OPERATION


iv. DELETE OPERATION

6. JDBC to perform batch insert, batch update and dynamically insert multiple
rows into your databases.

i. BATCH INSERT

ii. BATCH UPDATE

iii. DYNAMICALLY INSERT


7. To access a remote database server using JDBC, you need to specify the IP
address of the server and the port number for the database service in the
URL when connecting to the database.

You might also like