OOCUsingJava Lab Guide V3
OOCUsingJava Lab Guide V3
CONFIDENTIAL
Infosys Limited Object Oriented Concepts Using Java
COPYRIGHT NOTICE
All ideas and information contained in this document are the intellectual property of Education and Research
Department, Infosys Limited. This document is not for general distribution and is meant for use only for the person
they are specifically issued to. This document shall not be loaned to anyone, within or outside Infosys, including its
customers. Copying or unauthorized distribution of this document, in any form or means including electronic,
mechanical, photocopying or otherwise is illegal.
Contents
COPYRIGHT NOTICE ......................................................................................................1
CONTENTS ..................................................................................................................2
CONTEXT ....................................................................................................................6
GUIDELINES .................................................................................................................6
ASSIGNMENT 1.2.1: USE CASE DIAGRAM FOR COURSE REGISTRATION SYSTEM ................................................ 7
ASSIGNMENT 1.2.2: USE CASE DIAGRAM...................................................................................... 8
ASSIGNMENT 1.2.3 : CASE STUDY OF SPEDFAST COURIER COMPANY ........................................................... 8
Context
This document contains Practice Questions to be completed as part of lesson 3 control
structures.
Guidelines
x The lab guide has been designed to give a hands on experience to map the concepts
learnt in the session with practical assignments
x The assignments have been categorized into solved assignments to hand hold a
beginner, partially solved assignments to begin trying out on their own and unsolved
assignments to let learners write code completely on their own
x These assignments contain coding exercises, debugging exercises, coding standards
exercises and self-review assignments
x Lab guide assignments are threaded assignment which can be built incrementally every
day. This will help understanding the concepts and building a complete application
x Solving these exercises methodically would provide confidence to the learner to
attempt the module and Hands-On exams
x The estimated time would help a learner to solve problems given a deadline
Objective: Analysis of the following Case Study from the perspective of Object Oriented
Approach
A Course Registration System needs to be developed for an engineering college. The college
wants an automated system to replace its manual system for the purpose of registration of
students to branches and calculation of fees for each year. The engineering college provides
graduation courses in various branches of engineering.
The system will be used by the admin staff to register students admitted to the college to the
branches at the time of joining the college and also to calculate the yearly fees for the
students. The student has to register every year for the next academic year. The Admin takes
care of the yearly registration of the students and the calculation of yearly fees. The system
needs to be authenticated with a login id and password.
Registration of a student to a branch is based on the qualifying exam marks and the entrance
counseling. For every branch, a yearly branch fee is applicable. Discounts are given to the
6|Page Infosys Foundation Program
Infosys Limited Object Oriented Concepts Using Java
branch fees of the first year based on the qualifying exam marks. There is a registration fees
also applicable to the first year students. Students can opt to be a day scholar or hostelite.
Yearly bus fees are applicable for all the day scholars based on the distance of travel. Yearly
hostel fees are applicable for all the hostelites. Yearly infrastructure fees and library fees are
also applicable to all the students. Admin calculates the yearly college fees for each student
and the college fees include all the fees specified earlier based on the type of student. Admin
will provide a printed receipt of the fees to the students once the annual college fees have
been paid.
At the time of registration, student has to provide the permanent address and in case the
student is opting to be a day scholar, he/she has to provide the residential address also.
Assumption:
1. Decision of the branch of study a student is allocated, is not within the scope of this
case study
Consider the above case study Course Registration System (Reference 6.1 Assignment 1).
Answer the following questions:
Note:
x The use case diagram should be drawn in a Microsoft Word
Document and submitted as part of the assignments
Objective: Understand requirements of the system and draw a use case diagram.
Problem Description: Consider the scenario of an online auction including a buyer and seller.
The buyer and seller have to create accounts and searches listing for an item (Buyer to buy at
lowest price and seller to sell at profitable price). The seller has to create an auction and has
to ship the item if an acceptable bid is made. The buyer has to place a favorable bid and
purchases the item.
Note:
x The use case diagram should be drawn in a Microsoft Word
Document and submitted as part of the assignments
Objective: Understand requirements of the system and draw a use case diagram.
Customers approach the Dispatchers1 at SpedFast counters to send shipments. One customer
can send as many shipments as required. The Dispatcher initiates a shipment after the
payment from the customer.
Each shipment has a Shipment ID associated with it. A shipment also has a Recipient’s
address, priority, weight of the shipment, shipping date and date of delivery. The amount is
calculated based on the weight of the shipment and priority. Currently SpedFast provides
“LOW, NORMAL and URGENT” priorities with different rates on shipments.
SpedFast also intends to have a Greeting Shipment service for customers to send Gifts for
celebrations. This is similar to the normal shipments, but it also carries a “Greeting message”
from the customer.
Objective: Analysis of the scenarios picked from the case study discussed in Assignment 1 of
Day 1 and identification of the OO concepts associated to the scenarios
Problem Description: Identify the OO concepts associated with the below given scenarios
1. There are around 10000 students studying in various branches of engineering in the
college. Every student has some attributes and performs some activities. How can the
attributes and activities be represented using OO concepts .
1
Dispatcher: The person who dispatches shipments in a postal organization or courier company.
9|Page Infosys Foundation Program
Infosys Limited Object Oriented Concepts Using Java
2. Students can opt to be a Day Scholar or a Hostelite. In case of Day Scholar, bus fees is
applicable based on the distance from the residential location to the college. In case
of Hostelite, hostel fees is applicable. Identify the OO concept discussed .Identify the
generalized and specialized classes for this scenario.
3. The Admin staff calculates the fees to be paid for all students irrespective of the type
of student. The formula for calculation however depends on the kind of student.
Which is the OO concept discussed here?
4. Certain attributes of the student need to be accessed by the admin staff directly, and
certain attributes need not be accessed. How can this be implemented and what is the
OO concept discussed here?
Objective: Understand the various Object Oriented concepts and their definitions
Problem Description: Fill in the blanks for the below given statements
1. The properties exhibited by a complex system are ____, _____ and ____
2. A ___________ is a software design that describes the common attributes and behavior
of objects
6. UML diagram which can be used to identify the functionalities of the system under
development is called ___________
7. OO concept wherein a class shares some common structure or behavior with one or
more classes is called _____________
10. Process of focusing on essential details and ignoring non-essential details is called
__________
Problem Description: Fill in the crossword based on the scenario and clues given below:
Ashok and Amit are two employees who joined the Human Resources Department of a
technology driven firm this financial year. Ashok has opted to be a full time employee while
Amit has opted to be a part time one. The Accounting Group Head has to take care of
calculating the employee’s salary based on the status of work. For Ashok, the salary includes
DA, HRA, PF Contributions, Conveyance Charges and Fixed Salary component. For Amit ,the
salary includes DA, HRA and Fixed Salary Component only. On receiving salary, the employees
have to submit their signatures as a proof of receiving the salary from the accounting group.
Across
1. Ashok is an ________ of Employee class
2. Accounting group head represents an ________ of the course registration
system
3. Ashok and Amit are two kinds of employees. This represents the
_____________ OO concept.
4. The Accounting Group Head calculates the salary to be handed over for all
employees irrespective of the type of student. The formula for calculation
however depends on the kind of employee. This represents the
______________ OO concept.
Down
5. The notation that can be used for representing the salary system:
6. Ashok has access to details which are essential for him, whereas the
Accounting Group Head has access to all information related to the
employees. This represents the _________ OO concept
7. The attributes and activities of an employee can be bundled into a
11 | P a g e Infosys Foundation Program
Infosys Limited Object Oriented Concepts Using Java
__________
7
3
Objective: To define variables and constants & datatypes and to print the same.
Background: Java supports different basic data types (int, float, double,char etc).
Note: A java file VariablesDemo.java is provided to you in Supplied Source Code folder within
the Lab Guide folder.
Problem Description: Declare variables to store employee id, gender, basic salary and
allowances. Display all the details.
Step 1: Create a class file in the java project with the name VariablesDemo.java. Now copy
the source code, given in VaribalesDemo.java to the one created in the project
Step 2: In the supplied code, a variable called “empId” is declared of type int to store the
Employee id. Similarly declare the variable for storing gender, basic salary and allowances.
Step 3: Once when variables are declared, assign some values to it and display the same.
Step 4: Compile and run the program to view the outcome of the program.
Note:
While assigning value to char variable, the data should be in
single quotes. For example consider a variable “option” which
takes Y for Yes and N for No.
char option = 'Y' ;
And check what happens when you assign a value using double
quotes (“ ”) for char variable.
Problem Description: Refer Assignment 7.1.1, make the basic salary as constant and assign
the value 25000.0 to it.
Note:
Try assigning some values to the final (constant) variable in your
code and observe what happens
Problem Description: A Musical store wants to automate the process of calculating discount
based on the bill amount, which was done out manually.
Step 1: Use the formula as follows to get the right bill amount after discount:
billAmount = billAmount - (billAmount * ((double)discount/100))
Compile and execute the program and you will notice that the discount calculation is taking
place correctly.
Note:
The discount calculation did not happen, because the calculation
discount/100 resulted in an integer value (there is loss of the
precision part) and hence did not reflect in the output.
Step 2: Try out the same problem with the below mentioned changes to the formula
Note:
The discount calculation did happen, because the discount is type
casted to double explicitly and hence the desired output is
obtained
Facts:
x Widening conversions are allowed whereas narrowing
conversions result in compilation error
x It is not possible to assign a double to a float value
Objective: Understand the terms -class, objects, state, behavior and identity
2
7
3
9
4
Objective: Debug a program containing classes and objects and understand the common
programming errors
Problem Description: Consider the revised Demo class with the main method given below.
Identify the errors and debug the same to get the output as shown:
class Demo{
public static void main(String args[]){
Student student;
student.setStudentId(1002);
student.setQualifyingExamMarks(68);
student.setResidentialStatus('H');
System.out.println("Student Id:"+student.studentId);
System.out.println("Qualifying marks:"+getQualifyingExamMarks());
System.out.println("Residential Status:"+getResidentialStatus());
System.out.println("Year Of Engineering:"+getYearOfEngg());
}
}
Output expected:
Student Id:1002
Qualifying Marks:68.0
Residential Status:H
Year Of Engineering:3
Note:
x Initialization of variables before usage is important
x Invocation of methods is done with the help of objects
x Private access specifier is accessible only within the class where it
is declared
Objective: To understand the concept of Abstract Data Type used for achieving
encapsulation and abstraction.
Problem Description:
Student
-studentId : integer
-studentType:char
+setStudentId(id:int):void
+setStudentType(type:char):void
+getStudentId():int
+getStudentType():char
Note:
x Using a class , you can create any number of objects
x For every instance variable there should be a setter and getter
method associated to it. Setter method is to set the value of the
instance variable and getter method is to return the value of the
instance variable
x studentType instance variable can have ‘F’ (fresher) or ‘L’ (lateral)
Note:
x Create a folder for storing every assignment
Problem Description: Java programs are compiled to get the byte codes, which are verified
and executed by the JVM. Consider the Java program created in Assignment 1 of Day 2 to
explore and understand byte codes.
Step 3: Remove the Student class written in Assignment 2 of Day 2 from Demo.java file and
place it into another file called Student.java. Compile Student.java and Demo.java
(containing the Demo class with the main method) separately and Execute Demo.java. Repeat
Step 1 and answer the questions. Is there any difference in the answers?
Problem Description: The Student class with the attributes and methods is to be
implemented in Java as per the class diagram given below:
Step 2: Define the class Student as per the class diagram specified
Step 3: Define all the setter and getter methods of Student Class
studentId 1001
qualifyingExamMarks 95.0f
residentialStatus D
yearOfEngg 2
Student Id :___________________
Qualifying Marks :___________________
Residential Status :___________________
Current Year of Engineering :___________________
Step 5: List out the actual parameters, Formal Parameters, called function and
Caller function.
Estimated time: 25 minutes
Problem Description: To write code to understand pass by value and passing reference
objects.
sId = 10;
System.out.println("The sId are" + sId);
}
}
Step 2: Write the necessary code in above given program and compile it.
Step 3: After successful compilation of the program, execute it. Supply the necessary values
and observe the output.
Step 5: Enhance this code by passing the object of Student class(created in earlier
assignment) to the method passTheValueMethod().Change the value of Student Id and display
the Student Id of the student.
Problem Description: At an airport, a traveller is allowed entry into the flight only if he
clears the following checks
i. Baggage Check
ii. Immigration Check
iii. Security Check
Traveller
-travellerId:int
-baggageAmount:int
-expiryYear:int
-nocStatus:boolean
+setTravellerId(int):void
+setBaggageAmount(int):void
+setExpiryYear(int): void
+setnocStatus(boolean):void
+getTravellerId():int
+getBaggageAmount():int
+getExpiryYear():int
+getNocStatus():boolean
Demo Checks
Create the classes as per the class diagram. Notice here that an object of Traveller is passed
to the check methods. The logic for the check methods are given below:
Implementation details
checkBaggage(Traveller):boolean
x Check if baggageAmount is greater than or equal to 0 and less than or equal to 40.
If baggageAmount is VALID
return TRUE
else
return FALSE
checkImmigration(Traveller):boolean
x Check if expiryYear is greater than or equal to 2001 and less than or equal to 2025.
If expiryYear is VALID
return TRUE
else
return FALSE
checkSecurity(Traveller):boolean
If nocStatus is TRUE
return TRUE
else
return FALSE
In main method, create the object of class Traveller and initialize the values to the following
table:
Variable Value
travellerId 1001
baggageAmount 35
expiryDate 2019
nocStatus true
The created object with values initialized as above will be passed as argument to the
methods, checkBaggage(), checkImmigration() and checkSecurity() in object of class Checks
and the return values are stored in local variables.
Objective: Write programs to understand Control statements, Operators and Boolean data
type
Problem Description: The validation of the examination marks is to be done. The range of
exam marks is between 65 and 100 (both inclusive). This is to be done by including a validate
method in Student class.
Modify the code written in Student Class to implement selection statements using if-else and
logical operators
Step 1: Modify the Student class created (Student.java) in Assignment No. 2 of Day 2 to
include the method whose prototype is given above
Step 2: The implementation of the method is as follows:
a. validateExamMarks()
i. If the qualifyingExamMarks is greater than or equal to 65 and less than or
equal to 100, return true
ii. If not, return false
Step 3: Add the following statements to the existing main method written in Demo class
(Demo.java)
a. Invoke the validateExamMarks() method
b. If the qualifyingExamMarks are valid,
a. Display “Valid Marks”
b. If not valid, display “Invalid marks, the range of the qualifying exam marks
is between 65 and 100”
Step 4: Compile the program, fix the errors if any
Problem Description: Every student has to register and pay appropriate fees at the start of
every academic year of engineering. The fees to be paid are calculated based on branch
selected and discount based on qualification marks.
Step 2: Define the class Registration as per the class diagram specified
Step 3: Define all the getter and setter methods of Registration Class
Step 4: The implementation of calculateFees() method is done based on the marks which is
passed as an argument to the method. The details are given in Table 1:
Table 1:
Range of marks Discount in %
85-100 12
75-84 7
65-74 0
i. Declare a local variable with the name discount of type integer to store the
discount identified as per the Table 1
ii. Calculate the fees(instance variable of Registration class) after giving the
discount as follows:
fees = fees - (fees * (discount/100))
Step 4: Write a class called DemoReg in a file DemoReg.java with the main method
Step 5: Create a reference variable of Registration class with the name reg and instantiate
the same
a. Invoke the corresponding setter method to set the value for the instance variable as
follows:
RegistrationId 2001
b. The fees is based on the Branch Id. Create a local variable called branchId in the main
method and initialize to 1002. The logic for calculation of fees as per Branch Id is
given in Table 2
Table 2
branchId Fees
1001 25575.0
1002 15500.0
1003 33750.0
1004 8350.0
1005 20500.0
Write the logic for identifying the fees based on Branch Id using a switch case. (In the
assignments of Day 3 we will accept the branch Id as an argument).Using the
appropriate setter method, set the fees.
c. Invoke the calculateFees() with 79 as an argument for marks
d. Using the corresponding getter methods, and display the details as follows:
Registration Id :___________________
Fees :___________________
Step 6: Notice that the value of the discount calculated is not proper. Why?
Problem Description: A java program needs to be written to display the range of marks based
on the grade. The table for calculation of grade is as follows:
Problem Description: The code given below is written to display all the even numbers
between 50 and 80 (both inclusive). Debug the program to get the correct output.
Step 1: Type the below program in Eclipse, save the file as ForLoop.java, compile and
execute.
Step 2: Correct the logical error in the code, save, compile and execute the code
Problem Description: A Tutorial center has opened up invitations for admissions of students
to various courses. The class diagram for the student class is given in Figure 7.
Student
-studentAge:int
-studentName:String
-optedCourse:String
-courseType:char
-payableFees:double
+getStudentAge():int
+getStudentName():String
+getOptedCourse():String
+getCourseType():char
+getPayableFees():double
+validateStudentDetails():boolean
+calculateFeesPayable():double
Implementation Details:
Modify the design to include the setter methods for each of the instance variables
validateStudentDetails()
calculateFeesPayable()
x The fees for the student must be calculated using the following data in the Table 3.
x If the input values are valid (invoke the validateStudentDetails),calculate the fees as
given in Table 3 and update the instance variable, payableFees
Table 3:
x Create a starter called Demo. In the main method, create an object of Student class
and initialize the object with the values given in Table 4 (Use the appropriate setter
methods). Calculate the fees payable and display all the Student details by invoking
the appropriate methods.
Table 4:
At the end of the assignment you would have the following files:
Student.java
Demo.java
Step 1: Type the below programs in the Eclipse IDE, save, compile and execute
Program 1:
//Program to understand the loop and break
class Control{
public static void main(String args[]){
boolean bool = true;
System.out.println("Outer Loop");
}
System.out.println("End");
}
Program 2:
//Program to understand the loop and continue
class ControlContinue{
public static void main(String args[]){
boolean bool = true;
System.out.println("Outer Loop");
}
System.out.println("End");
}
Note:
x You can’t use a number or anything that does not evaluate to a
Boolean value as a condition in selection / iteration statement
Problem Description:
Student
-studentId : integer
-studentType:char
+Student()
+setStudentId(studentId:int):void
+setStudentType(type:char):void
+getStudentId():int
+getStudentType():char
Problem Description:
Student
-studentId : integer
-studentType:char
-studentName:String
+Student()
+Student(char sType,String fname,String lname)
+displayDetails(Student):void
Problem Description: Debug the below given code to get the output shown below after the
code.
class Registration{
private int registrationId;
class Demo{
public static void main(String args[]){
Registration reg = new Registration();
reg.setRegistrationId(1001);
System.out.println("Registration Id:"+
reg.getRegistrationId());
}
}
Step 2: Correct the logical error in the code, save, compile and execute the code to get the
below output
Output Expected:
Problem Description:
Student
-studentId : integer
-studentType:char
+Student()
+setStudentId(id:int):void
+setStudentType(type:char):void
+getStudentId():int
+getStudentType():char
Problem Description: Create a class called UserType and create a default and a
parameterized constructor. Invoke these constructors through two different objects of the
UserType class.
String name;
UserType(String parameterVal)
{
name = parameterVal;
}
UserType()
{
this("student");
}
System.out.println(usertype1.name);
System.out.println(usertype2.name);
}
Problem Description: The new metro rail service is planning to automate the generation of
tickets .This would be done when the customer press a specific key on an automated machine
available in the railway stations. The tickets are generated for a preset start point and preset
end point of travel location. The class diagram is given in Figure 3.
Ticket
-startPoint:int
-endPoint:int
-ticketAmount:int
+Ticket()
+Ticket(int,int)
+getStartPoint():int
+getEndPoint():int
+getTicketAmount():int
+validateTravelPoints():boolean
+calculateTicketAmt():void
Implementation Details:
x calculateTicketAmt ()
o The ticket amount is calculated by the following formula:
o (endpoint – startPoint) * 20
o The value is stored in the variable ticketAmount
Objective: To understand the static variable, static block and static method
Problem Description:
Step 1: Add static data member studentCount to store the total number of
student objects of type Student
Step 2: Add static member method getStudentCount () to return the
studentCount.
Step 3: In default constructor Student(), Increment the studentCount by 1 and assign
studentId = studentCount;
Static block:
Step 4: Assign studentCount = 10 (as already 10 students have enrolled)
Step 5: Save and Compile the program, fix the errors if any
Step 6: Execute the program and verify the output
Modify the Student class created (Student.java) in Assignment No. 2 of Day 3 to add the
following mentioned in the class diagram:
Step 1: Modify the Student class created (Student.java) of Assignment No. 2 of Day 3 to
include the default constructor
Step 3: Initialize the counter to 1000 (Hint: you may use a static block for this)
Step 4: Increment the value for counter by one and initialize the value of Student Id.
Step 5: Define a static method getStudentCount() which returns the number of students
enrolled.(Hint: Use the static variable)
a. Invoke the corresponding setter methods to set the values for the instance
variables as follows(studentOne):
Table 6
studentName Johan
qualifyingExamMarks 95.0f
residentialStatus D
yearOfEngg 2
branchName CSE
Student Id :___________________
Student Name :___________________
Qualifying Marks :___________________
Residential Status :___________________
Current Year of Engineering :____________________
Branch Name :____________________
c. Invoke the corresponding setter methods to set the values for the instance
variables as follows(studentTwo):
studentName James
qualifyingExamMarks 73.0f
residentialStatus D
yearOfEngg 1
branchName MECH
Step 9: Execute the program and verify the output. Did you notice that the studentId is
incremented by one for each of the objects created? Can the studentId be made static? If
yes, why? If not, Why?
Background: There are several code tuning techniques, which if used while coding can
improve the performance of the code.
Problem: Modify the codes given using the specified code tuning technique
Description: It replaces expressions consisting of constants (e.g., "3 + 5") with their final
values ("8") and thus saves time during execution
import java.util.Random;
class CFP {
public static void main(String[] args) {
final int Num1 = 30;
int Num2 = 9 - Num1 / 5;
int Num3;
Random random = new Random();
Num3 = Num2 * random.nextInt(100);
if (Num3 > 100) {
Num3 = Num3 - 100;
System.out.println("Number 3 Changed");
}
System.out.println("Number 1 :" + Num1);
System.out.println("Number 2 :" + Num2);
System.out.println("Number 3 :" + Num3);
}
}
Description: It searches for instances of identical expressions (i.e., they all evaluate to
the same value), and analyses whether it is worthwhile replacing them with a single
variable holding the computed value
import java.util.Random;
class CSE {
public static void main(String[] args) {
Description: It removes assignments to variables that are not subsequently read, either
because the lifetime of the variable ends or because of a subsequent assignment that will
overwrite the first value.
import java.util.Random;
class DCE {
public static void main(String[] args) {
int Num1;
int Num2 = 10;
Random random = new Random();
Num1 = random.nextInt(100);
Num1=Num1+1000;
Num1=Num1 + Num1/4;
System.out.println("Number 1 :" + Num1);
}
}
iv. Code tuning technique: Induction variable analysis and strength reduction
class Induction_Variable {
}
}
}
Description: Loop fission attempts to break a loop into multiple loops over the same
index range but each taking only a part of the loop's body. This can improve locality of
reference
class Loop_Fission {
public static void main(String[] args) {
int Count1, Num1[] = new int[100], Num2[] = new int[100];
for (Count1 = 0; Count1 < 100; Count1++){
Num1[Count1] = Count1;
Num2[Count1] = Num1[Count1];
}
System.out.println("Printing Array Num1 ");
Description: when two adjacent loops iterate the same number of times (whether or
not that number is known at compile time), their bodies can be combined as long as
they make no reference to each other's data.
class Loop_Fusion {
public static void main(String[] args) {
int Count1, Num1[] = new int[100];
for (Count1 = 0; Count1 < 100; Count1++)
{
Num1[Count1] = Count1;
}
for (Count1 = 0; Count1 < 100; Count1++)
{
System.out.println(Num1[Count1]);
}
}
}
class Loop_Splitting {
Background: Infosys follows coding standards for the programs written in order to improve
the maintainability aspect.
Problem Description:
a) A text file CodingStandards.java is provided to you in Supplied Source Code folder
within the Lab Guide folder. Identify the missing coding standards in the given source
code, correct them and execute the code. (The coding standards include
documentation, indentation, variable naming standards, proper comments, file
header, footer etc)
b) Write a program to add two numbers and display the sum as the output. Implement all
the coding standards applicable.
Topic 4 Arrays
4.1: Arrays
Problem Description: In Day 2 we had several Branch Id’s related to the various branches of
engineering in the college. The fees to be paid is different for different branches. The
business logic needs to be implemented to calculate the fees based on branch by using a data
structure.
Create an array for the branch Id’s and initialize them as follows:
Step 1: Open the file DemoReg.java with the main method written in Assignment 6 of Day 2.
In the main method, do the following:
a. Declare an integer array branchList and initialize it with the following values:
b. Declare a double array fees and initialize it with the following values:
Note: The branchList array and fees array are related as follows: the fees for
branchId in branchList[0] is fees[0], the fees for branchId in branchList[1] is
fees[1] and so on
c. Check whether the value of the local variable, branchId is present in the
branchList array
[Hint: make use of length property of the array]
i. If present, identify the fees for the specified branchId from the fees
array. Using the appropriate setter method, set the fees
a. Invoke the calculateFees() with 79 as an argument for marks
b. Using the corresponding getter methods, and display the details
as follows:
Registration Id :___________________
Fees :___________________
Step 2: Compile the programs – Registration.java, DemoReg.java, fix the errors if any. Did
you notice any difference in the way the array is declared and initialized compared to C
language?
Consider that the students joined a tutorial for various subjects as given below:
Table 7
Step 1: Create a file JaggedArray.java with a class JaggedArray containing the main method
Step 2: Initialize the array based on the above table and display the tutorials attended by
Delvin.
Estimated time: 20
Summary of this assignment:
Note:
x In C language, an array of strings is represented by a two-
dimensional array. In Java, array of strings is a single dimensional
array consisting of instances of String class
49 | P a g e Infosys Foundation Program
Infosys Limited Object Oriented Concepts Using Java
Topic 5 Strings
Problem Description: The student name and the branch name details of a particular student
has to be captured and validated.
Add the following mentioned in the class diagram of the existing Student class:
Step 1: Modify the Student class created (Student.java) in Assignment No. 8 of Day 2 to
include the instance variables and the methods whose prototype is given above:
If it is valid, return true, else set the value of branchName to CSE and display a
message “Invalid Branch Name, set to CSE” and return false.
Step 4: Add the following statements to the existing main method written in Demo class
(Demo.java in Assignment Number 5 of Day 2)
Create a reference variable of Student class(or use the existing object created earlier) with
the name studentOne and instantiate the same
a. Invoke the corresponding setter methods to set the values for the instance
variables as follows:
Table 4
studentId 1001
studentName Jackson
qualifyingExamMarks 95.0f
residentialStatus D
yearOfEngg 2
branchName CSE
Student Id :___________________
Step 7: Create reference variables of Student class with the name studentTwo and
instantiate the same
a. Invoke the corresponding setter methods to set the values for the instance
variables as follows:
Table 5
studentId 1002
studentName Jen
qualifyingExamMarks 68.0f
residentialStatus H
yearOfEngg 3
branchName ABC
Repeat Step 4.b for studentTwo created in Step 7, compile and execute the program. Do you
find a difference in the output? Why?
Problem Description: The permanent address and the residential address of the students
need to be captured. For this purpose, an Address class was identified on Day 1. Implement
the Address class as per the class diagram given below:
Step 1: Create a file Address.java and create the Address class as shown in the class diagram
Step 3: Create a file called DemoAddress.java and create a class called DemoAddress
containing the main method
Step 4: Create a reference variable of type Address and initialize the values of the instance
variables as given in table below using the appropriate setter methods:
Table 6
addressLine No.3,KT street
city Mysore
zip 570001
state Karnataka
Step 5: Use the corresponding getter methods display the details in the following format:
Address Line : ___________________
City : ___________________
Zip code : ____________________
State : ____________________
Problem Description: The Admin who is using the system has to be validated using a
username and password at the time of logging into the system. Create a login class for the
same.
Step 1: Create a class called Login in Login.java file as per the below mentioned class
diagram
Step 2: Initialize the usernames and passwords arrays with the values given below in a static
block:
Table 8
usernames admin finance student
passwords Admin Finance Student
b. A case sensitive comparison should be made for the instance variable password
against the passwords present in the passwords array and it should be the
password corresponding to the username
c. If the username and password are valid, return true
d. If not, return false
Step 6: Create a file DemoLogin.java containing a class DemoLogin which in turn has the main
method. In the main method
a. Create a reference variable of Login class with the name login
b. Invoke the validateLogin() method
i. If the return value is true, display a message “Login Successful”
ii. If not, display an error message “Login Denied”
Problem Description: Planet one, a leading data management group has been given the task
of storing the records of their one lakh employees. The record contains an email id whose
datatype is String. The logic for validation of the email id needs to be written and hence
implement the following class EmailCheck
EmailCheck
-emailId:String
+getEmailId():String
+setEmailId(String):void
+main(String[] args):void Æstatic
The validation rules for the email id check are as follows (to be implemented in main()):
Problem Description: The branch chosen by the student can be accepted by the program as
an argument. Implement the same using command line argument.
Use the DemoReg.java used in Assignment 1 of Day 3 to include command line arguments.
Step 1: In the DemoReg class remove the initialization for the branchId local variable
Step 2: Accept the branch Id as a command line argument. Initialize the branch Id to the
value of the command line argument after appropriate conversion (Hint: Use
Integer.parseInt()).
Step 3: The rest of the program remains the same. Compile the programs – Registration.java
and DemoReg.java and execute the code. Include the command line arguments.
Note: Follow the steps below to use the Command Line arguments to execute Java
Program in Eclipse
On the dialog box that appears, select the class to whose main method you want to pass the
command line arguments from the left hand side panel.
Then select the arguments tab on the right side of the dialog box and enter the values to be
passed in the text area corresponding to the Program arguments option.
Use a space to separate the values in case more than one argument is being passed and click
on the run button to execute the code with the set of arguments passed.
Topic 6 Relationships
6.1 – Inheritance
Problem Description: Hostelite and DayScholar are two classes which inherit from the
Student class. They represent the two different kinds of Student. The class diagram is as
given below:
Step 1: Create a new file Hostelite.java and define the Hostelite class which extends the
Student class as per the above class diagram
Step 2: Implement the constructor of Hostelite class and invoke the constructor of Student
class using the super keyword
Step 3: Compile the Student.java and Hostelite.java file and fix the errors if any
Step 4: Create a new file DayScholar.java and define the DayScholar class which extends the
Student class as per the above class diagram
Step 5: Implement the constructor of DayScholar class and invoke the constructor of Student
class using the super keyword
Step 6: Compile the DayScholar.java file and fix the errors if any
Step 7: Create a new file DemoInherit.java containing the DemoInherit class with the main
method
Table 12
Instance Variable Value to be initialized
hostelName Aaradhya
roomNumber 105
roomType double
studentName Tommy
qualifyingExamMarks 75.6f
residentialStatus H
branchName CSE
yearOfEngg 4
addressLine L-51,SriLabdhi Colony
city Chennai
state TamilNadu
zip 600004
(Hint: Create reference variables of Address class whenever an address needs to be stored)
Student Id :___________________
Student Name :___________________
Qualifying Marks :___________________
Residential Status :___________________
Current Year of Engineering :____________________
Branch Name :____________________
Permanent Address :____________________
Hostel Name :____________________
Room Number :____________________
Room Type :____________________
c. Create a reference variable of DayScholar class and instantiate the same with the
following values:
Table 13
Instance Variable Value to be initialized
For Residential Address
addressLine No.3, Choultry circle
City Mysore
state Karnataka
Zip 570017
distance 10
studentName Timmy
qualifyingExamMarks 80.0f
residentialStatus D
branchName CSE
yearOfEngg 4
For Permanant Address
addressLine No.L-82, West Fort
City Trivandrum
state Kerala
Zip 560015
(Hint: Create reference variables of Address class whenever an address needs to be stored)
Student Id :___________________
Student Name :___________________
Qualifying Marks :___________________
Residential Status :___________________
Current Year of Engineering :____________________
Branch Name :____________________
Residential Address :____________________
Distance :____________________
Permanent Address :____________________
Step 11: Compile, execute the program and verify the output
Problem Description: The firmware in the ticketing device used by the conductors in a public
transport system works on inputs from the conductor. The conductor,
x When hits a specific hotkey generates tickets from a preset start point and end
point
x When enters a start point and end point generates tickets from the corresponding
travel points
Ticket
-startPoint:int
-endPoint:int
63 | P a g e Infosys Foundation Program
Infosys Limited Object Oriented Concepts Using Java
-ticketAmount:int
+Ticket()
+Ticket(int,int)
+getStartPoint():int
+getEndPoint():int
+getTicketAmount():int
+validateTravelPoints():void
+calcTicketAmt():int
At the end of each calculation, display the amount of money to be paid and observe the
changes.
Going ahead, ensure a validation with validateTravelPoints() with the following criteria:-
x endPoint and startPoint must be greater than 0
x endPoint must always be greater than startPoint
6.2: Aggregation
Problem Description: The relationship between the Student and the Address class is that of
‘has-a’ relationship. Using a java program, the relationship between the two classes can be
established by holding a reference of the Address class inside Student class as every student
has an address.
64 | P a g e Infosys Foundation Program
Infosys Limited Object Oriented Concepts Using Java
Step 1: Use the Student.java file created in Assignment 1 of Day 4. Modify the class by adding
an instance variable of type Address. (Use the Address class created in Assignment 3 of Day 3)
Step 2: Modify the parameterized constructor to add the Address reference as a parameter
and initialize the permanantAddress with the reference passed
class DemoConstructor{
public static void main(String args[]){
Address address = new Address();
address.setAddressLine("No.333,ABC street");
address.setCity("Mysore");
address.setState("Karnataka");
address.setZip("570001");
Student studentSix = new Student();
studentSix.setPermanantAddress (address);
Step 5: Copy the Address.java file into the present working folder, compile the code.
Compile the Student.java and also compile the DemoConstructor.java program and fix errors
if any
Note:
x The reference of the Address class is placed as a member of the
Student class representing aggregation
6.3: Association
Problem Description: The relationship between Registration class and the PrintDetails class
is that of association. The calculateFees() method uses PrintDetails class for printing the
header of the bill. Implement this relationship using a Java program.
Step 1: Use the file Registration.java created on Day 2, Assignment 7 and make the changes
to the calculateFees() before the calculation of fees is done
a. Create a reference variable of PrintDetails class
b. Invoke the printHeader() method of the PrintDetails class by passing a
character ‘*’ to it
c. Invoke the printHeader() method of the PrintDetails class by passing a String "
Ricto Engineering College" to it
d. Invoke the printHeader() method of the PrintDetails class by passing a
character ‘*’ to it
e. Display the registrationId as shown below:
Registration Id: _________________________
Step 2: The rest of the implementation of the calculateFees() method remains the same
.Compile the file Registration.java
Step 3: Use the class DemoReg created in the file DemoReg.java with the main method on
Day 2. Remove the code written to display registrationId since it is now displayed in
calculateFees() of Registration class.
Step 4: Compile DemoReg.java and execute the code. Do you observe the printing of the
header? What is the relationship between the Registration and the PrintDetails class? How is it
different from aggregation?
Topic 7 Polymorphism
Problem Description: The Admin wants to print the header of the bill in multiple ways
depending on the need. This can be printing a single character n, number of times or printing
of String or printing a character specified number of times.
Create a class called PrintDetails with overloaded methods as shown in the class diagram:
Step 1: Create a file called PrintDetails.java which contains the PrintDetails class designed
as per the class diagram given above.
Step 3: Create a file DemoPrint.java containing the DemoPrint class with the main method.
68 | P a g e Infosys Foundation Program
Infosys Limited Object Oriented Concepts Using Java
Step 4: Create an object of PrintDetails class and instantiate the same. Invoke the
printHeader methods with the following values for the arguments
Table 11
Variables values
c *
no 20
s Ricto Engineering College
Note:
x Methods can be overloaded based on the number, sequence and type
of arguments
Modify the Student class created earlier (Student.java) to add the following mentioned in the
class diagram:
Step 1: Modify the Student class created earlier (Student.java) to include the definition for
the parameterized constructor as shown in above class diagram.
Step 2: Initialize the values of the instance variables appropriately using the values passed to
the parameterized constructor.
(Note: Ensure that the Student Id gets generated every time the default or the
parameterized constructor is called)
Step 3: Add the following statements to the existing main method written in Demo class
(Demo.java)
a. Create a reference variable of Student class with the name studentFive by
invoking the parameterized constructor of the student class by passing the
following values:
Table 10
studentName Jimmy
qualifyingExamMarks 688.0f
residentialStatus H
yearOfEngg 2
branchName ECE
Student Id :___________________
Student Name :___________________
Qualifying Marks :___________________
Residential Status :___________________
Step 7: Compile and Execute the program and verify the output. Did you notice that the
studentId is incremented by one for each of the object created? Did you also notice that
there are two versions of the constructor?
Note:
x The setter methods may be used for modification of instance variable
values
x The setter may also be used for setting the values of the instance
variables in the absence of a parameterized constructor
x Constructors can be overloaded
Problem Description: The firmware in the ticketing device used by the conductors in a public
transport system works on inputs from the conductor. The conductor,
x When hits a specific hotkey generates tickets from a preset start point and end
point
x When enters a start point and end point generates tickets from the corresponding
travel points
Ticket
-startPoint:int
-endPoint:int
-ticketAmount:int
+Ticket()
+Ticket(int,int)
+getStartPoint():int
+getEndPoint():int
71 | P a g e Infosys Foundation Program
Infosys Limited Object Oriented Concepts Using Java
+getTicketAmount():int
+validateTravelPoints():void
+calcTicketAmt():int
At the end of each calculation, display the amount of money to be paid and observe the
changes.
Going ahead, ensure a validation with validateTravelPoints() with the following criteria:-
x endPoint and startPoint must be greater than 0
x endPoint must always be greater than startPoint
Problem Description: Method overriding happens when a method defined in the parent class
is redefined in the derived classes. displayStudentInformation() has to be defined in the
Student class to display student information and overridden in the derived classes (Hostelite
and DayScholar) to display the respective class details.
Step 1: Use the file Student.java, Address.java, Hostelite.java and DayScholar.java files
created earlier
In the displayStudentInformation(),write the logic using the getter methods of the class and
display the details as follows: Notice how within the method, there is no need for
an object reference as the ‘this’ reference is
public void displayStudentInformation(){
System.out.println("Student Id : "+getStudentId());
System.out.println("StudentName : "+getStudentName());
System.out.println("Qualifying Marks : "+getQualifyingMarks());
System.out.println("Residential status :"+getResidentialStatus());
System.out.println("Current Year Of Engg : "+getYearOfEngg());
System.out.println("Branch Name : "+getBranchName());
System.out.println("Address:"+getPermanantAddress().getAddressLin
e()+getPermanantAddress().getCity()+getPermanantAddress().getState()+g
etPermanantAddress().getZip());
} Notice how the getPermanantAddress() method returns a
reference of Address class, which in turn is used to invoke
Step 2: Use the file Hostelite.java file created earlier, add a new method called
displayStudentInformation() as shown in the class diagram below:
Step 3: Use the file DayScholar.java file created earlier, add a new method called
displayStudentInformation() as shown in the class diagram below:
Step 4: Create a file DemoOverriding.java containing the DemoOverriding class with the
main method.
Step 5: Create an object each of the Hostelite and DayScholar class and instantiate them.
(Pass values for each of the instance variables through the parameterized constructor). Invoke
the displayStudentInformation() using the objects individually.
Problem Description: The calculation of the fees paid by a student is based on the following:
x Qualifying marks
x Hostelite or Day scholar
x Year of Engineering
x Additional fees to be paid
The calculateFees() of Registration class has to be modified based on whether the student is
a hostelite or a day scholar.
Step 2: Use the Registration.java created earlier and add the following to the Registration
class:
x A static counter variable
x Constructor of the Registration class
x Change the prototype of the calculateFees() to pass a Student reference to it
int discount=0;
if(stu.validateStudentName() ==true){
if(stu.validateBranchName() ==true){
if(stu.validateExamMarks() ==true){
if(stu.getQualifyingMarks()>=85
&& stu.getQualifyingMarks()<=100){
discount=12;
}
………………………………..
}
c. Identify the fees based on the branch name of the student using the student
reference as per the below table:
Table 14
branchName branchFees
CSE 25575
ECE 15500
EEE 33750
MECH 8350
Bio-Tech 20500
d. Identify the qualifying marks of the student (using the student reference and
getter method) and calculate the discount by declaring a local variable discount.
(In Day 2, recall that the marks was passed as an argument to the calculateFees()
). The table for your reference is as follows:
Table 15
qualifyingMarks Discount in %
85-100 12
75-84 7
65-74 0
Table 16
Instance Variable Value to be initialized
hostelName Aaradhya
roomNumber 105
roomType double
studentName Tommy
qualifyingExamMarks 75.6f
residentialStatus H
branchName CSE
yearOfEngg 4
addressLine L-51,SriLabdhi Colony
city Chennai
state TamilNadu
zip 600004
(Hint: Create reference variables of Address class whenever an address needs to be stored)
Do you notice here that a reference variable of a parent class is instantiated with an
object of derived class. Thus a parent reference may point to an object of itself or its
child classes which is one aspect of dynamic polymorphism
Table 17
(Hint: Create reference variables of Address class whenever an address needs to be stored)
Step 5: Compile Registration.java and DemoDynamic.java files, execute the program and
verify the output
Objective: Understand abstract keyword for usage with class and method
Problem Description: When at least one method in a class is not complete (ie. abstract)
then, the class holding that method also needs to be declared abstract. The
displayStudentInformation() is a good candidate for abstract method, as the same
information can be accessed and displayed in the overridden method. The Student class,
therefore has to be declared abstract.
Step 1: Use the file Student.java, Address.java, Hostelite.java and DayScholar.java files
created earlier.
Step 2: Make the Student class and the displayStudentInformation() present in the class
abstract. This is needed because the Hostelite and the DayScholar classes override this
method. There is no definition to this method as shown below:
……..
abstract
ract public void displayStudentInformation();
}
Step 3: Use the file Hostelite.java file created earlier. In the displayStudentInformation(),
invoke the getter methods of the Student class explicitly (remove the invocation of the
displayStudentInformation() using super ) to display the values of the instance variables of
the Student. This is followed by the display of details of the Hostelite class members as
shown below:
class Hostelite{
……….
public void displayStudentInformation(){
System.out.println("Student Id : "+getStudentId());
System.out.println("StudentName : "+getStudentName());
System.out.println("Qualifying Marks : "+getQualifyingMarks());
System.out.println("Residential status :"+getResidentialStatus());
System.out.println("Current Year Of Engg : "+getYearOfEngg());
System.out.println("Branch Name : "+getBranchName());
System.out.println("Address:"+getPermanantAddress().getAddressLine()+ge
tPermanantAddress().getCity()+getPermanantAddress().getState()+getPerma
nantAddress().getZip());
System.out.println("Hostel Name : "+getHostelName());
System.out.println("Room Number : "+getRoomNumber());
System.out.println("Room Type : "+getRoomType());
}
}
8.2: Interfaces
Problem Description: Interfaces represent a special form of classes containing only abstract
methods. They are deployed when some generic behavior is required across many classes
(both related and unrelated). The student has to pay infrastructure and library fees along
with yearly fees. Library and Infrastructure fees are constant values. Implement the same
using an interface.
Step 3: Use the Registration.java created in Assignment 2 of Day 5. Use the implements
keyword so that the Registration class implements the AdditionalFees interface and
overrides the computeAddtionalFees() as shown below:
Topic 9 Packages
Problem Description: Create, compile and execute the program contained in a package and
access the data members with different access specifiers in different packages
To create a new package, right click on the src folder in your project and select
NewÆPackage
Enter the package name in the dialog box and click on finish.
This would create a new package in the project explorer as shown below.
To create a new class in this package, right Click on this newly created package and create
new class b following the normal process to create a class.
This would add the class in the new package as shown below.
package pack1;
public class Base{
private int privateNum;
int defaultNum;
protected int protectedNum;
public int publicNum;
public Base(){
privateNum=90;
defaultNum=900;
protectedNum=9000;
publicNum=90000;
}
}
Problem Description: Organize the classes created for the case study into a package.
package courseRegistration;
package Main;
import courseRegistration.*;
Problem Description: Find the step count for the following code
a. Sum(a,n)
{
S= 0;
for (i=1;i<=n;i=i+1)
S=S+a[i]
return S
}
b. SequentialSearch(a,x,n)
{
i=n;
a [0]=x;
while(a [i]!= x) do
i = i-1
return i
}
c. Smallest(a,n)
{
small=a[1];
for(i=1;i<=n;i=i+1)
{
if(a[i] < small)
{
small=a[i];
}
}
return small;
}
Summary of this assignment:
In this assignment, you have learnt
x Determining the step count for an algorithm
Objective: To learn how to determine the amount of time a given algorithm would consume.
Problem Description: Find the order of time complexity for the following code snippets and
represent it in Big O notation.
e. for(iCount=0;iCount<iNum; iCount=iCount+2){
…
}
f. for(iCount=1;iCount<iNum; iCount=iCount*2){
…
}
h. for(iCount1=0;iCount1<iNum;iCount1= iCount1+1){
for(iCount2=0;iCount2<iNum;iCount2= iCount2+1)
{
…..
}
}
i. for(iCount1=0;iCount1<iNum;iCount1= iCount1+1)
{
for(iCount2=1;iCount2<=iCount1;iCount2= iCount2+1)
{
…
}
}
j. for(iCount1=0;iCount1<iNum;iCount1= iCount1+1)
{
for(iCount2=0; iCount2<iNum; iCount2= iCount2+2)
{
…
}
}
k. for(iCount1=0;iCount1<iNum;iCount1= iCount1+1)
{
for(iCount2=1;iCount2<n;iCount2=iCount2*2)
{
…
}
}
l. for(iCount1=0;iCount1<iNum;iCount1= iCount1+1)
{
for(iCount2=iNum; iCount2>0; iCount2= iCount2/2)
{
…
}
}
…
}
}
else {
for(iCount=0;iCount<iNum/2;iCount= iCount+1)
{
…
}
}
Objective: To understand how to calculate the worst case time complexity of well-known
algorithms.
Background: This assignment helps you to understand how to identify the time complexity for
search and sort techniques.
Problem Description:
1. Linear search is a well-known search algorithm to search key element in a given list of
elements. The linear search is applied on the set of items that are not arranged in any
particular order. In linear search, the searching process starts from the first item. The
searching is continued till either the item is found or the end of the list is reached
indicating the item is not found. The items in the list are assumed to be unique. The
algorithm can be expressed as below.(Consider ‘n’ as the total number of elements in the
list)
Begin
for (i = 1,i<=n; i=i+1)
If (target = a[i]) then
End with output as i
End For
End with output as none
Identify the worst case time complexity for above search algorithm and express in the form of
Big Oh notation.
2. Bubble Sort is a well-known algorithm for sorting the elements in a specific order. The
algorithm can be expressed as below. (Consider aiNum as an integer array and num as the
total number of elements in the array need to be sorted
Summary of this assignment: In this assignment, we learn how to get the worst case time
complexity of well-known algorithms.
Problem Description:
Analyze the following code snippet and tune the code snippet wherever necessary.
Note: For all the assignments on code tuning techniques, the tuned code can be submitted in
a .txt file.
iNum=1;
while(iNum<= iX/2)
{
afSal[iNum] = 1.5* afSal[iNum];
iNum=iNum+1;
}
Problem Description:
Analyze the following code snippet and tune the code snippet wherever necessary.
Note: For all the assignments on code tuning techniques, the tuned code can be submitted in
a .txt file.
Problem Description:
Analyze the following code snippet and tune the code snippet wherever necessary.
Note: For all the assignments on code tuning techniques, the tuned code can be submitted in
a .txt file.
for( iNum=2;iNum<10;iNum++){
92 | P a g e Infosys Foundation Program
Infosys Limited Object Oriented Concepts Using Java
aiArr[1]=10;
aiArr[iNum]=iNum*aiArr[iNum-1];
}
Problem Description:
Analyze the following code snippet and tune the code snippet wherever necessary.
Note: For all the assignments on code tuning techniques, the tuned code can be submitted in
a .txt file.
iNum = 10;
for(iIndex=0;iIndex<10;iIndex++){
if(iNum>20)
System.out.println(iNum +“ is greater than 20”);
else
System.out.println(iNum +“%d is less than or equal to 20”);
---------------------
---------------------
}