Se2 Group9 9
Se2 Group9 9
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.
// Constructor
public VariableDeclaration(){
number = 1;
}
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;
}
employeeObject.setFirstName("GREYSON");
employeeObject.setLastName("shawa"); employeeObject.setSalary(120000);
System.out.println(employeeObject.getFirstName());
System.out.println(employeeObject.getLastName());
System.out.println(employeeObject.getSalary());
object1.setSalary(2000000);
object2.setSalary(400000);
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 = "--
";
}
System.out.println(employee1.name);
System.out.println(employee1.balance);
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 = "--
";
}
employee1.deposite(120000.0);
employee2.deposite(1000000.0);
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++;
}
class Rectangle {
float length, width;
public Rectangle()
{ this.length = 1;
this.width = 1;
}
System.out.println("--------------------------");
rectangle.setLength(4);
rectangle.setWidth(6);
}
}
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;
}
saver1.modifyInterestRate(4);
saver2.modifyInterestRate(4);
saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();
System.out.println("##########");
saver1.modifyInterestRate(5);
saver2.modifyInterestRate(5);
saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();
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. {
10. {
14. System.out.printf(
28. // utility method to confirm proper day value based on month and year
32. { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30,
31, 30, 31 };
33. // check if day in range for month
42. }
45. {
47. }
48. }
49.
53. {
71. }}
72.
73. package solution6;
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;
3. {
10. {
14. System.out.printf(
28. // utility method to confirm proper day value based on month and year
32. { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30,
31, 30, 31 };
33. // check if day in range for month
47. }
48. }
49. package solution6;
59. {
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();
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
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;
}
package Question5; public class Rectangle extends Polygon { public double areaR()
{ return getHeight() * getWidth();
} } package
Question5;
System.out.println("Height = "
+rectangle.height);
System.out.println("\n\"width\" and
\"height\" for the triangle are :");
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;
area();
}
package qn6; public class Rectangle
extends Polygon {
@Override
public double area(){ return
this.height * this.width;
extends Polygon {
}
package qn6; public class MyMain { public static void main(String[] args) {
Rectangle rectangle = new Rectangle(); rectangle.setValues(42, 51);
System.out.println();
System.out.println();
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 Accountant extends Employee {
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) {
System.out.println("Accountant:\t" +
(accountant.salary + accountant.bonusA));
}
class CommissionEmployee extends Object {
private String firstName; private String
lastName; private int
socialSecurityNumber; private double
commissionRate; private double
grossSalesAmount;
}
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;
@Override
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:
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
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);
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();
// 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");
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();
}
}
}
);
NOT NULL
);
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')");
// 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'");
// 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");
// 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 (?, ?, ?, ?)");
// 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);
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 (?, ?, ?, ?)");
LAB ASSIGNMENT 8
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;
super(message);
}
public class Maini { public static void
main(String[] args) {
try {
ExceptionA("This is an ExceptionA");
t
r
y
{
ExceptionB("This is an ExceptionB");
tr
y
{
// Throw NullPointerException
}
t
r
y
{
IOException("This is an IOException");
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
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