82810_634167223152796250
Transcript of 82810_634167223152796250
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 1 of 68
thi
Lab Guide for Java Programming
CommunicationTeam.org
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 2 of 68
Contents
THICOPYRIGHT NOTICE .................................................................................................. 1
COPYRIGHT NOTICE ............................................................. ERROR! BOOKMARK NOT DEFINED.
DOCUMENT REVISION HISTORY ............................................... ERROR! BOOKMARK NOT DEFINED.
CONTENTS .................................................................................................................. 2
1 CONTEXT ................................................................................................................. 4
2 ASSIGNMENTS FOR DAY 1 JAVA PROGRAMMING ............................................................. 4
ASSIGNMENT 1: OOAD OF TELE-COMMUNICATION COMPANY ............................................................... 4
ASSIGNMENT 2: USAGE OF ARRAY .......................................................................................... 5
ASSIGNMENT 3: MULTI-DIMENSIONAL ARRAYS ............................................................................... 7
ASSIGNMENT 4: CREATING A CLASS AND OBJECT ........................................................................... 9
ASSIGNMENT 5: PROBLEM DESCRIPTION TO JAVA PROGRAM .............................................................. 11
ASSIGNMENT 6: INITIALIZING THE CLASS MEMBER VARIABLES .............................................................. 11
ASSIGNMENT 7: ARCHITECTURAL NEUTRALITY OF JVM ................................................................... 12
ASSIGNMENT 8: UNDERSTANDING CLASSES ................................................................................ 13
ASSIGNMENT 9: METHOD OVERLOADING .................................................................................. 15
ASSIGNMENT 10: UNDERSTANDING CONSTRUCTORS ...................................................................... 18
ASSIGNMENT 10.A: UNDERSTANDING CONSTRUCTORS .................................................................... 18
ASSIGNMENT 10.B: UNDERSTANDING CONSTRUCTORS .................................................................... 20
ASSIGNMENT 10.C: UNDERSTANDING CONSTRUCTORS .................................................................... 22
ASSIGNMENT 10.D: UNDERSTANDING CONSTRUCTORS .................................................................... 23
ASSIGNMENT 11: ARRAYS OF OBJECTS ................................................................................... 25
3 ASSIGNMENTS FOR DAY 2 JAVA PROGRAMMING ........................................................... 27
ASSIGNMENT 12: STATIC CONCEPTS ...................................................................................... 27
ASSIGNMENT 12.A: STATIC CONCEPTS – STATIC VARIABLES ............................................................... 28
ASSIGNMENT 12.B: STATIC CONCEPTS - STATIC BLOCKS ................................................................. 29
ASSIGNMENT 12.C: STATIC CONCEPTS – PRIVATE CONSTRUCTORS AND STATIC METHODS .................................. 29
ASSIGNMENT 13: INHERITANCE ........................................................................................... 31
ASSIGNMENT 14: UNDERSTANDING INHERITANCE ......................................................................... 32
ASSIGNMENT 15: UNDERSTANDING DYNAMIC BINDING .................................................................... 36
ASSIGNMENT 16: UNDERSTANDING ABSTRACT CLASS ...................................................................... 38
ASSIGNMENT 17: UNDERSTANDING DYNAMIC BINDING .................................................................... 41
ASSIGNMENT 18: UNDERSTANDING INTERFACE ............................................................................ 43
ASSIGNMENT 19: UNDERSTANDING PACKAGES ............................................................................ 44
ASSIGNMENT 20: UNDERSTANDING THE ACCESS SPECIFIER ................................................................ 45
ASSIGNMENT 21: GARBAGE COLLECTION ................................................................................. 48
ASSIGNMENT 21A: GARBAGE COLLECTION ................................................................................ 49
ASSIGNMENT 21B: GARBAGE COLLECTION ................................................................................ 50
5 ASSIGNMENTS FOR DAY 3 JAVA PROGRAMMING ........................................................... 51
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 3 of 68
ASSIGNMENT 22: AUTOBOXING AND UNBOXING ........................................................................... 51
ASSIGNMENT 23: UNDERSTANDING EXCEPTION HANDLING (UNCHECKED EXCEPTIONS) .................................... 52
ASSIGNMENT 24: UNDERSTANDING EXCEPTION HANDLING – TRY, CATCH & FINALLY ...................................... 55
ASSIGNMENT 25: UNDERSTANDING EXCEPTION HANDLING (CHECKED EXCEPTIONS) ....................................... 56
ASSIGNMENT 26: UNDERSTANDING USER DEFINED EXCEPTION HANDLING ................................................. 57
3 ASSIGNMENTS FOR DAY 4 JAVA PROGRAMMING ........................................................... 59
ASSIGNMENT 27: JAVABEANS ............................................................................................. 59
ASSIGNMENT 28: CREATING (JAVA BEAN) CLASSES AND OBJECT ......................................................... 60
ASSIGNMENT 29: USAGE OF „THIS‟ KEYWORD ............................................................................. 63
ASSIGNMENT 30: UNDERSTANDING COLLECTION FRAMEWORK ............................................................ 65
ASSIGNMENT 31: REFLECTION API ....................................................................................... 65
ASSIGNMENT 32: ANNOTATIONS .......................................................................................... 67
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 4 of 68
1 Context
This document contains assignments to be completed as part of the hands on for the subject
Java programming
In order to complete the course, assignments in this document must be completed in
the sequence mentioned.
Create a workspace on your desktop with the name “Java” for the assignments.
Under the “Java” folder,create project with names depending upon the day of
assignment. If it is day 1 , create a project with the name “day1” in the “Java”
workspace. Now for every assignment create a separate package. If some assignment
requires multiple packages ( as in case of package assignments ) then create the
nested packages. For example , assume your assignment is “assignment1” and you
need to create two packages in this assignment ( “pack1” and “pack2” ) then you will
be creating two packages with names “pack1” and “pack2” under package
“assignment1”.
2 Assignments for Day 1 Java Programming
Assignment 1: OOAD of Tele-Communication Company
A telecom company wants to automate their process of giving mobile and internet
connections and bill generation. The company has a set of customers. Each customer has a
unique Customer ID, name and address.
Telecom company offers two types of plans for their customers:
a) Mobile Plans
b) Internet Plans
Mobile Plans can be of two types: Pre-paid or Post-paid.
Internet Plans can also be of two types: Business Plan and Home Plan.
A customer can have multiple plans. When the customer opts for a plan, he will be given a
unique user-id and password for the specific plan. Bill should be generated at the end of
every month for every customer.
Identify the classes for the above problem.
Solution:
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 5 of 68
Assignment 2: Usage of array
Objective: To understand the usage of array.
Problem Description: To calculate the feedback of 5 employees and grade them according to their feedback. Estimated time: 20 Mins.
Step 1: Create a package for the assignment.
Step 2: Open a Eclipse ganymede IDE and create a java file with the name EmployeeGrade
:
Filename EmployeeGrade.java
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 6 of 68
/*
* This java file is a program to calculate the average feedback
* of 5 employees and determine their grade
*/
/**
* This class will display the grade of 5 employees according
* to their feedback.
* Date : <<Replace with the date you do this assignment>>
* @author <<Replace with your Emp No. & Name>>
* @version 1.0
*/
public class EmployeeGrade {
/**
* Calculates the average feedback of 5 employees and determines
* their grade
* @param args: Command line arguments
*/
public static void main (String [] args) {
//To-do: Calculate the average feedback of all the
employees
//To-do: Determine the grade of all the employees
}
}
Save the file as „EmployeeGrade.java‟.
Follow the below mentioned steps to complete the program
Step 3: Inside the main method, declare 4 arrays for storing the employee numbers,
customer1Feedback, customer2Feedback and customer3Feedback of 5 employees. Initialize
them to any value.
For e.g.
int employeeId[]={1001,1002,1003,1004,1005};
float customer1Feedback[]={4.1f, 3.8f, 4.5f, 4.9f, 3.9f};
Assume employeeId[0] i.e. 1001 has customer 1 feedback as
customer1Feedback[0] i.e. 4.1 and so on
Step 4: Declare a float array averageFeedback [] to store the average feedback of all the
employees.
Step 5: Declare a char array grade [] to store the grade of all the employees.
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 7 of 68
Step 6: Calculate the average feedback and determine the grade . Store the average
feedback of all the employees in averageFeedback [] array and the grades in grade[] array.
Use looping control statements to access the values from the arrays.
Step 7: Display the employee number, average feedback and grade of all the employees.
Step 8: Compile EmployeeGrade.java. Resolve the errors if any, and recompile the program.
Step 9: Execute EmployeeGrade.java.
Summary of this exercise:
You have just learnt
To declare, initialize and access arrays.
To use looping control statements.
Assignment 3: Multi-dimensional Arrays
Objective: To understand the two-dimensional arrays. Problem Description: Create a class EmployeeFeedback that stores the employee number and the feedback from their customers. Note: Not necessarily, all the employees would have the same number of customers. Estimated time: 15 Mins.
Step 1: Create a package for the assignment.
Step 2: Open Eclipse ganymede IDE and type the following:
Filename EmployeeFeedback.java
/*
* This java file is a program to store and display the employee
* number and their feedback from the customer.
*/
/**
* This class will display the feedback of all the employees
* Date : <<Replace with the date you do this assignment>>
* @author <<Replace with your Emp No. & Name>>
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 8 of 68
* @version 1.0
*/
public class EmployeeFeedback {
/**
* Stores and displays the feedback of the employees from their
* customer
* @param args: Command line arguments
*/
public static void main (String [] args) {
int [][]empInfo = {{1001,4,5}, {1002,2,4,5}};
for (int outerLoop=0;outerLoop<2;outerLoop++) {
for (int innerLoop=0;innerLoop<3;innerLoop++) {
System.out.println(empInfo[outerLoop][innerLoop]);
}
}
}
}
Save the file as „EmployeeFeedback.java‟
Step 3: Compile and execute the code.
Now, 1001 has feedback from 2 customers and 1002 has feedback from 3
customers. Do you get to display all the values? You would get run-time
exception, if you try to change the upper limit of the array from 3 to 4.
(Analyze and find out the reason). Now, instead of mentioning the constant
as upper limit for the array, use the length property.
for (int outerLoop=0;outerLoop<empInfo.length;outerLoop++)
{
for (int innerLoop=0;innerLoop<empInfo[outerLoop].length;
innerLoop++)
{
System.out.println(empInfo[outerLoop][innerLoop]);
}
}
Step 4: Do the modification in the program, compile and execute the code.
Summary of this exercise:
You have learnt
Usage of length property of array
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 9 of 68
In java, the best practice is always to use the length property instead of the constant
as value for upper limit of the array.
Assignment 4: Creating a Class and Object
Objective: To understand how to create a class and instantiate it. Problem Description: Create a class Customer with instance variables customerID, customerName, address and pinCode. Estimated time: 15 Mins. Step 1: Create a package for the assignment. Step 2: Open Eclipse ganymede IDE and type the following:
/*
* This java file is a demo Java program which depicts a class
* with a main method inside and necessary instance variables
*/
/**
* This class is template to create Customer Object.
* Date : <<Replace with the date you do this assignment>>
* @author <<Replace with your Emp No. & Name>>
* @version 1.0
*/
public class Customer {
private String customerID;
private String customerName;
private String address;
private int pinCode;
/**
* This method creates an object of Customer Class and sets its
*instance variable and display the same.
* @param args The command line arguments
*/
public static void main (String [] args){
Customer customer = new Customer(); //statement 1
customer.customerID = “1234”; //statement 2
customer.customerName = “Jayant”; //statement 3
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 10 of 68
customer.address = “PHA-Sawan Apts., Yadavgiri, Hyderabad”;
//statement 4
customer.pinCode = 570020; //statement 5
System.out.println(“Customer ID ” + customer.customerID);
System.out.println(“Customer Name ” + customer.customerName);
System.out.println(“Customer Address ” + customer.address);
System.out.println(“Customer Pin Code ” + customer.pinCode);
}
}
Save the file as : Sample.java
Step 2: Compile the program. Read the error reported and fix it (refer to the Note given below).
1. In a java file, if the class is declared as public, the name of the
class and the name of the file should be the same (including the
case).
2. The main() method is the starting point of the program. It is not
mandatory for all the classes to have the main() method. The class
with main() method is called „Starter class‟.
Step 3: Execute the program. Step 4: In the above code main method is a part of Customer class. Step 5: Try to understand the program.
Statement 1: Creates an instance of type Customer and the instance is
assigned to the reference variable “customer”. (More about this on Day 2)
Statement 2…5: Using the reference variable assigning value to the member
variable of the class (similar to structure concept in C)
The following statements retrieve the values assigned to the member
variables and display it.
This exercise is just for demo purpose. The program does not adhere to
the OO concepts.
Summary of this exercise:
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 11 of 68
You have just learnt
Creating object of a class
How to access instance variables of an object
Assignment 5: Problem Description to Java Program
CityBank is a multinational private bank. CommunicationTeam employees can open a bank account in CityBank on the day of their joining. Account can be of two types (1) Salary Account and (2) Non Salary Account. For non salary account the minimum bank balance should be Rs 10,000/-. There are different privilege levels (shown in the table below) available on both the accounts.
Type of
customer
Privileges
Salary Non-salary
Multi city cheque book No No
Discount on shopping using
debit card
No Yes
ATM card Yes Yes
The application is used by the clerk of the bank. On allocating it should return a customer id and Account Number. To open a bank account following details are required by the bank: 1 Applicant first, middle and last name 2. Email-id 3. Account Type 4. Date of Birth 5. Gender (M/F) 6. Marital status (Single / Married) Write a program in Java to represent the above description.
Assignment 6: Initializing the class member variables
Modify the above program to get the new account number for the following new employees of CommunicationTeam:
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 12 of 68
Employee 1: Employee 2:
Name
First: Paul Middle: J Last: Anderson
First: John Middle: Last: Jacob
Date of Birth 3rd Jan,1985 6th March, 1985
Email-id [email protected] [email protected]
Account Type Salary Non-Salary
Gender M M
Marital Status Single Married
Hint: A constructor can be used to initialize class member variables.
Assignment 7: Architectural neutrality of JVM CityBank software is made to be deployed on different architectures. Fill out the below diagram to complete depict the flow of deploying InyBank software which is written in Java.
A .class files
.java files
B1 B2 B3
Q1. What is done in Step A to get .class files?
Q2. .class files are also known as __________? Are the .class files platform independent (Yes/No)?
Q3. Which software is used at B1, B2, B3 to deploy CityBank software? Is the software platform independent (Yes/No)?
Apple
Machine
Windows
Machine
Unix
Machin
e
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 13 of 68
Assignment 8: Understanding Classes
Problem Description: Create a class to store the employee information and calculate the average feedback and grade based on their feedback. Create the starter class to instantiate the employee and invoke the methods. Estimated time: 15 Mins.
Step 1: Create the class EmployeeGrade according to the below given class diagram.
EmployeeGrade
- employeeNo : int
- employeeName : String
- customer1Feedback: float
- customer2Feedback: float
- customer3Feedback: float
- averageFeedback : float
- grade : char
+ initializeEmployee(int employeeNo, String
employeeName, float customer1Feedback, float
customer2Feedback, float customer3Feedback) : void
+ calculateAverageFeedback() : void
+ calculateGrade() : void
+ displayInfo() : void
initializeEmployee(..) : This method initialize employee No, name, feedback
from 3 customers to the member variables. Remember to use „this‟.
calculateAverageFeedback() : This method calculates the average of the 3
feedback and store it in the corresponding member variable.
calculateGrade() : This method calculates the grade for the employee based
on his average feedback. displayInfo(): This method displays the
employeeNo, name, average feedback and the grade of the employee.
Step 2: Save the class under the package of the assignment and compile the program. Fix the
errors, if any.
Step 3: create a starter class with the name City as given below.
Filename City.java
/*
* This java file is a starter class which instantiates EmployeeGrade
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 14 of 68
* Calls the corresponding methods to initialize the values
* Calculate the average feedback and the grade
* Display the information
*/
/**
* This class is a starter classes that instantiate the EmployeeGrade.
* Using the instance, the class should call the corresponding methods
* to calculate the average feedback and grade.
* Display the information.
* Date : <<Replace with the date you do this assignment>>
* @author <<Replace with your Emp No. & Name>>
* @version 1.0
*/
public class City {
/**
* Instantiate the EmployeeGrade. Set the values for the member
* variables and invoke the method to calculate the average feedback
* and grade. Invoke the method to display the employee information.
* @param args The command line arguments
*/
public static void main (String[] args) {
// To-do: Create an instance (Elvis) for EmployeeGrade class.
// To-do: Invoke methods for calculating Avg feedback & grade
// To-do: Invoke method to display the employee information
}
}
Save the file as : City.java.
Step 4: Compile City.java. Fix the errors, if any.
Step 5: Execute City.java. Check the output.
The program displays the default value for all the member variables. The
reason being, the main() of the starter class has not invoked the method that
initializes the member variables.
The default constructor for EmployeeGrade has not been defined. Hence the
compiler adds the „default constructor‟ and initializes the variables to the
default value, based on their data type.
Step 6: Modify the main() in City.java to invoke the method that initializes the member
variables, before invoking the method that calculates the average feedback and grade.
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 15 of 68
Step 7: Compile City.java and execute the program. It should display the information about
the employee.
Summary of this exercise:
You have learnt
Initializing the member variables using user-defined methods.
If the constructor is not defined in the program, the system automatically provides
the default constructor and initializes the member variables with default values based
on the data type.
If the member variables are not initialized through the constructor, the programmer
should invoke the method that initializes the member variables, if defined.
Assignment 9: Method Overloading
Problem Description: Create a class to store the employee information and calculate the average feedback and grade based on their feedback. Create the starter class to instantiate the employee and invoke the methods. Estimated time: 15 Mins.
Step 1: Create the class EmployeeGrade according to the below given class diagram.
EmployeeGrade
- employeeNo : int
- employeeName : String
- customer1Feedback: float
- customer2Feedback: float
- customer3Feedback: float
- averageFeedback : float
- grade : char
+ initializeEmployee(int employeeNo, String
employeeName, float customer1Feedback, float
customer2Feedback, float customer3Feedback) : void
+ initializeEmployee(int employeeNo, String
employeeName, float customer1Feedback, float
customer2Feedback) : void
+ calculateAverageFeedback() : void
+ calculateGrade() : void
+ displayInfo() : void
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 16 of 68
initializeEmployee(int employeeNo, String employeeName, float
customer1Feedback, float customer2Feedback, float customer3Feedback)
This method initialize employee No, name, feedback from 3 customers to
the member variables. Remember to use „this‟.
initializeEmployee(int employeeNo, String employeeName, float
customer1Feedback, float customer2Feedback) This method initialize
employee No, name, feedback from 2 customers to the member variables.
Remember to use „this‟.
calculateAverageFeedback() : This method calculates the average of the
available feedback and store it in the corresponding member variable
calculateGrade() : This method calculates the grade for the employee based
on his average feedback. displayInfo(): This method displays the
employeeNo, name, average feedback and the grade of the employee.
Step 2: Save the class under the package of this assignment and compile the program. Fix the
errors, if any.
Step 3: create a starter class with the name City as given below, under the package.
Filename City.java
/*
* This java file is a starter class which instantiates EmployeeGrade
* Calls the corresponding methods to initialize the values
* Calculate the average feedback and the grade
* Display the information
*/
/**
* This class is a starter classes that instantiate the EmployeeGrade.
* Using the instance, the class should call the corresponding methods
* to calculate the average feedback and grade.
* Display the information.
* Date : <<Replace with the date you do this assignment>>
* @author <<Replace with your Emp No. & Name>>
* @version 1.0
*/
public class City {
/**
* Instantiate the EmployeeGrade. Set the values for the member
* variables and invoke the method to calculate the average feedback
* and grade. Invoke the method to display the employee information.
* @param args The command line arguments
*/
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 17 of 68
public static void main (String[] args) {
// To-do: Create an instance (Elvis) for EmployeeGrade class.
// To-do: Invoke methods for calculating Avg feedback & grade
// To-do: Invoke method to display the employee information
// To-do: Create an instance (Martha) for EmployeeGrade class.
// To-do: Invoke methods for calculating Avg feedback & grade
// To-do: Invoke method to display the employee information
}
}
Save the file as : City.java.
Step 4: Compile City.java. Fix the errors, if any.
Step 5: Execute City.java. Check the output.
Now, open the City.java and modify the program to invoke the method that
initializes the member variables, before invoking the method to calculate the
average feedback and grade, as given in step 6.
Step 6: Call the initializeEmployee method for Elvis as well Martha. All the 3 customers have
given the feedback for Elvis as 4.1, 3,9 and 4.2. But only 2 customers have given the feedback
for Martha as 4.2 and 4.4. Alter the main() method of City.java program as follows.
public static void main (String[] args) {
// To-do: Create an instance (Elvis) for EmployeeGrade class
// To-do: Call the initializeEmployee with 3 feedback
// To-do: Invoke methods for calculating Avg feedback & grade
// To-do: Invoke method to display the employee information
// To-do: Create an instance (Elvis) for EmployeeGrade class
// To-do: Call the initializeEmployee with 2 feedback
// To-do: Invoke methods for calculating Avg feedback & grade
// To-do: Invoke method to display the employee information
}
Step 7: Compile City.java and execute the program. It should display the information about
the employee.
Summary of this exercise:
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 18 of 68
You have learnt
Initializing the member variables using user-defined methods.
If the constructor is not defined in the program, the system automatically provides
the default constructor and initializes the member variables with default values based
on the data type.
If the member variables are not initialized through the constructor, the programmer
should invoke the method that initializes the member variables, if defined.
The methods can be overloaded. If overloaded, the compiler decides the method to
be executed based on the method signature.
Assignment 10: Understanding Constructors
Objective: To understand the usage and the implementation of constructors.
Assignment 10.a: Understanding Constructors
Problem Description: Create a class to store the employee information and calculate the average feedback and grade based on their feedback. Use the constructor to initialize the member variables. Create the starter class to instantiate the employee and invoke the methods. Estimated time: 15 Mins.
Step 1: Create the class EmployeeGrade under the package based on the below given class
diagram.
EmployeeGrade
- employeeNo : int
- employeeName : String
- customer1Feedback: float
- customer2Feedback: float
- customer3Feedback: float
- averageFeedback : float
- grade : char
+ EmployeeGrade()
+ calculateAverageFeedback() : void
+ calculateGrade() : void
+ displayInfo() : void
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 19 of 68
EmployeeGrade() : This is the default constructor which initializes the
member variables with values as follows.
Employee No :101, Name: “Ram”, customer1Feedback: 4.1f,
customer2Feedback: 4.0f, customer3Feedback: 4.3f
Step 2: Compile EmployeeGrade and fix the errors, if any.
Step 3: Create a starter class with the name City as given below.
Filename City.java
/*
* This java file is a starter class which instantiates EmployeeGrade.
* Calculate the average feedback and the grade
* Display the information
*/
/**
* This class is a starter classes that instantiate the EmployeeGrade.
* Using the instance, the class should call the corresponding methods
* to calculate the average feedback and grade.
* Display the information.
* Date : <<Replace with the date you do this assignment>>
* @author <<Replace with your Emp No. & Name>>
* @version 1.0
*/
public class City {
/**
* Instantiate the EmployeeGrade. Set the values for the member
* variables and invoke the method to calculate the average
* feedback and grade. Invoke the method to display the employee
* information.
* @param args The command line arguments
*/
public static void main (String[] args) {
// To-do: Create instance(ram) for EmployeeGrade.
// To-do: Invoke methods for calculating Avg feedback & grade
// To-do: Invoke method to display the employee information
}
}
Save the file as : City.java.
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 20 of 68
Step 4: Compile City.java. Fix the errors, if any.
Step 5: Execute City.java. Check the output. It should display the information about
employee 101.
If the default constructor is defined for initializing the values, you need not
explicitly invoke any method to initialize the values.
But when the default constructor is used to initialize the values like shown in
the exercise, every instance is initialized with same values!
Summary of this exercise:
You have learnt
Initializing the member variables within default constructor.
If initialized within constructor, need not explicitly invoke any method to initialize.
The same values are initialized to all the instances.
Assignment 10.b: Understanding Constructors
Problem Description: Create a class to store the employee information and calculate the average feedback and grade based on their feedback. Use the constructor to initialize the member variables. Create the starter class to instantiate the employee and invoke the methods. Estimated time: 15 Mins.
Step 1: Make a copy of EmployeeGrade of Assignment 10.a, under the package of this
assignment. Modify the EmployeeGrade according to the below given class diagram.
EmployeeGrade
- employeeNo : int
- employeeName : String
- customer1Feedback: float
- customer2Feedback: float
- customer3Feedback: float
- averageFeedback : float
- grade : char
+ EmployeeGrade()
+ EmployeeGrade(int employeeNo, String
employeeName, float customer1Feedback, float
customer2Feedback, float customer3Feedback)
+ calculateAverageFeedback() : void
+ calculateGrade() : void
+ displayInfo() : void
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 21 of 68
EmployeeGrade() : This is the default constructor which initializes the
member variables to their default values, based on the data type of the
variable.
EmployeeGrade(int employeeNo, String employeeName, float
customer1Feedback, float customer2Feedback, float customer3Feedback)
: This is the overloaded constructor, which initializes the member variables
with the values being passed as parameter.
Step 2: Compile EmployeeGrade and fix the errors, if any.
Step 3: Create a starter class with the name City as given below.
Filename City.java
/*
* This java file is a starter class which instantiates EmployeeGrade.
* Calculate the average feedback and the grade
* Display the information
*/
/**
* This class is a starter classes that instantiate the EmployeeGrade.
* Using the instance, the class should call the corresponding methods
* to calculate the average feedback and grade.
* Display the information.
* Date : <<Replace with the date you do this assignment>>
* @author <<Replace with your Emp No. & Name>>
* @version 1.0
*/
public class City {
/**
* Instantiate the EmployeeGrade. Set the values for the member
* variables and invoke the method to calculate the average
* feedback and grade. Invoke the method to display the employee
* information.
* @param args The command line arguments
*/
public static void main (String[] args) {
EmployeeGrade ram = new EmployeeGrade();
EmployeeGrade james = new
EmployeeGrade(102,”James”,4.2f,4.4f,4,1f);
// To-do: Invoke methods for calculating Avg feedback & grade
for both the employees
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 22 of 68
// To-do: Invoke method to display the employee information
for both the employees
}
}
Save the file as : City.java
Step 4: Compile City.java. Fix the errors, if any.
Step 5: Execute City.java. Analyze the output.
Summary of this exercise:
You have learnt
Initializing the member variables within default constructor.
Initializing the member variables using overloaded constructor.
Assignment 10.c: Understanding Constructors
Problem Description: Create a class to store the employee information and calculate the average feedback and the grade based on their feedback. Use the constructor to initialize the member variables. Creating the starter class to instantiate the EmployeeGrade and invoke the methods. - Estimated time: 15 Mins.
Step 1: Make a copy of EmployeeGrade of Assignment 10.b, under the package of this
assignment.
Step 2: Modify the EmployeeGrade.java by commenting the default constructor of the
EmployeeGrade class.
Step 3: Save the program and compile it. Fix the errors, if any.
Step 4: In City.java, comment the instance „ram‟ and all the statements that invoke the
methods through the instance ram.
/*
* This java file is a starter class which instantiates EmployeeGrade.
* Calculate the average feedback and the grade
* Display the information
*/
/**
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 23 of 68
* This class is a starter classes that instantiate the EmployeeGrade.
* Using the instance, the class should call the corresponding methods
* to calculate the average feedback and grade.
* Display the information.
* Date : <<Replace with the date you do this assignment>>
* @author <<Replace with your Emp No. & Name>>
* @version 1.0
*/
public class City {
/**
* Instantiate the EmployeeGrade. Set the values for the member
* variables and invoke the method to calculate the average
* feedback and grade. Invoke the method to display the employee
* information.
* @param args The command line arguments
*/
public static void main (String[] args) {
//EmployeeGrade ram = new EmployeeGrade();
EmployeeGrade james = new
EmployeeGrade(102,”James”,4.2f,4.4f,4,1f);
// To-do: Invoke methods for calculating Avg feedback & grade
for „james‟ alone
// To-do: Invoke method to display the employee information
for „james‟ alone
}
}
Save the program.
Step 5: Compile the program. Fix the errors, if any
Step 6: Execute the program.
Summary of this exercise:
You have learnt
Initializing the member variables using the overloaded constructor, without defining
the default constructor.
Assignment 10.d: Understanding Constructors
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 24 of 68
Problem Description: Create a class to store the employee information and calculate the average feedback and grade based on their feedback. Use the constructor to initialize the member variables. Creating the starter class to instantiate the employee and invoke the methods. Estimated time: 15 Mins.
Step 1: Make a copy of EmployeeGrade.java and City.java of Assignment 10.c, under the
package of this assignment.
Step 2: Modify City.java by removing the comment for the statement that creates an instance
for „ram‟, as given below.
/*
* This java file is a starter class which instantiates EmployeeGrade.
* Calculate the average feedback and the grade
* Display the information
*/
/**
* This class is a starter class that instantiates the EmployeeGrade.
* Using the instance, the class should call the corresponding methods
* to calculate the average feedback and grade.
* Displays the information.
* Date : <<Replace with the date you do this assignment>>
* @author <<Replace with your Emp No. & Name>>
* @version 1.0
*/
public class City {
/**
* Instantiate the EmployeeGrade. Set the values for the member
* variables and invoke the method to calculate the average
* feedback and grade. Invoke the method to display the employee
* information.
* @param args The command line arguments
*/
public static void main (String[] args) {
EmployeeGrade ram = new EmployeeGrade();
EmployeeGrade james = new
EmployeeGrade(102,”James”,4.2f,4.4f,4,1f);
// To-do: Invoke methods for calculating Avg feedback & grade
for „James‟ alone
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 25 of 68
// To-do: Invoke method to display the employee information
for „James‟ alone
}
}
Save the program.
Step 3: Compile the program. Look into the compilation error and understand the reason.
The compiler would provide the default constructor, only if no other
constructors are defined in the program.
Here, the program has defined the overloaded constructor. So, the system
doesn‟t generate the default constructor. When you try to call the default
constructor, it would throw an error that there is no default constructor.
Remove the comment for the default constructor in the class
EmployeeGrade. Compile the code. Execute City.java
Summary of this exercise:
You have learnt
When the parameterized constructors are defined but not the default constructor, if
you try to invoke the default constructor, you would get compilation error.
Assignment 11: Arrays of Objects
Objective: To understand how to create and use arrays of objects.
Problem Description: Create a class that stores information about employees and calculates their grades according to the feedbacks. Use EmployeeGrade class created in Assignment 10.b. Estimated time: 15 Mins.
When the grade is to be determined for just 2 or 3 employees, separate
objects can be created. But what if there are more than 10 or 20 employees.
It is not feasible to create separate objects. That‟s where array of objects is
used.
Step 1: Make a Copy of EmployeeGrade.java from Assignment 10.b under the package of this
assignment.
Step 2: Create City.java under the current package, which creates array of objects for
EmployeeGrade, so that the employee grade can be calculated for any number of employees.
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 26 of 68
Filename City.java
/*
* This java file is a starter class which instantiates EmployeeGrade.
* Calculates and displays the average feedback and the grade
*/
/**
* This class is a starter classes that instantiate the EmployeeGrade.
* Using the instance, the class should call the corresponding methods
* to calculate the average feedback and grade.
* Display the information.
* Date : <<Replace with the date you do this assignment>>
* @author <<Replace with your Emp No. & Name>>
* @version 1.0
*/
public class City {
/**
* Calculates the average feedback of employees and determines
* the grade.
* @param args: Command line arguments
*/
public static void main (String [] args) {
// create an array of 5 references of EmployeeGrade class
EmployeeGrade [] employee = new EmployeeGrade[5];
// To-do: Initialize the references by calling the
parameterized constructor.
// To-do: Call the corresponding methods to calculate
average feedback and grade for all the 5 employees.
// To-do: Display the details for all the 5 employees
}
}
Save the file as „City.java‟
Step 3: Compile the program. Fix the errors, if any
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 27 of 68
When an array of objects are created like below,
EmployeeGrade [] employeeGrade=new EmployeeGrade[10];
they are references pointing to null. To create objects, the constructor
should be called on every index of the array as given below, after declaring
the array.
for(int loop=0;loop<employees.length;loop++) {
employeeGrade [loop]=new EmployeeGrade (..); //invokes the overloaded
constructor
}
The above code creates actual objects of the EmployeeGrade class.
Step 4: Execute the program.
Summary of this exercise:
You have just learnt
To create and use array of objects
---Solve Self Review Questions------------------------------------------------------------------------------
3 Assignments for Day 2 Java Programming
Assignment 12: Static Concepts
Objective: To understand how to create static variables, static blocks and methods and how
to create objects for classes having private constructors, outside the class Problem Description: Create a Loan class for the class diagram shown Estimated time: 15 Mins.
Loan
- loanNo : int
- accountNo : int
- customerNo: int
- loanAmount: float
- loanDuration: int
- interest : float
+Loan()
+Loan(int accountNo , int customerNo,int
loanDuration ,float loanAmount, float interest)
+calculateInstallments() : float
+getAccountNo() : int
+getCustomerno() : int
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 28 of 68
+getLoanAmount() : float
+getInterest() : float
+getInterest() : float
+setAccountNo(int accountNo) : void
+setCustomerNo(int customerNo) : void
+setLoanDuration(int loanDuration) : void
+setLoanAmount(float loanAmount) : void
+setInterest(float interest) : void
Assignment 12.a: Static Concepts – static variables
Objective: To understand how to create static variables and their usage.
Problem Description: To count the number of instances(Objects created) using static variable Estimated time: 15 Mins.
Step 1: Add a static variable loanCounter to the Loan class.
Step 2: In both the constructors of the loan class add the following statement
Step 3: In the main method of the loan class create some instances of the class loan using
both default and overloaded constructors( may be five or six instances).
Step 4: In the main method of the loan class after creating the instances add the following
statement.
Step 5: Compile and execute the program
Summary of this exercise:
You have just learnt
How to create static variables
//To count the total number of instances
loanCounter++;
//To print the count of instances created in the main method
System.out.println("Number of instances :"+loanCounter);
//loanCounter counts the total number of objects
static int loanCounter;
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 29 of 68
Assignment 12.b: Static Concepts - static blocks
Objective: To understand how to use of static blocks.
Problem Description: To count the number of instances (Objects created) using static variable Estimated time: 15 Mins.
Step 1: Now assume that 100 users have already visited the class. Now the count will start from 101. Use static block to initialize the loanCounter variable to 101.
Step 3: In the main method of the loan class create some instances of the class loan using
both default and overloaded constructors ( may be five or six instances).
Step 4: In the main method of the loan class after creating the instances, add the
following statement.
Step 5: Compile and execute the program
Summary of this exercise:
You have just learnt
How to create static variables
Assignment 12.c: Static Concepts – private constructors and static methods
Objective: To understand static methods to create objects for the class having private
constructors
Problem Description: To create objects of a class having private constructors outside the class Estimated time: 20 Mins.
Step 1: Modify the above class and make the both the constructors as private. Also remove
the main method of the loan class. Create one more class TestLoan.java like this
//To print the count of instances created in the main method
System.out.println("Number of Objects :"+loanCounter);
public class TestLoan {
public static void main(String[] args) {
//To-Do: create the instances of the Loan class
System.out.println("Total number of objects :" +
Loan.loanCounter);
}
}
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 30 of 68
Step 2: Compile and execute the above class
Above code will not compile as the object of a class cannot be created
outside the class if the constructors are private. Static methods can be used
to create objects for the classes having private constructors
Step 3: Add a static method to the Loan class as shown. Replace the To-Do comments with
the code
Step 4: Modify the TestLoan.java class so that the instances of Loan class are created using
the getLoanInstance() static method .
Step 5: Modify the Loan.java class to make the loanCounter variable as private.
Step 6: Save the Loan class and again compile the TestLoan.java class
Since the loanCounter variable is private now it cannot be accessed outside
the class.
Step 7: Create a method getNumberOfObjects() in the Loan class that will return the
number of objects created of Loan class.
Step 8: Modify the TesLoan.java such that , instead of Loan.loanCounter use
getNumberOfObejcts() method in the SOP statement .
public static Loan getLoanInstance(){
//To-Do: create the object of loan class and return it
}
public class TestLoan {
public static void main(String[] args) {
//To-Do: create the instances of the Loan class using
getInstance() method of Loan class
System.out.println("Total number of objects :" +
Loan.loanCounter);
}
}
public int getNumberOfObjects(){
return loanCounter;
}
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 31 of 68
Now one thing has to be decided whether to make the getNumberOfObjects()
method as static or not
Summary of this exercise:
You have just learnt
Static variables and static blocks and their use
Static methods and their use
Assignment 13: Inheritance
Objective: To understand the concept of inheritance
Problem Description: CityBank wants to automate their services to the customers. Bank allows the customers to hold either a Savings Account or Overdraft Account. The account number, customer details, balance for both savings account and the overdraft account should be stored. The customer has to maintain a minimum balance of Rs. 500 in his/her Savings Account. The bank pays an interest of 12% on the balance available in the Savings Account. The bank would fix the overdraft amount for the individuals who possess the Overdraft Account. Hence, the customer who possesses Overdraft Account can withdraw the balance he/she has in their account as well as the overdraft amount fixed for them. Say, if the customer has a balance of Rs. 10000 and the overdraft amount fixed is Rs. 5000, then the customer is eligible to withdraw up to Rs. 15000. The bank wants to automate the deposit, withdraw and the balance enquiry on both the account. The bank also wants to automate the interest calculation for the savings account. Identify the classes to be designed Find the relationship between the classes Identify the member variables and methods of the classes Implement the classes and their methods
Estimated time: 45 Mins.
First three parts of the problem are already implemented in the next section
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 32 of 68
Assignment 14: Understanding Inheritance
Objective: To understand how to design and implement inheritance.
Problem Description: For the Scenario given as part of Assignment 18, identify, design and implement the various classes. Estimated time: 30 Mins. Step 1: Identify the classes. Identify the classes. Generalization can be applied on Savings
Account and Current Account, which leads to a super class “Account”. All the properties and functionalities that are common to the Savings Account and Current Account would become part of “Account” class. Hence we derive the concept of Inheritance with “Account” being the super class and “SavingsAccount” and “CurrentAccount” being the sub classess. The Account has the
customer details, account number, balance. Hence Customer becomes part of Account class.
Step 2: Design the classes. Below is the class design for Customer and Account.
Customer
- customerId : int
- customerName : String
- customerAddress : String
- pincode : int
+ Customer()
+ Customer(int customerId, String customerName,
String customerAddress, int pincode)
+ setCustomerId(int customerId) : void
+ getCustomerId() : int
+ setCustomerName(String customerName) : void
+ getCustomerName() : String
+ setCustomerAddress(String customerAddress) : void
+ getCustomerAddress() : String
+ setPincode(int pincode) : void
+ getPincode() : int
As you can see the customer is a part of the account class. So customer‟s relation must be shown in the account class. Note the an instance variable of type customer to relate customer to Account class.
Account
- accountNo : int
- customer : Customer
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 33 of 68
# balance : double
+ Account()
+ Account(int accountNo, Customer customer,
double balance)
+ getCustomer() : Customer
+ balanceEnquiry() : double
+ deposit(double amount) : void
balanceEnquiry(): double
The method returns the balance available in the account.
deposit(double amount): void
The method updates the available balance.
Within all the constructor of all the classes in this assignment, display a
unique message, so that you can understand the execution sequence
of the constructors better.
Step 4: Design the Sub classes.
The SavingsAccount and CurrentAccount would be subclasses for the Account class. The
savings account has minimum balance to be maintained and also provides interest at the rate of
12% to the customers. Current account can no minimum balance limit the balance can go even
negative, but it does not provide any interest rate. Also the account cannot go beyond the
negative balance of 10000
SavingsAccount
- minimumBalance: double
- interestRate: int
+ SavingsAccount()
+ SavingsAccount(int accountNo, Customer
customer, double balance)
+ withdraw(double amount) : void
+ calculateInterest(): void
minimumBalance
Initialize the member variable minimumBalance member variable
with 500.
interestRate
Initialize the member variable to 12
SavingsAccount(int accountNo, Customer customer, double balance)
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 34 of 68
Call the super class constructor.
withdraw(double amount): void
The method should check whether the account would have the
minimum balance after the withdraw operation. If available, then
update the balance (belonging to Account class). If the sufficient
balance is not available, display an appropriate message.
calculateInterest(): double
The method should calculate the interest for the available balance.
(For simplicity, the interest is calculated for the available balance,
instead of the average of the balance for a period of time)
CurrentAccount
- CurrentAmount: double
CurrentAccount() + CurrentAccount(int accountNo, Customer customer, double balance, double currentAmount) + withdraw(double amount) : void
+ getEligiblityAmount(): double
CurrentAccount(int accountNo, Customer customer, double balance, double currentAmount)
Call the super class constructor and then initializes the currentAmount member variable with the value passed as parameter
withdraw(double amount) The method should check for sufficient balance, by checking whether the amount to be withdrawn is less than or equal to the amount available and the allowed negative amount, the customer is eligible for. If available, withdraw the amount and update the balance. If the sufficient balance is not available, display an appropriate message.For e.g., say if the customer has a balance of Rs. 10000 and he is eligible for negative balance of 10000, then he can withdrew maximum of Rs.20000 (available balance + Eligible Negative amount). If the withdraw amount is Rs. 15000, then the balance available would be – 5000. Then again he is allowed to withdraw 5000 after which his account will show insufficient balance.
getEligiblityAmount(): double The method would return the negative amount the customer is eligible for.
Step 3: Implement the Customer, Account, SavingsAccount and CurrentAccount as per the
design.
Step 4: Implement the starter class. Save the starter class as “CityBank.java”
Filename CityBank.java
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 35 of 68
/*
* This java file is a starter class which instantiates the Account
* class and call the corresponding methods for various banking
* operations.
*/
/**
* This class is a starter classes that instantiate the Account.
* Using the instance, it invokes the corresponding banking
* operations.
* Date : <<Replace with the date you do this assignment>>
* @author <<Replace with your Employee No. and Name>>
* @version 1.0
*/
public class CityBank {
/**
* Instantiate the Account object. Call the corresponding methods that
* does the various banking operations.
* @param args The command line arguments
*/
public static void main (String[] args) {
// To-do: Create an instance (john) for Customer class. Call the
overloaded constructor
SavingsAccount johnSA = new SavingsAccount(101,john,1000);
johnSA.deposit(1000);
// To-do: display the balance available in account no 101
// To-do: call the method to withdraw Rs.1600.
// To-do: display the balance available.
// To-do: Create an instance (jenny) for Customer class. Call
the overloaded constructor
OverdraftAccount jennyOA = new
OverdraftAccount(201,jenny,500,2000);
// To-do: deposit Rs. 1500 to the account
// To-do: display the balance available in account no 201
Note: available balance for Overdraft Account is
balance+ Allowed negative amount
// To-do: call the method to withdraw Rs. 1000
// To-do: display the balance available
// To-do: call the method to withdraw Rs. 4000
// To-do: display the balance available
// To-do: call the method to withdraw Rs. 3000
// To-do: display the balance available
}
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 36 of 68
}
Step 5: Save and compile all the programs. Fix errors, if any.
Step 6: Execute CityBank. Analyze the outputs.
Summary of this exercise:
You have just learnt
To identify classes and their relationship (OO Analysis)
To identify data members and methods (OO Design)
To design the classes
To implement the classes
Assignment 15: Understanding Dynamic Binding
Objective: To understand dynamic binding, run-time polymorphism and its usages.
Problem Description: Making the CityBank.java to implement the dynamic binding and run-time polymorphism. Estimated time: 20 Mins.
Step 1: Make a copy of Customer, Account, SavingsAccount, OverdraftAccount and CityBank
of the previous assignment ie. Assignment 14 under the package of this assignment.
Step 2: Modify the CityBank.java as mentioned below (highlighted).
/*
* This java file is a starter class which instantiates the Account
* class and call the corresponding methods for the various banking
* operations.
*/
/**
* This class is a starter classes that instantiate the Account.
* Using the instance, it invokes the corresponding banking
* operations.
* Date : <<Replace with the date you do this assignment>>
* @author <<Replace with your Employee No. & Name>>
* @version 1.0
*/
public class CityBank {
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 37 of 68
/**
* Instantiate the Account object. Call the corresponding methods that
* does the various banking operations.
* @param args the command line arguments
*/
public static void main (String[] args) {
// To-do: Create an instance (john) for Customer class. Call the
overloaded constructor
SavingsAccount johnSA = new SavingsAccount(101,john,1000);
// To-do: call transaction(johnSA,1000) of CityBank
// To-do: call the method to withdraw Rs.1600.
// To-do: display the balance available.
// To-do: Create an instance (jenny) for Customer class. Call
the overloaded constructor
OverdraftAccount jennyOA = new
OverdraftAccount(201,jenny,500,2000);
// To-do: call transaction(jennyOA,1500) of CityBank
// To-do: display the balance available in account no 201
Note: available balance for Current Account is
balance+ Allowed negative amount
// To-do: call the method to withdraw Rs. 1000 to A/c No 201
// To-do: display the balance available of 201
// To-do: call the method to withdraw Rs. 4000 to A/c No 201
// To-do: display the balance available of 201
// To-do: call the method to withdraw Rs. 3000 to A/c No 201
// To-do: display the balance available of 201
}
// To-do: Add the /** .. */ comment for the method
public void transaction(Account account, double amount) {
account.deposit(amount);
}
}
Fix the compilation error in CityBank.java
Step 3: Compile and execute the program. You should get the same output as that of
Assignment 19. Try to understand how the program works.
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 38 of 68
The compiler, while compiling the program, would find the class for
which the reference variable is declared. The compiler also checks
whether the class has method which is being invoked.
In this case, the account is a reference variable for Account class.
Account class does not have a method withdraw. Hence, the compiler
shows an error within transaction method.
At the time of execution, the run-time environment identifies the
type of the object that the reference variable is pointing to. The run-
time environment invokes the method defined in the class of the
object, the reference variable is pointing to.
In the case of transaction(johnSA,1000), the type of the object that
the reference variable account pointing to is “SavingsAccount”. The
SavingsAccount inherits the deposit method from Account. Hence, the
deposit method in Account would be invoked automatically.
Step 4: Modify the transaction() method of CityBank to call the withdraw() method, as shown
below.
public static void transaction(Account account, double amount) {
account.deposit(amount);
account.withdraw(100);
}
Step 5: Compile the program and try to understand the compilation error.
In this case, the account is a reference variable for Account class.
Account class does not have a method withdraw. Hence, the compiler
shows an error.
Step 6: Fix the error, by removing the account.withdraw(100) from transaction method.
Step 7: Compile and execute the program.
Summary of this exercise:
You have just learnt
The concept of Dynamic binding and run-time polymorphism.
Assignment 16: Understanding Abstract class
Objective: To understand the concept of abstraction (abstract method and abstract class).
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 39 of 68
Problem Description: Introducing the abstract method and abstract class in CityBank application. Estimated time: 30 Mins.
Step 1: Make a copy of Customer, Account, SavingsAccount, CurrentAccount and CityBank of
the previous assignment i.e., Assignment 15 under the package of this assignment.
Abstract method:
A method can be declared as abstract in the super class, if the
method cannot be defined within the super class, but needs to be
defined within the sub class. By declaring a method abstract, you are
forcing the subclass to define the method.
Abstract class:
A class can be declared as abstract in two circumstances. One, if the
class has any of the method declared as abstract. Other being, If you
don‟t want to instantiate the class but you want to instantiate the
subclass.
Note: Object cannot be instantiated for the abstract class, where as the
reference variable can be declared for the abstract class.
Step 2: In CityBank application, the programmer should not create an object for the class
Account. (In real world, we have either Savings Account or Current Account. There cannot be
simply be an account. Similarly, there is nothing called vehicle existing in the real world. It
would be an instance of car, bike, or other type of vehicles. )
Step 3: Modify the Account class by declaring Account class as abstract.
Step 4: Compile all the programs and execute.
Step 5: Modify CityBank.java as given below.
/*
* This java file is a starter class which instantiates the Account
* class and call the corresponding methods for the various banking
* operations.
*/
/**
* This class is a starter classes that instantiate the Account.
* Using the instance, it invokes the corresponding banking
* operations.
* Date : <<Replace with the date you do this assignment>>
* @author <<Replace with your Employee No. & Name>>
* @version 1.0
*/
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 40 of 68
public class CityBank {
/**
* Instantiate the Account object. Call the corresponding methods that
* does the various banking operations.
* @param args The command line arguments
*/
public static void main (String[] args) {
// To-do: Create an instance (john) for Customer class. Call the
overloaded constructor
Account account = new Account();
SavingsAccount johnSA = new SavingsAccount(101,john,1000);
// To-do: call transaction(johnSA,1000) of CityBank
// To-do: call the method to withdraw Rs.1600.
// To-do: display the balance available.
// To-do: Create an instance (jenny) for Customer class. Call
the overloaded constructor
CurrentAccount jennyOA = new
CurrentAccount(201,jenny,500,2000);
// To-do: call transaction(jennyOA,1500) of CityBank
// To-do: display the balance available in account no 201
Note: available balance for Current Account is
balance+Allowed negative amount
// To-do: call the method to withdraw Rs. 1000 to A/c No 201
// To-do: display the balance available of 201
// To-do: call the method to withdraw Rs. 4000 to A/c No 201
// To-do: display the balance available of 201
// To-do: call the method to withdraw Rs. 3000 to A/c No 201
// To-do: display the balance available of 201
}
// To-do: Add the /** .. */ comment for the method
public static void transaction(Account account, double amount) {
account.deposit(amount);
}
}
Step 6: Save and compile the program.
Step 7: Fix the compilation error, by removing the statement highlighted. Compile the
program.
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 41 of 68
Step 8: Also, as part of OOD, you have identified that the subclasses i.e. SavingsAccount and
CurrentAccount should define the withdraw method. This can be enforced by declaring an
abstract method in the Account class.
Step 9: Modify the Account abstract to have an abstract method with the signature as
follows.
public abstract void withdraw(double amount);
The class should be declared as abstract, if any of the method is
declared as abstract.
Account is already declared as abstract, according to step 3.
Step 10: Compile and execute the program.
Step 11: Try to comment the withdraw method in SavingsAccount and compile the program.
You would get compilation error.
Step 12: Un-comment the withdraw method. Save, compile and execute CityBank.java
Summary of this exercise:
You have just learnt
Abstract method
Abstract class
Assignment 17: Understanding Dynamic Binding
Objective: To understand and revisit dynamic binding, run-time polymorphism and its usages.
Problem Description: Making the CityBank.java to implement the dynamic binding and run-time polymorphism. Estimated time: 20 Mins.
Step 1: Make a copy of Customer, Account, SavingsAccount and OverdraftAccount of the
previous assignment i.e. Assignment 16 under the package of this assignment.
Step 2: Create a class CityBank, as shown below.
/*
* This java file is a starter class which instantiates the Account
* class and call the corresponding methods for the various bank
* operation.
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 42 of 68
*/
/**
* This class is a starter classes that instantiate the Account.
* Using the instance, it invokes the corresponding banking
* operations.
* Date : <<Replace with the date you do this assignment>>
* @author <<Replace with your Emp No. & Name>>
* @version 1.0
*/
public class CityBank {
/**
* Instantiate the Account object. Call the corresponding methods that
* does the various banking operations.
* @param args The command line arguments
*/
public static void main (String[] args) {
// To-do: Create an instance (john) for Customer class. Call the
overloaded constructor
SavingsAccount johnSA = new SavingsAccount(101,john,1000);
// To-do: call transaction(johnSA,1000) of CityBank
// To-do: display the balance available.
// To-do: Create an instance (jenny) for Customer class. Call
the overloaded constructor
CurrentAccount jennyOA = new
CurrentAccount(201,jenny,500,2000);
// To-do: call transaction (jennyOA,1500) of CityBank
// To-do: display the balance available in account no 201
Note: available balance for Overdraft Account is
balance+ Allowed negative amount
}
// To-do: Add the /** .. */ comment for the method
public static void transaction(Account account, double amount) {
account.deposit(amount);
account.withdraw(100);
}
}
Step 3: Compile and execute the program.
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 43 of 68
Now, you are able to call the deposit as well withdraw within
transaction method, because the Account class has the definition of
deposit as well the declaration of withdraw method.
Summary of this exercise:
You have just learnt
The concept of Dynamic binding and run-time polymorphism.
Assignment 18: Understanding Interface
Objective: To understand the concept of interface.
Problem Description: Create classes for different animals like Lion, Hippo, Dog, Cat.
Estimated timed: 20 mts
Step 1: Perform OOA
Step 2: Perform OOD. You should be able to identify the commonality among the nouns.
Hence, you derive at the super class Animal. Dog and Cat again has come commonality as
both are pet animals. Hence you can introduce the concept of generalization here. But, the
Dog and Cat is already inheriting from Animal. Hence PetAnimal cannot be a class.
Make PetAnimal as Interface. The pet animals would have the functionality of being friendly
and playing with the human beings.
Based on these, design the classes, its properties (if any) and functionalities.
Step 3: Implement the Animal, Hippo, Dog, Cat classes and the PetAnimal Interface.
Step 4: Make sure the Dog and Cat are inheriting from both Animal class as well from Pet
interface. Create all the below mentioned classes and interfaces according to the standards.
public interface PetAnimal {
}
public class Animal {
}
public class Hippo extends Animal {
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 44 of 68
}
public class Dog extends Animal implements PetAnimal {
}
public class Cat extends Animal implements PetAnimal {
}
Step 5: Save all and compile. Execute the program.
Summary of this exercise:
You have just learnt
The concept of Interface in Inheritance
Assignment 19: Understanding Packages
Objective: To understand the package concept.
Problem Description: Organizing the classes and interfaces of CityBank application into packages. Estimated time: 20 Mins. Note: All package names must start with a lower case letter
Step 1: Create a package with name com.Citybank.customer. Modify the Customer class of
Assignment4, so that it belongs to the package com.Citybank.customer. Make sure the class
and the constructor(s) are declared as public.
Step 2: Compile Customer.java. Fix the errors, if any.
Step 3: Create a package with name com.Citybank.account. Add the Account,
SavingsAccount, CurrentAccount to the package com.Citybank.account. Modify Account class,
so that it imports the Customer class belonging to com.Citybank.customer package. Make
sure all the classes and constructors are declared as public. Otherwise you will not be
able to access the class outside the package.
Step 4: Create a package with name com.Citybank. Add the CityBank to the package
com.Citybank. Make sure the class and constructor(s) are declared as public. Import the
relevant classes and the packages.
Step 5: Compile all the classes and fix the errors, if any.
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 45 of 68
There won‟t be any error related to locating the package, be it
com.Citybank.customer or com.Citybank.account.
Try to find why the java compiler / run-time do not throw any error.
Step 7: Execute the com.Citybank.CityBank from the package where the package is stored.
Summary of this exercise:
You have just learnt
The concept of Dynamic binding and run-time polymorphism.
Assignment 20: Understanding the Access Specifier
Objective: To understand the concept of Access specifiers.
Problem Description: Create classes in different packages and try to access variables with different access specifiers. Estimated time: 20 Mins.
Step 1: Create a package „package1‟
Step 2: Create two classes Base, Child1 under package1 as given below.
Base.java
package package1;
/*
* This java file is a class which has 4 member variables
* with different access specifiers
*/
/**
* This class is a class that has 4 member variables
* with different access specifiers
* It also has 2 methods to access the variables
* Date : <<Replace with the date you do this assignment>>
* @author <<Replace with your Employee No. & Name>>
* @version 1.0
*/
public class Base {
int variable1;
private int variable2;
protected int variable3;
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 46 of 68
public int variable4;
/*
* Default Constructor that initializes the member variables
*/
Base () {
variable1=100;
variable2=200;
variable3=300;
variable4=400;
}
/*
* Returns the value of the member variable variable1
*/
int getVariable1(){
return variable1;
}
/*
* Returns the value of the member variable variable2
*/
public int getVariable2(){
return variable2;
}
}
Child1.java
package package1;
/*
* This java file is a class which is a sub class
* of Base class
*/
/**
* This class is a class which extends Base class
* It has a method that gets the values of the
* member variables of Base class
* Date : <<Replace with the date you do this assignment>>
* @author <<Replace with your Emp No. & Name>>
* @version 1.0
*/
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 47 of 68
public class Child1 extends Base{
public void getValues()
{
System.out.println (getVariable1());
System.out.println (getVariable2());
System.out.println (variable3);
System.out.println (variable4);
}
}
Step 3: Compile all the classes. Fix the errors.
Members declared without any access specifier is default. They can be
accessed only within the same package
Members declared as private can be accessed only within the class
Members declared as protected can be accessed within the class and also
by sub classes in a different package
Members declared as public can be accessed anywhere
Step 4: Create a package package2
Step 5: Create a class Child2 under package2 as given below.
Child2.java
package package2;
/*
* This java file is a class which is another sub class
* of Base class
*/
import package1.Base;
/**
* This class is a class which extends Base class
* It has a method that gets the values of the
* member variables of Base class
* Date : <<Replace with the date you do this assignment>>
* @author <<Replace with your Emp No. & Name>>
* @version 1.0
*/
public class Child2 extends Base{
public void getValues() {
Base base=new Base();
System.out.println (variable3); // Line 1
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 48 of 68
System.out.println (base.variable3); // Line 2
System.out.println (variable4);
}
}
Step 6: Compile Child2.java. Fix the errors.
Though protected members can be accessed in sub classes in different
package, it can be accessed only through inheritance
That is it can be accessed as if it belongs to the same class (Like in
Line 1)
When accessed using an object, it acts as if it is a private variable
(So, Line 2 will throw a compile time error)
Step 7: Compile all the programs and execute the program.
Summary of this exercise:
You have just learnt
To declare variables with different access specifiers and where it can be accessed.
Assignment 21: Garbage Collection
Objective: To understand the concept of memory allocation and how garbage collection takes
place in Java.
Problem Description: Draw the stack and heap representation for the following class. And identify how many objects are created on heap
Estimated time: 20 Mins.
class Tyre{}
public class Car {
Tyre tyre;
String name;
public static void main(String[] args) {
Car carMain = new Car();
carMain.setFeatures(carMain);
}
void setFeatures(Car car) {
tyre = new Tyre();
car.setName("Swift");
}
void setName(String name){
this.name = name;
}
}
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 49 of 68
setName() name
setFeatures() car
main() carMain
Overall three objects are created on the Heap.
Summary of this exercise:
You have just learnt
How memory allocation takes place on heap and stack
Assignment 21a: Garbage Collection
Objective: To understand the concept of memory allocation and how garbage collection takes
place in Java.
Problem Description: Draw the stack and heap representation for the following class. And identify how many objects will be created on heap
Summary of this exercise:
Heap String
Object:
“Swift”
Tyre object
Car object:
Instance variables:
name
tyre
Stack
public class Vehicle {
String vehicleName;
Wheels [] wheels = new Wheels [4] ;
public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
}
}
class Wheels{}
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 50 of 68
You have just learnt
How memory allocation takes place on heap and stack
Assignment 21b: Garbage Collection
Objective: To understand the concept of memory allocation and how garbage collection takes
place in Java.
Problem Description: Analyze the following code example and tell how many objects will
be garbage collected after
a. Line 1
b. Line 2
c. Line 3
Before solving the above parts of the problem, find the total number of objects that will be
created on heap just before the start of line 1.
Ans :
a. after line 1: 0 Objects will be garbage collected
b. after line 2: 2 Objects will be garbage collected
c. after line 3: remaining 2 Objects will be garbage collected.
Summary of this exercise:
You have just learnt
To understand the how the stack and heap work together
How to analyze a code to predict the number of objects created on the heap.
public class Garbage {
String garbageLocation;
Garbage garbage;
public static void main(String[] args) {
Garbage garbage1 = new Garbage();
garbage1.garbage = new Garbage();
garbage1.garbageLocation="Hyderabad";
garbage1.garbage.garbageLocation="Kukatpally"; garbage1.garbage.garbage=garbage1;
garbage1.garbage.garbage = null ; //line 1
garbage1.garbage= null; //line 2
garbage1 = null; //line 3
}
}
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 51 of 68
How to predict the number of objects that are eligible for garbage collection.
5 Assignments for Day 3 Java Programming
Assignment 22: Autoboxing and unboxing
Objective: To understand the autoboxing and unboxing concept.
Problem Description: Write a class to store the list of employee id‟s belonging to a particular project in a vector. Assume that employee from 1001 to 1005 has been assigned a project in CityBank account. Estimated time: 15 Mins.
Step 1: Create a class Employee based on the below given requirements.
/*
* To-do: <<Write appropriate comment>>
*/
/**
* <<Replace with appropriate description>>
* Date : <<Replace with the date you do this assignment>>
* @author <<Replace with your Emp No. & Name>>
* @version 1.0
*/
public class EmployeeInfo{
/**
* To-do: << Replace with appropriate description >>
*/
public static void main (String[] args) {
//Vector is in java.util package. Refer javaDocs
Vector empList = new Vector();
int empNo=1000;
for(int count=0;count<5;count++)
{
empNo++;
// Only object can be added to the vector.
// Convert the int to Integer
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 52 of 68
// To-do: add the empNo to the vector
}
// To-do: retrieve and display the elements in vector
}
}
Step 2: Complete the above program and execute the same.
Step 3: Modify the above program to use the concept of autoboxing and unboxing, which
would simplify the program. Also, use enhanced for loop to retrieve and display the elements
in the vector.
Step 4: Compile and execute the program.
Summary of this exercise:
You have just learnt
The concept of Autoboxing and unboxing.
Assignment 23: Understanding Exception Handling (Unchecked Exceptions)
Objective: To understand how to handle the exceptions.
Problem Description: A program that would handle the NullPointerException with try and catch block. Estimated time: 30 Mins.
Step 1: Create a starter class with the name ExceptionHandlingDemo.
Step 2: Write the below given code in the main method of the starter class.
String name;
System.out.println(name.length());
name = "John";
System.out.println(name.length());
Step 3: Compile the program.
Step 4: Fix the error as shown below.
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 53 of 68
String name = null;
System.out.println(name.length());
name = "John";
System.out.println(name.length());
Step 5: Compile the program.
Step 6: Execute the program and note the exception.
NullPointerException is an unchecked exception. The compiler would
check only for the checked exceptions.
Refer to JavaDoc for further information about
NullPoninterException.
Step 7: Modify the program to handle the run-time exception, as given below.
String name = null;
try{
System.out.println(name.length());
}
catch(NullPointerException exception){
System.out.println("Object is null");
}
System.out.println(“Continuing the execution...”);
Step 8: Now, execute the program. As the exception raised is handled in the program, the
program does not terminate abruptly, as happened in step 6.
Step 9: Modify the code as given below.
String name = null;
try{
System.out.println(name.length());
System.out.println(“End of try block”);
}
catch(NullPointerException exception){
System.out.println("Object is null");
}
System.out.println(“Continuing the execution...”);
If a statement in the try block, throws an exception, the following
statements in the try block would not be executed.
Hence, System.out.println(“End of try block”); is not executed, when
name.lenght() throws NullPointerException.
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 54 of 68
Step 10: Compile and execute the program.
Step 11: Modify the code as given below.
String name = null;
int total = 100,count=0;
try{
int average = total/count;
System.out.println(average);
System.out.println(name.length());
}
catch(NullPointerException exception){
System.out.println("Object is null");
}
System.out.println(“Continuing the execution...”);
Step 12: Execute the program and understand the output.
Step 13: Modify the program as given below.
String name = null;
int total = 100,count=0;
try{
int average = total/count;
System.out.println(average);
System.out.println(name.length());
}
catch(ArithmeticException exception) {
System.out.println("Arithmetic Exception " +
exception.getMessage());
}
catch(NullPointerException exception){
System.out.println("Object is null");
}
System.out.println(“Continuing the execution...”);
Step 14: Execute and analyze the cause of this output.
Summary of this exercise:
You have just learnt
The fundamental of exception handling
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 55 of 68
Assignment 24: Understanding Exception Handling – try, catch & finally
Objective: To understand how to handle the exceptions – try, catch and finally block.
Problem Description: A program that would handle the NullPointerException with try, catch and finally block. Estimated time: 15 Mins.
Step 1: Make a copy of the ExceptionHandlingDemo.java in Assignment 23, under the
package of this assignment.
Step 2: Modify the program as given below.
String name = “john”;
int total = 100,count=10;
try{
int average = total/count;
System.out.println(average);
System.out.println(name.length());
}
catch(ArithmeticException exception) {
System.out.println("Arithmetic Exception " +
exception.getMessage());
}
catch(NullPointerException exception){
System.out.println("Object is null");
}
finally{
System.out.println(“within finally block”);
}
System.out.println(“Continuing the execution...”);
Step 3: Compile, execute and analyze the output.
finally block would get executed, even if the try block throws
exception. The finally block should be used to release the resources
that you have locked within the application.
For e.g. you might have opened a file within the try block. It is
always advisable to close the file in the finally block, because the
finally block would be executed definitely irrespective of the
exceptions.
Step 4: Change the value of count to 0. Compile and execute the program. Analyze the
output.
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 56 of 68
Step 5: Try to analyze the different cases associated with finally block. Especially when the
code in finally will be executed and when it will not.
Summary of this exercise:
You have just learnt
The fundamental of exception handling (try, catch and finally)
Assignment 25: Understanding Exception Handling (Checked Exceptions)
Objective: To understand how to handle the checked exceptions – try, catch and finally
block.
Problem Description: Write a program that would handle the ClassNotFoundException with try, catch and finally block. Estimated time: 15 Mins.
Step 1: Create a class named ExceptionDemo with the static block given below, under the
package com.exception.
static {
System.out.println(“In the static block of ExceptionDemo..”);
}
Step 2: Create a starter class named CheckedExceptionDemo under the package
com.exception.
Step 3: Make the CheckedExceptionDemo program to load the ExceptionDemo class at run-
time.
class Class has a method named “forName”, which loads any given
class at run-time.
public static void main(String arg[]) {
Class.forName(“com.exception.ExceptionDemo”);
}
Step 4: Save and compile the program.
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 57 of 68
The compiler throws an exception in Class.forName(..). The forName
method of Class, throws checked exception –
ClassNotFoundException. The compiler expects the programmer to
handle the checked exception.
Step 5: Modify the method as shown below.
public static void main(String arg[]) {
try{
Class.forName(“com.exception.ExceptionDemo”);
}
catch(ClassNotFoundException exception){
System.out.println(“Exception : “ + exception);
}
}
Step 6: Compile and execute the program.
To get to know about whether the method throws any checked
exception, refer to the java doc. All those methods mentioned in the
throws clause of the method signature are checked exceptions.
E.g. refer to the method signature of forName of Class.
Summary of this exercise:
You have just learnt
To handle the checked exceptions
Assignment 26: Understanding User defined Exception Handling
Objective: To understand how to handle the user-defined exceptions.
Problem Description: The withdrawal method of SavingsAccount and OverdraftAccount should raise an exception, if the balance is not sufficient for withdrawl. Estimated time: 15 Mins.
Step 1: Make a copy of Account, SavingsAccount, CurrentAccount and CityBank programs from
Assignments of Day 2 under the package of this assignment.
Step 2: Create User defined exception class, InsufficientBalanceException, as shown below.
/*
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 58 of 68
* To-do: <<Write appropriate comment>>
*/
/**
* <<Replace with appropriate description>>
* Date : <<Replace with the date you do this assignment>>
* @author <<Replace with your Emp No. & Name>>
* @version 1.0
*/
public class InsufficientBalanceExcpetion extends Exception {
/**
* To-do: << Replace with appropriate description >>
*/
public InsufficientBalanceException(){
super("Sufficient Balance not available");
}
}
Step 3: Modify the withdraw method of both SavingsAccount as well OverdraftAccount to
throw the exception
public void withdraw(double amount) throws
InsufficientBalanceException {
// logic to check the sufficient balance
// if (availablebalance <= amount)
throw new InsufficientBalanceException();
// else
// Update the balance
}
Step 4: Modify the CityBank program to handle the exceptions.
try {
// johnSA.withdraw(amount);
// johnSA.
} catch (InsufficientBalanceException e) {
System.out.println(e.getMessage());
}
Step 5: Similarly modify the code every time you invoke the withdraw method.
Step 6: Compile all the programs and execute it.
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 59 of 68
Summary of this exercise:
You have just learnt
To handle the user defined exceptions
To handle the exception
3 Assignments for Day 4 Java Programming
Assignment 27: JavaBeans
Objective: To understand how to create JavaBeans using Eclipse IDE.
Problem Description: Create a EmployeeBean class named Employee under the package of
this assignment. Employee should contains following fields:
Step 1: select all the fields and right click, you will get a floating menu.
Step 2: From the floating menu select source and then select Generate Getters and Setters
and the same are highlighted in the screenshot above. After you select, you will get a window
like this.
public class Employee{
int employeeID;
String employeeName;
Calendar dateOfBirth;
}
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 60 of 68
Step 3: select the checkboxes for the fields for which you want to generate the getters and
setters. From the right you can select different options of generating only setters or getters.
Then click ok.
Step 4: Save and compile the bean class
Summary of this exercise:
You have just learnt
How to create JavaBeans using Eclipse IDE
Assignment 28: Creating (Java Bean) Classes and Object
Objective: To understand what is java bean and how to create a java bean class and
instantiate it in another class. Problem Description: Create a Customer (Bean) class with instance variables customerID, customerName, address and pinCode. Create another starter class and instantiate Customer bean object in it. Estimated time: 15 Mins.
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 61 of 68
Step 1: Create a Java Bean Class – Customer according to the below given class diagram. Save
the file as Customer.java under the package of the assignment.
Customer
- customerId : int
- customerName : String
- customerAddress : String
- pincode : int
+ setCustomerId(int custId) : void
+ getCustomerId() : int
+ setCustomerName(String custName) : void
+ getCustomerName() : String
+ setCustomerAddress(String custAddress) : void
+ getCustomerAddress() : String
+ setPincode(int pin) : void
+ getPincode() : int
Java Bean:- Java Bean is defined as a reusable component. A java bean class
should adhere to the following rules.
All the member variables should be declared private
(Almost) All the member variables should have the Getter and Setter
methods
o Setter Method is to set the value for the corresponding
member variable.
o Getter Method is to retrieve the value stored in the
corresponding member variable.
Name of the Getter & Setter method should match the variable name
o E.g, member variable : customerName (according to the java
naming convention the variable should follow camel-casing.
Hence first letter should be in lower case)
Setter Method Name : setCustomerName
Constructor need not be defined
Step 2: Create a starter class with name “CityBank”.
Filename CityBank.java
/*
* This java file is a starter class which instantiates Customer bean
* and call the corresponding setter (to assign values) and getter
* methods (to retrieve the values and display it)from the main method
*/
/**
* This class is a starter classes that instantiate the Customer bean.
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 62 of 68
* Using the instance, it calls the setter to set the member variables
* and the getter method to display the values
* Date : <<Replace with the date you do this assignment>>
* @author <<Replace with your Emp No. & Name>>
* @version 1.0
*/
public class CityBank {
/**
* Instantiate the Customer bean. Set the values for the member
* variables and get the values and display the same.
* @param args The command line arguments
*/
public static void main (String[] args) {
// To-do: Create an instance (john) for Customer class.
//Set the values of all the member variables for „john‟
john.customerId = 101;
//To-do: Set the values for all the other member variables
// Retrieve the values and display it
System.out.println(john.customerId);
//To-do: Retrieve and display all the other member variables
}
}
Step 3: Try to Compile the CityBank.java. Read the compilation error and try to fix it.
The java compiler would list compilation errors like “customerId has
private access in Customer” for customerId and similar error for
other member variables. If those compilation errors are not listed,
then the Customer class has not been created according to the class
diagram. Check whether all the member variables are declared as
„private‟. Modify Customer.java accordingly and recompile the code.
The customerId is private in Customer class. The private members
can be accessed only within the class. According to the OO concept
(refer to encapsulation and data hiding concept in the slide), the
member variables cannot be declared as public. The only way to
access the member variable is through the setter and getter
methods.
Step 4: Modify the CityBank.java accordingly.
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 63 of 68
Use john.setCustomerId(101) – to set the value for the member
variable
Use john.getCustomerid() – to retrieve the value and display the same
in CityBank
Similarly, call the corresponding methods of all the member variables.
Step 5: Save the program. Compile it. Fix all the errors, if any.
Step 6: Execute the CityBank class and check the output.
Summary of this exercise:
You have just learnt
Java Beans
Creating object of one class in another class
How to access member variables of an object
Assignment 29: Usage of ‘this’ keyword
Objective: To understand the usage of „this‟ keyword. Problem Description: Create a Customer (Bean) class with instance variables customerID, customerName, address and pinCode and use the „this‟ to represent the current object within the member methods. Estimated time: 15 Mins.
Step 1: Make a copy of Customer.java and CityBank.java of Assignment 28, under the package
of this assignment.
Step 2: Alter the class according to the below given class diagram.
Customer
- customerId : int
- customerName : String
- customerAddress : String
- pincode : int
+ setCustomerId(int customerId) : void
+ getCustomerId() : int
+ setCustomerName(String customerName) : void
+ getCustomerName() : String
+ setCustomerAddress(String customerAddress) : void
+ getCustomerAddress() : String
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 64 of 68
+ setPincode(int pincode) : void
+ getPincode() : int
The parameter name of the setter methods is different from
Assignment 8. You have to change the variable name used within the
setter methods to match the member variable names.
e.g. public void setCustomerId(int customerId) {
customerId = customerId;
}
Step 3: Compile Customer.java. Fix the errors if any.
Step 4: Compile CityBank.java and fix the errors if any.
Step 5: Execute CityBank.java.
Do you get the default value for all the properties? Try to analyze the
output
public void setCustomerId(int customerId) {
customerId = customerId;
}
The value of the local variable customerId is assigned to the local
variable itself, instead of the member variable customerId.
Step 6: Do the necessary modification in the Customer class, so that the values get initialized
to the member variables rather than the local variables themselves.
Alter the setter definition in Customer as follows.
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
this.customerId, „this‟ – refers to the current object i.e. john. Hence
the value of the local variable customerId is assigned to john‟s
customerId. Similarly change the definition for all the setter methods.
Step 7: Compile Customer.java. Fix the errors, if any.
Step 8: Execute CityBank. Check whether the program displays the Customer Id, Name,
address and pincode of john.
Summary of this exercise:
You have learnt
Usage of „this‟
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 65 of 68
Assignment 30: Understanding Collection Framework
Objective: To understand the Collection framework.
Problem Description: A program to store the employee object in the ArrayList. Estimated time: 20 Mins.
Step 1: Create a EmployeeBean class named Employee under the package of this assignment.
Employee contains following fields:
Note: you can use the EmployeeBean created as a part of earlier assignment.
Step 2: Create a starter class named EmployeeInfo under the package of this assignment as
shown below.
Step 3: Change the class to retrieve the records using forEach loop not an iterator
Summary of this exercise:
You have just learnt
Basics of the collection framework using ArrayList and List.
Assignment 31: Reflection API
Objective: To understand the basics of reflection API.
int employeeID;
String employeeName;
Calendar dateOfBirth;
public class EmployeeInfo {
public static void main(String[] args) {
//To-Do : create four employee objects
//To-Do : store the objects in the ArrayList
/* [ HINT :]
* Employee employee1 = new Emlpoyee();
* employee1.employeeID = 1001 ;
* List list = new ArrayList();
* list.add(employee1);
*/
//To-Do : retrieve the employee objects from the list using iterator
and display their information
}
}
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 66 of 68
Problem Description: To analyze a class using Reflection API Estimated time: 20 Mins.
Step 1: Copy the class file of the Employee bean in the current package of this assignment.
Step 2: Create a TestReflection.java in the current package of the assignment. Class will look
something like this.
When you will save (+compile) the file. You will get a checked
exception ClassNotFoundException because the Class.forName() is a
static method which throws ClassNotFoundException.
Step 3: Make the above code compile, put the above code in the main in try-catch block or
use throws clause with the main.
Step 4: Replace the comments with actual code that is required to collect information about
the fields and methods in the Employee class.
Summary of this exercise:
You have just learnt
How to use Reflection API
import java.lang.reflect.*;
public class TestReflection {
public static void main(String[] args) {
Class classObj = Class.forName("Employee");
}
}
try {
Class classObj = Class.forName("Employee");
//To-Do : write code to collect the method information- name and
parameters
// To-Do : write code to collect field information -access
specifiers and data types
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 67 of 68
Assignment 32: Annotations
Objective: To understand the basics of reflection API.
Problem Description: Use @Deprecated annotation to make the function of a class deprecated. Estimated time: 15 Mins.
Step 1: Create a java class as shown below
Step 2: Create a java class to test the above class as shown below
public class StringMock {
String capacity;
public StringMock(){
}
public StringMock(String capacity){
this.capacity=capacity;
}
/** Description: method returns the position of the character if
* char to be searched is present in the String otherwise it
* returns -1
* @param string
* @param searchItem
* @return int
*/
@Deprecated
public static int search(String string,char searchItem){
//declare loop variable
int index ;
//convert the string to char array
char [] charArray = string.toCharArray();
//iterate over the char array to search for the character
for(index=0; index < charArray.length; index ++){
if(charArray[index]==searchItem) return index;
}
return -1 ;
}
}
public class TestStringMock {
public static void main(String[] args) {
String message = "What's in the name";
//To-Do : create an object of StringMock class
//To-Do : Use search method to search for a character present
in the array
//To-Do : Use search method to search for a character not
present in the array
}
}
CommunicationTeam.org Lab Guide for Java Programming
Version No. 1.0 68 of 68
You will see that the method with which you gave @Deprecated
annotation will come as deprecated when you are using it. Likewise
fields and even class can be made as deprecated
Summary of this exercise:
You have just learnt
Basics of built-in annotations