[go: up one dir, main page]

0% found this document useful (0 votes)
42 views75 pages

Se2 Group9 9

The document describes a lab assignment for a course on Object-Oriented Programming in Java at the University of Dodoma. It lists 9 students enrolled in the course and their registration numbers. It then provides 11 questions as part of the first lab assignment, involving writing Java classes, methods, and code to demonstrate concepts like object instantiation, parameter passing, overloading methods, and more. The questions cover topics like declaring variables, creating classes with methods and constructors, handling input/output, and testing class functionality.

Uploaded by

Bryan Phillip
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views75 pages

Se2 Group9 9

The document describes a lab assignment for a course on Object-Oriented Programming in Java at the University of Dodoma. It lists 9 students enrolled in the course and their registration numbers. It then provides 11 questions as part of the first lab assignment, involving writing Java classes, methods, and code to demonstrate concepts like object instantiation, parameter passing, overloading methods, and more. The questions cover topics like declaring variables, creating classes with methods and constructors, handling input/output, and testing class functionality.

Uploaded by

Bryan Phillip
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

THE UNIVERSITY OF DODOMA

COLLEGE OF INFORMATICS AND VIRTUAL EDUCATION

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

COURSE NAME: OBJECT-ORIENTED PROGRAMMING IN JAVA

GROUP NUMBER: BSC.SE_9


S/N NAME OF STUDENT REGISTRATION NO: SIGNATURE SCORES

1 KULWA SIMON MARUBA T22-03-14638

2 KATUNDU ALOYCE MAKONDE T22-03-05078

3 HAMISI SELEMANI HAMISI T22-03-11748

4 PATRICK KENNETH MPEMBO T22-03-11757

5 GREYGORY EVARIST SULLE T22-03-07303

6 PROSPER LAITON MPELETA T22-03-02537

7 SAMWEL STEVEN NGUSA T22-03-03695

8 JEREMIAH LEMA T22-03-07169

9 JUMA RICHARD T21-03-04488

FIRST LAB ASSIGNMENT: LAB ASSIGNMENT 4


LAB ASSIGNMENT 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.
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.
Modify question 2 to allow a user to pass arguments to the methods using Scanner class.

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

// Instance variable declaration


double number;

// Constructor
public VariableDeclaration(){
number = 1;
}

public void set(int n){


number = n;
}

public static void main(String[] args) {


}
}

