Se2 Group4 11
Se2 Group4 11
Se2 Group4 11
• 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.
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.
3. Modify question 2 to allow a user to pass arguments to the methods using Scanner class.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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());}}
LAB PRACTICAL 6:
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.
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.
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.
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.
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.
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.
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.
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;
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 {
SomeClass");
}
}
try {
ourMethod2();
} catch (Exception e) {
System.out.println("Exception caught in ourMethod:");
throw e;
}
}
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.
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.
1. The following diagram shows the relationship between Java code, JDBC API
and Database Driver.
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").
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.
i. INSERTION OPERATION
6. JDBC to perform batch insert, batch update and dynamically insert multiple
rows into your databases.
i. BATCH INSERT