class Instantiator { //
Instantiating object
VariableDeclaration object = new VariableDeclaration();

object.set(99);

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.

class Employee {
String first_name;
String last_name;
double salary;

public Employee () {
first_name = "Nasibu";
last_name = "Maulid";
salary = 0;
}
public void setFirstName(String fname) {
this.first_name = fname;
}

public void setLastName(String lname) {


this.last_name = lname;
}

public void setSalary(double


salary){ if(salary >= 0)
this.salary = salary;
}

public String getFirstName(){


return this.first_name;

public String getLastName() {


return this.last_name;
}

public double getSalary() {


return this.salary;
}
}

public class EmployeeTest {

public static void main(String[] args) {


Employee employeeObject = new Employee();

employeeObject.setFirstName("GREYSON");
employeeObject.setLastName("shawa"); employeeObject.setSalary(120000);
System.out.println(employeeObject.getFirstName());
System.out.println(employeeObject.getLastName());
System.out.println(employeeObject.getSalary());

Employee object1, object2;


object1 = new Employee(); object2 =
new Employee();

object1.setSalary(2000000);
object2.setSalary(400000);

System.out.println("Object 1 salary: "+object1.getSalary());


System.out.println("Object 2 salary: "+object2.getSalary());
object1.setSalary(object1.getSalary() + 0.1*object1.getSalary());
object1.setSalary(object2.getSalary() + 0.1*object2.getSalary());

System.out.println("Salaries after 10% increment:");


System.out.println("Object 1 salary: "+object1.getSalary());
System.out.println("Object 2 salary: "+object2.getSalary());
}

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.
LAB ASSIGNMENT 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.

class Employee
{ String name;
Double balance;

public Employee(){
//
Initialization
this.balance =
0.0;
this.name = "--
";
}

public void setName(String name) {


this.name = name;
}
public String getName(){
return this.name;
}
public void deposite(Double amount) {
this.balance = amount;
}
public Double getBalance(){
return this.balance;
}
}

public class EmployeeTest {

public static void main(String[] args) {


Employee employee1 = new Employee();
Employee employee2 = new Employee();

System.out.println(employee1.name);
System.out.println(employee1.balance);

employee1.setName("Nasibu Maulid Omary"); employee2.setName("Kasimu


Juma Omary"); employee1.deposite(120000.0);
employee2.deposite(1000000.0);

System.out.println("Employee1 Name: "+employee1.name);


System.out.println("Balance: "+employee1.balance);
System.out.println("---------------------");
System.out.println("---------------------");
System.out.println("Employee2 Name: "+employee2.getName());
System.out.println("Employee2 Balance: "+employee2.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.

class Employee
{ String name;
Double balance;

public Employee(){
//
Initialization
this.balance =
0.0;
this.name = "--
";
}

public void setName(String name) {


this.name = name;
}
public String getName(){
return this.name;
}
public void deposite(Double amount) {
this.balance = amount;
}
public Double getBalance(){
return this.balance;
}
public void Withdraw(Double amount){
if (amount <= this.balance){
this.balance = this.balance - amount;
}
el
se
{
System.out.println("Withdrawal amount exceeded Employee balance.");
}
}
}

public class EmployeeTest {

public static void main(String[] args) {


Employee employee1 = new Employee();
Employee employee2 = new Employee();
System.out.println(employee1.name);
System.out.println(employee1.balance);

employee1.setName("Nasibu Maulid Omary");


employee2.setName("Kasimu Juma Omary");

employee1.deposite(120000.0);
employee2.deposite(1000000.0);

System.out.println("Employee1 Name: "+employee1.name);


System.out.println("Balance: "+employee1.balance);
System.out.println("---------------------");
System.out.println("---------------------");
System.out.println("Employee2 Name: "+employee2.getName());
System.out.println("Employee2 Balance: "+employee2.getBalance());

employee1.Withdraw(100000.0);
System.out.println("Employee1 balance after withdrawal: "
+ employee1.getBalance());

employee2.Withdraw(10000000.0);
}
}
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.

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 object1 = new
Employee();
Employee object2 = new Employee();
System.out.println("Number of objects created is " + 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.

class Rectangle {
float length, width;

public Rectangle()
{ this.length = 1;
this.width = 1;
}

public float Area() {


return this.length * this.width;
}

public float Perimeter() {


return 2*(this.length + this.width);
}

public void setLength(float len) {


if(len>0 && len<20) this.length = len;
}

public void setWidth(float wid) {


if(width>0 && width<20) this.width = wid;
}

public float getLength(){


return this.length;
}

public float getWidth(){


return this.width;
}
}

public class RectangleTest {

public static void main(String[] args) { Rectangle


rectangle = new Rectangle();
System.out.println("Before setting values:");
System.out.println("Length = " + rectangle.getLength());
System.out.println("Width = " + rectangle.getWidth());

System.out.println("--------------------------");

rectangle.setLength(4);
rectangle.setWidth(6);

System.out.println("After setting values:");


System.out.println("Length = " + rectangle.getLength());
System.out.println("Width = " + rectangle.getWidth()); System.out.println("-
---------------------------");

System.out.println("Area = " + rectangle.Area());


System.out.println("Perimeter = " + rectangle.Perimeter());

}
}
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.
class SavingsAccount
{ static float
annualInterestRate;
private float
savingsBalance;

public float
getBalance(){
return
this.savingsBalance;
}
public void setBalance(float balance) {
this.savingsBalance = balance;
}

public void calculateMonthlyInterest() { this.savingsBalance = this.savingsBalance +


(this.savingsBalance*annualInterestRate)/12;
}

public void modifyInterestRate(float


newValue) { annualInterestRate =
newValue;
}
}

public class SavingsAccountTest {

public static void main(String[] args) {


SavingsAccount saver1 = new SavingsAccount(), saver2 = new SavingsAccount();
saver1.setBalance(2000); saver2.setBalance(3000);

saver1.modifyInterestRate(4);
saver2.modifyInterestRate(4);

saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();

System.out.println("Saver1 new balance = $" + saver1.getBalance());


System.out.println("Saver2 new balance = $" + saver2.getBalance());

System.out.println("##########");
saver1.modifyInterestRate(5);
saver2.modifyInterestRate(5);

saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();

System.out.println("Saver1 new balance = $" + saver1.getBalance());


System.out.println("Saver2 new balance = $" + saver2.getBalance());

System.out.println("######");
}
}
LAB ASSIGNMENT 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).

1. package solution6;
2. public class Date

3. {

4. private int month; // 1-12

5. private int day; // 1-31 based on month

6. private int year; // any year

7. // constructor: call checkMonth to confirm proper value for month;

8. // call checkDay to confirm proper value for day

9. public Date( int theMonth, int theDay, int theYear )

10. {

11. month = checkMonth( theMonth ); // validate month

12. year = theYear; // could validate year

13. day = checkDay( theDay ); // validate day

14. System.out.printf(

15. "Date object constructor for date %s\n", this );


16. }

17. // utility method to confirm proper month value

18. private int checkMonth( int testMonth ) 19. {

20. if ( testMonth > 0 && testMonth <= 12 ) // validate month

21. return testMonth;

22. else // month is invalid


23. {

24. System.out.printf( "Invalid month (%d) set to 1.", testMonth );

25. return 1; // maintain object in consistent state


26. }
27. }

28. // utility method to confirm proper day value based on month and year

29. private int checkDay( int testDay )


30. {
31. int daysPerMonth[] =

32. { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30,

31, 30, 31 };
33. // check if day in range for month

34. if ( testDay > 0 && testDay <= daysPerMonth[ month ] )

35. return testDay;

36. // check for leap year

37. if ( month == 2 && testDay == 29 && ( year % 400 == 0 ||

38. ( year % 4 == 0 && year % 100 != 0 ) ) ) 39. return testDay;

40. System.out.printf( "Invalid day (%d) set to 1.", testDay );


41. return 1; // maintain object in consistent state

42. }

43. // return a String of the form month/day/year

44. public String toString()

45. {

46. return String.format( "%d/%d/%d", year, day, month );

47. }

48. }
49.

50. //class Employee

51. package solution6;

52. public class Employee

53. {

54. private String firstName;

55. private String lastName;

56. private Date birthDate;

57. private Date hireDate;

58. // constructor to initialize name, birth date and hire date

59. public Employee( String first, String


last, Date dateOfBirth,
60. Date dateOfHire )
61. {
62. firstName = first;

63. lastName = last;

64. birthDate = dateOfBirth;

65. hireDate = dateOfHire;


66. }

67. // convert Employee to String format

68. public String toString() {

69. return String.format( "%s, %s Hired: %s Birthday: %s",

70. firstName,lastName, hireDate, birthDate );

71. }}
72.
73. package solution6;

74. public class EmployeeTest


75. {

76. public static void main( String args[] )


77. {

78. Date birth = new Date( 7, 24, 1999 );

79. Date hire = new Date( 19, 12, 2022 );

80. Employee employee = new Employee(


"Nasibu", "Omary", birth, hire );

81. System.out.println( employee );


82. }
83. }
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

84.
display error report. Perform the leap year testing for February, if the month is February and the day is
of days in the particular month (except February 29th which requires special testing for leap years), 29
and the year is not a leap year, display error report.

1. package solution6;

2. public class Date

3. {

4. private int month; // 1-12

5. private int day; // 1-31 based on month

6. private int year; // any year

7. // constructor: call checkMonth to confirm proper value for month;

8. // call checkDay to confirm proper value for day

9. public Date( int theMonth, int theDay, int theYear )

10. {

11. month = checkMonth( theMonth ); // validate month

12. year = theYear; // could validate year

13. day = checkDay( theDay ); // validate


day

14. System.out.printf(

15. "Date object constructor for date %s\n",


this );
16. }

17. // utility method to confirm proper month value

18. private int checkMonth( int testMonth ) 19. {

20. if ( testMonth > 0 && testMonth <= 12 ) // validate month

21. return testMonth;

22. else // month is invalid


23. {

24. System.out.printf( "Invalid month (%d) set to 1.", testMonth );

25. return 1; // maintain object in consistent state


26. }
27. }

28. // utility method to confirm proper day value based on month and year

29. private int checkDay( int testDay )


30. {
31. int daysPerMonth[] =

32. { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30,
31, 30, 31 };
33. // check if day in range for month

34. if ( testDay > 0 && testDay <= daysPerMonth[ month ] )


35. return testDay; // check for leap year

36. if ( month == 2 && testDay == 29 && (


year % 400 == 0 ||
37. ( year % 4 == 0 && year % 100 != 0 ) ) ) 39. return testDay;

40. System.out.printf( "Invalid day (%d) set to 1.", testDay );

41. return 1; // maintain object in consistent state


42. }

43. // return a String of the form month/day/year

44. public String toString()


45. {

46. return String.format( "%d/%d/%d", year, day, month );

47. }
48. }
49. package solution6;

50. public class Employee


51. {

52. private String firstName;

53. private String lastName;


54. private Date birthDate;

55. private Date hireDate;

56. // constructor to initialize name, birth date and hire date

57. public Employee( String first, String last, Date dateOfBirth,

58. Date dateOfHire )

59. {

60. firstName = first;

61. lastName = last;

62. birthDate = dateOfBirth;

63. hireDate = dateOfHire;


64. }
65. // convert Employee to String format

66. public String toString() {


67. return String.format( "%s, %s Hired: %s Birthday: %s",

68. firstName,lastName, hireDate, birthDate );


69. }
70. }
71. package solution6;

72. public class EmployeeTest


73. {
74. public static void main( String args[] )
75. {

76. Date birth = new Date( 7, 24, 1999 );

77. Date hire = new Date( 19, 12, 2022 );

78. Employee employee = new Employee(


"Nasibu", "Omary", birth, hire );

79. System.out.println( employee );


80. }
81. }

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.
package question3; public class Polygon {
float height; float width; public void
setValues(float height,float width) {
this.height=height; this.width=width;
} public double getHeight()
{ return height;
} public double getWidth()
{ return width;
}

//Other class package question3; public class Rectangle extends Polygon { public
double area(){
return () * getHeight getWidth();

//other class package question3; public class MyMain { public static void
main(String[] args) { Rectangle square = new Rectangle();
square.setValues(15,5);
System.out.println("Width = " + square.width);

System.out.println("Height = " + square.height);

System.out.println();
System.out.println("Area = " + square.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.
package question4; public class EmployeeA { float
salary=324;
} package question4; public class EmployeeB extends

EmployeeA { float bonusB=10;

} package question4; public class EmployeeC extends

EmployeeB { float bonusC=100;

package question4; public class EmployeesTest {


public static void main(String[] args) { EmployeeC employeeC=new EmployeeC();
System.out.println("EMPLOYEE EARNINGS:");
System.out.println("*******************");
System.out.println("Employee A: " + employeeC.salary);

System.out.println("Employee B: " +
(employeeC.salary + employeeC.bonusB));

System.out.println("Employee C: " +
(employeeC.salary + employeeC.bonusC));
}

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.
package Question5; public class Polygon { double
height; double width;
public void (doubleheight,doublewidth){setValues

this.height=height; this.width=width;
} public double getHeight() { return

height;

public double getWidth() { return width;


}

}
package Question5; public class Rectangle extends Polygon { public double areaR()
{ return getHeight() * getWidth();

} } package
Question5;

public class extends Triangle Polygon { public double areaT() {


return (getHeight() * getWidth())/2;

} } package Question5; public class


MyMain {

public static void main(String[] args) {


Rectangle rectangle=new Rectangle(); Triangle triangle=new Triangle(); triangle.setValues(2.2,9);
rectangle.setValues(12,49);
System.out.println("\"width\" and
\"height\" for the rectangle are :");

System.out.println("Width = " + rectangle.width);

System.out.println("Height = "
+rectangle.height);

System.out.println("Area for Rectangle = " + rectangle.areaR() );

System.out.println("\n\"width\" and
\"height\" for the triangle are :");

System.out.println("Width = " + triangle.width);

System.out.println("Height = "
+triangle.height);
System.out.println("Area for 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.
package qn6;

public abstract class { Polygon

int height, width; public void setValues(int h, int

w){ this.height = h; this.width = w;

} public abstract double

area();

}
package qn6; public class Rectangle

extends Polygon {

@Override
public double area(){ return

this.height * this.width;

} } package qn6; public class Triangle

extends Polygon {

@Override public double area(){

return 0.5 * this.height * this.width;

}
package qn6; public class MyMain { public static void main(String[] args) {
Rectangle rectangle = new Rectangle(); rectangle.setValues(42, 51);

Triangle triangle = new Triangle(); triangle.setValues(521, 118);


System.out.println("Rectangle width = " + rectangle.width);
System.out.println("Rectangle height = " + rectangle.height);

System.out.println();

System.out.println("Triangle width (base) = " + triangle.width);

System.out.println("Triangle height = " + triangle.height);

System.out.println();

System.out.println("Area of rectangle = " + rectangle.area());

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
package question7; public class Employee { double
salary = 500;
}

package question7; public class Programmer extends Employee {

double bonusP = 4000;

}
package question7; public class Accountant extends Employee {

double bonusA = 700;

main methdod, create objects of classes Programmer and Accountant and display the earning
of each employee.

package question7; public class MyMain { public static void main(String[] args) {

Programmer programmer = new Programmer();

Accountant accountant = new Accountant();

System.out.println("EMPLOYEE EARNINGS:"); System.out.println("*-*-*-*-*-**-*-*-*-*- **-*-*-*-*-


*");
System.out.println("Programmer:\t" +
(programmer.salary + programmer.bonusP));

System.out.println("Accountant:\t" +
(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.
a) class Object {

}
class CommissionEmployee extends Object {
private String firstName; private String
lastName; private int
socialSecurityNumber; private double
commissionRate; private double
grossSalesAmount;
}

b) class BaseplusCommissionEmployee extends Object {


private String firstName; private String
lastName; private int
socialSecurityNumber; private double
commissionRate; private double
grossSalesAmount; private double
baseSalary;
}

At this the subclass cannot inherit any properties from the superclass (Object) since the
super class contains no any properties to be inherited.

c) The code in not running simply because private members cannot be inherited. Members to
be inherited have to be declared public or protected.

d) The drawback of using protected instance is that if the method or variable in declared with
the keyword protected it can be only accessed within a class and to the subclass.

e) Private instance variables are used for security purposes due to the fact that private instance
variable cannot be accessed outside the class.

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.
The classes that extend Employee are SalariedEmployee, CommissionEmployee and
HourlyEmployee. Class BasePlusCommissionEmployee which extends CommissionEmployee
represents the last employee type. The inheritance hierarchy is represented on the figure below.
package question9; abstract class Employee { private String firstName;
private String lastName; private String socialSecuriyNumber; public
String getFistName(){ return this.firstName;
} public String getLastName(){ return

this.lastName;

public String getSocialSecurityNumber(){ return this.socialSecuriyNumber;


}

@Override

public String toString (){

return getFistName()+" "+getLastName()+


"\n"+getSocialSecurityNumber();
}
}
GROUP ACTIVITY 2
Read on Java Database Connectivity (JDBC) and perform the following task: -
(Use MySql or SQL Server as your DBMS)

1) In diagram, indicate the relationship between Java code, JDBC API and Database Driver (of
your choice).

ANSWER

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database. There are four types of JDBC drivers:

• JDBC-ODBC Bridge Driver,


• Native Driver,
• Network Protocol Driver, and
• Thin Driver

Below is the diagram, indicate the relationship between Java code, JDBC API and
Database Driver using a Network Protocol Driver

The Network Protocol driver uses middleware (application server) that converts JDBC
calls directly or indirectly into the vendor-specific database protocol

DIAGRAM

JDBC
API

Network
Middleware Database
Java protocol
Application driver

Client machine Server side


2) Itemize requirements necessary to use JDBC and any DBMS (Install all packages and
drivers).

ANSWER

To use JDBC (Java Database Connectivity) with a DBMS (Database Management System), the
following requirements must be met:

1. Download and install the appropriate release of the MySQL database server software
(several different releases are available).
2. Download and install the MySQL Connector/J -- for connecting to a MySQL database
server from Java.
3. Download and install the documentation for the MySQL database server.
4. Download and install the documentation for the Connector, which is a separate
documentation package from the database server documentation.
5. Write and test one or more JDBC programs that will act as a database administrator,
creating one or more users and possibly one or more databases on the database server. (I
will show you three different ways to accomplish this.)

6. Write and test a JDBC program that will log in as a user and manipulate data stored in
one of those databases.

3) Understand the 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.e

• Loading driver
• Establishing connection
• Creating a statement
• Executing statements
• Processing ResultSet and closing your connection

Answer
1. Loading the Driver: The first step is to load the JDBC driver for the specific database
being used. This is typically done using the
Class.forName() method, passing in the fully-qualified name of the driver class as an
argument.
Example
// Loading the Driver
Class.forName("com.mysql.cj.jdbc.Driver");

2. Establishing Connection: Once the driver is loaded, a connection to the database can be
established using the DriverManager.getConnection() method. This method takes in the
URL of the database and the username and password to connect to the database.
Example
// Establishing Connection
Connection connection = DriverManager.getConnection(DB_URL,USER, PASS);

3. Creating a Statement: After a connection is established, a statement object can be


created using the Connection.createStatement() method. The statement object is used to
execute SQL statements against the database.
Example
// Creating a Statement
Statement statement = connection.createStatement();

4. Executing Statements: The statement object can be used to execute either a SELECT
statement to retrieve data from the database or an INSERT, UPDATE, or DELETE
statement to modify data in the database. The executeQuery() method is used to execute
SELECT statements, while the executeUpdate() method is used to execute data
modification statements.
Example
// Executing Statements
ResultSet resultSet = statement.executeQuery("SELECT * FROM my_table");

5. Processing ResultSet: If a SELECT statement was executed, the results of the query are
returned in a ResultSet object. The ResultSet can be used to retrieve the rows of data
returned by the query, using methods such as next() and getInt(), getString(), etc.
Example
// Processing ResultSet while
(resultSet.next()) {
// Do something with the retrieved data
}

6. Closing the Connection: Finally, it is important to close the connection when done using
it, to free up resources and prevent any potential connection leaks. This is done using
the Connection.close() method.
Example
// Closing the Connection connection.close();

4) Make sure your handle exception

Code file is called company.java

import java.sql.*; class Company{


public static void main(String args[]){ try {
// Loading the Driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establishing Connection
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/company","root","");
// Creating a Statement
Statement statement = connection.createStatement();

// Executing Statements
ResultSet resultSet = statement.executeQuery("SELECT * FROM employee");

// Processing ResultSet while


(resultSet.next()) { int emp_id =
resultSet.getInt("emp_id"); String name =
resultSet.getString("name");
Date date_of_birth = resultSet.getDate("date_of_birth");
String email = resultSet.getString("email");

System.out.println("Employee ID: " + emp_id + " | Name: " + name + " | Date of Birth:
" + date_of_birth + " | Email: " + email);

}
// Closing the Connection connection.close();
} catch (ClassNotFoundException e) {
System.out.println("Could not find the JDBC driver class.");
e.printStackTrace(); } catch (SQLException e) {
System.out.println("An error occurred while communicating with the database.");
e.printStackTrace();
}
}
}

5) Write a SQL query for


• To create database called StudentData
• Create table called Student and Course
• Use java code to Insert/ update in your code / retrieve on command line data
into/ from database tables.
CREATE DATABASE StudentData;
USE StudentData; CREATE TABLE Student ( student_id

INT PRIMARY KEY, name

VARCHAR(260) NOT NULL, date_of_birth

DATE NOT NULL, email VARCHAR(260)

NOT NULL UNIQUE

);

CREATE TABLE Course ( course_id INT

PRIMARY KEY, name VARCHAR(260)

NOT NULL, description VARCHAR(260)

NOT NULL

);

The process of the code above in command line

Code to insert data

import java.sql.*;

class Student{
public static void main(String args[]){ try {
// Loading the Driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establishing Connection
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/StudentData","root","
");

// Creating a Statement
Statement statement = connection.createStatement();

// Executing Statement to insert data into the Student table int result =
statement.executeUpdate("INSERT INTO Student
(student_id, name, date_of_birth, email) VALUES (1, 'jigui galasic', '1979-11- 01',
'jigui.galasic@example.com')");

// Checking if the insertion was successful if (result == 1)


{
System.out.println("Data inserted successfully.");
}
// Closing the Connection connection.close();
} catch (ClassNotFoundException e) {
System.out.println("Could not find the JDBC driver class.");
e.printStackTrace(); } catch (SQLException e) {
System.out.println("An error occurred while communicating with the database.");
e.printStackTrace();
}
}
}

Code to update data

import java.sql.*; class Student{


public static void main(String args[]){ try {
// Loading the Driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Establishing Connection
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/StudentData","root","
");

// Creating a Statement
Statement statement = connection.createStatement();

// Executing Statement to insert data into the Student table int result =
statement.executeUpdate("update Student set email = 'raudoe@gmail.com' where email=
'john.doe@example.com'");

// Checking if the insertion was successful if (result == 1)


{
System.out.println("Data inserted successfully.");
}
// Closing the Connection connection.close();
} catch (ClassNotFoundException e) {
System.out.println("Could not find the JDBC driver class.");
e.printStackTrace(); } catch (SQLException e) {
System.out.println("An error occurred while communicating with the database.");
e.printStackTrace();
}
}
}

Database state after update

Code to retrive data

import java.sql.*; class Student{ public static void


main(String args[]){ try {
// Loading the Driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establishing Connection
Connection connection =
DriverManager.getConnection("jdbc: mysql://localhost:3306/StudentData”,”root","
");

// Creating a Statement
Statement statement = connection. createStatement();
// Executing Statements
ResultSet resultSet = statement. executeQuery("SELECT * FROM Student");

// Processing ResultSet while


(resultSet.next()) { int student_id =
resultSet.getInt("student_id");
String name = resultSet.getString("name");
Date date_of_birth = resultSet.getDate("date_of_birth");
String email = resultSet.getString("email");

System.out.println("Employee ID: " + student_id + " | Name: " +


name + " | Date of Birth: " + date_of_birth + " | Email: " + email);

// Closing the Connection connection.close();


} catch (ClassNotFoundException e) {
System.out.println("Could not find the JDBC driver class.");
e.printStackTrace(); } catch (SQLException e) {
System.out.println("An error occurred while communicating with the database.");
e.printStackTrace();
}
}
}

6) Use preparedStatement to insert, select, update and delete operation

import java.sql.*; class Student{ public static void


main(String args[]){ try {
// Loading the Driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establishing Connection
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/StudentData","root","
");
// Creating a PreparedStatement PreparedStatement preparedStatement
= connection.prepareStatement("INSERT INTO Student (student_id, name,
date_of_birth, email) VALUES (?, ?, ?, ?)");

// Setting the parameters for the PreparedStatement preparedStatement.setInt(1,


23); preparedStatement.setString(2, "loran kylie");
preparedStatement.setDate(3, Date.valueOf("1998-01-07"));
preparedStatement.setString(4, "florian34@yahoo.com");
// Executing the PreparedStatement
int result = preparedStatement.executeUpdate();

// Checking if the insertion was successful if (result == 1)


{
System.out.println("Data inserted successfully.");
}

// Closing the Connection connection.close();


} catch (ClassNotFoundException e) {
System.out.println("Could not find the JDBC driver class.");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("An error occurred while communicating with the database.");
e.printStackTrace();
}
}}

Code for retrieve data

import java.sql.*; class Student{ public static void


main(String args[]){ try {
// Loading the Driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establishing Connection
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/StudentData","root","
");
// Creating a PreparedStatement PreparedStatement preparedStatement =
connection.prepareStatement("SELECT * FROM Student WHERE student_id = ?");
// Setting the parameters for the PreparedStatement preparedStatement.setInt(1,
23);

// Executing the PreparedStatement


ResultSet resultSet = preparedStatement.executeQuery();

// Processing ResultSet while


(resultSet.next()) { int student_id =
resultSet.getInt("student_id");
String name = resultSet.getString("name");
Date date_of_birth = resultSet.getDate("date_of_birth");
String email = resultSet.getString("email");

System.out.println("Student ID: " + student_id + " | Name: " + name + " | Date of Birth:
" + date_of_birth + " | Email: " + email); }
// Closing the Connection connection.close();
} catch (ClassNotFoundException e) {
System.out.println("Could not find the JDBC driver class.");
e.printStackTrace(); } catch (SQLException e) {
System.out.println("An error occurred while communicating with the database.");
e.printStackTrace();
}
}}

7) Use JDBC to perform batch insert, batch update and dynamically insert multiple rows into
your databases.

Code
import java.sql.*; class Student{ public static void
main(String args[]){ try {
// Loading the Driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establishing Connection
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/StudentData","root","
");
// Turning off auto-commit to allow multiple queries in a single transaction
connection.setAutoCommit(false);
// Creating a PreparedStatement PreparedStatement preparedStatement
= connection.prepareStatement("INSERT INTO Student (student_id, name,
date_of_birth, email) VALUES (?, ?, ?, ?)");

// Adding multiple queries to the batch preparedStatement.setInt(1, 34);


preparedStatement.setString(2, "richard madenge"); preparedStatement.setDate(3,
Date.valueOf("1977-05-12")); preparedStatement.setString(4,
"madenge711@gmail.com"); preparedStatement.addBatch();
preparedStatement.setInt(1, 27); preparedStatement.setString(2, "ricahrd
evaristo"); preparedStatement.setDate(3, Date.valueOf("1977-07-11"));
preparedStatement.setString(4, "richardevaristo@gmail.com"); preparedStatement.addBatch();

// Executing the batch int[] results =


preparedStatement.executeBatch();

// Committing the transaction connection.commit();

// Checking if all the inserts were successful for (int result :


results) { if (result == 1) {
System.out.println("Data inserted successfully.");
}
}

// Closing the Connection connection.close();


} catch (ClassNotFoundException e) {
System.out.println("Could not find the JDBC driver class.");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("An error occurred while communicating with the database.");
e.printStackTrace();
}
}
}
Code

import java.sql.*; class Student{ public static void


main(String args[]){ try {
// Loading the Driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Establishing Connection
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/StudentData","root","
");

// Turning off auto-commit to allow multiple queries in a single transaction


connection.setAutoCommit(false);

// Creating a PreparedStatement PreparedStatement preparedStatement =


connection.prepareStatement("UPDATE Student SET name = ? WHERE student_id = ?");

// Adding multiple queries to the batch preparedStatement.setString(1,


"sibomana Karl"); preparedStatement.setInt(2, 27);
preparedStatement.addBatch();

preparedStatement.setString(1, "richard evaristo");


preparedStatement.setInt(2, 34); preparedStatement.addBatch();

// Executing the batch int[] results =


preparedStatement.executeBatch();

// Committing the transaction connection.commit();

// Checking if all the inserts were successful for (int result


: results) { if (result == 1) {
System.out.println("Data updated successfully.");
}
}

// Closing the Connection connection.close();


} catch (ClassNotFoundException e) {
System.out.println("Could not find the JDBC driver class.");
e.printStackTrace(); } catch (SQLException e) {
System.out.println("An error occurred while communicating with the database.");
e.printStackTrace();
}
}
}

LAB ASSIGNMENT 8

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.

ANSWER;
OUTPUT
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. ANSWER; import
java.io.IOException;

// Define superclass ExceptionA inheriting from


Exception class ExceptionA extends Exception {
// Constructor for ExceptionA public
ExceptionA(String message) {
super(message);

// Define subclass ExceptionB inheriting from


ExceptionA class ExceptionB extends

ExceptionA { // Constructor for ExceptionB public


ExceptionB(String message) {

super(message);

}
public class Maini { public static void

main(String[] args) {

try {

// Throw ExceptionA throw new

ExceptionA("This is an ExceptionA");

} catch (Exception exception) {

// Catch all exceptions with type Exception

System.out.println("Caught an Exception: " + exception.getMessage());

t
r
y
{

// Throw ExceptionB throw new

ExceptionB("This is an ExceptionB");

} catch (Exception exception) {

// Catch all exceptions with type Exception

System.out.println("Caught an Exception: " + exception.getMessage());

tr
y
{

// Throw NullPointerException

throw new NullPointerException("This is a NullPointerException");

} catch (Exception exception) {

// Catch all exceptions with type Exception

System.out.println("Caught an Exception: " + exception.getMessage());

}
t
r
y
{

// Throw IOException throw new

IOException("This is an IOException");

} catch (Exception exception) {

// Catch all exceptions with type Exception

System.out.println("Caught an Exception: " + exception.getMessage());

OUTPUT

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

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

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

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

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
OUTPUT

You might also like