Sunteți pe pagina 1din 180

Assignments for OO programming using Java

COPYRIGHT NOTICE
2013 Infosys Limited, Bangalore, India. All Rights Reserved.
Infosys believes the information in this document is accurate as of its publication date; such
information is subject to change without notice. Infosys acknowledges the proprietary rights of
other companies to the trademarks, product names and such other intellectual property rights
mentioned in this document. Except as expressly permitted, neither this documentation nor
any part of it may be reproduced, stored in a retrieval system, or transmitted in any form or by
any means, electronic, mechanical, printing, photocopying, recording or otherwise, without the
prior permission of Infosys Limited and/ or any named intellectual property rights holders
under this document.
Education, Training and Assessment Department
Infosys Limited
Electronics City
Hosur Road
Bangalore 561 229, India.
Tel: 91 80 852 0261-270
Fax: 91 80 852 0362
www.infosys.com
mailto:ETA@infosys.com

CONFIDENTIAL

CONFIDENTIAL

Document Revision History

Version

Date

Author(s)

Reviewer(s)

Description

Mohanakrishna BG
Manjunatha
Satyanarayana
Vijay Kumar Dani

1.0

Jan 2014

Meenakshi S
Anooja Mary Jacob
Nithyanandalakshmi

1.1

Feb 2014

Anooja Mary Jacob


Nithyanandalakshmi

Meenakshi S

1.2

Apr-May
2014

Anooja Mary Jacob

Meenakshi S

1.3

May 2014

Anooja Mary Jacob

Meenakshi S

Initial Draft
Resequenced to account for
1 day increase in course
Resequenced and made into
two courses for campus
batches 2014
Minor changes done after
pilot for campus batches
2014

Customization Revision History

Version

Date

Author(s)

Reviewer(s)

Description

4.0

Sep 2014

K.N.Vani

Dr. Suresh P.,


Manisha

Customization for Campus


Connect FP 4.0 release

CONFIDENTIAL

CONFIDENTIAL

CONTENTS
COPYRIGHT NOTICE ............................................................................................................................................................. ii
Document Revision History .................................................................................................................................................. iv
Customization Revision History ........................................................................................................................................... iv
CONTENTS ............................................................................................................................................................................. vi
Assignments for OO programming using Java ...................................................................................................................... 1
Context................................................................................................................................................................................... 1
Guidelines .............................................................................................................................................................................. 1
Problem Solving Assignments ............................................................................................................................................... 1
Introduction to Problems: Assignment 1 ............................................................................................................................... 1
Demo : Algorithms: Assignment 2 ........................................................................................................................................ 2
Demo : Algorithms and its representation: Assignment 3 ..................................................................................................... 2
Demo : Pseudo-code Testing: Assignment 4 ......................................................................................................................... 3
Demo - Algorithm Properties: Assignment 5 ........................................................................................................................ 5
Algorithm Properties: Assignment 6 ..................................................................................................................................... 5
Programming Constructs in Java - Assignments .................................................................................................................. 6
Observations from a real world problem - Assignment 7 ...................................................................................................... 6
Assignment 8: Programming constructs in Java .................................................................................................................... 7
Assignment 9-A: Using Eclipse IDE to create and execute Java Program ............................................................................ 7
Assignment 9-B: Programming constructs in Java - Demo ................................................................................................ 18
Assignment 10: Programming constructs in Java Hands on practice .............................................................................. 19
Assignment 11: Control Structures Observations from a real world problem .................................................................. 19
Assignment 12: Selection Control Structures Demo ........................................................................................................ 20
Assignment 13: Selection Control Structures Hands on practice...................................................................................... 22
Assignment 14: Iterational Control Structures - Demo........................................................................................................ 23
Assignment 15: break statement - Demo ............................................................................................................................. 25
Assignment 16: continue statement - Demo ........................................................................................................................ 25
CONFIDENTIAL

Assignment 17: Iteration Control Structure - Debugging .................................................................................................... 26


Assignment 18: Control Structures Hands on practice ..................................................................................................... 27
Assignment 19: Type Conversion and Casting Demo ...................................................................................................... 27
Assignment 20: Type Conversion and Casting Hands on practice ................................................................................... 31
Object Oriented Fundamentals- Assignments..................................................................................................................... 32
Assignment 21: A system engineers story Observations ................................................................................................. 32
Assignment 22: Object Oriented Concepts - Quiz ............................................................................................................... 36
Assignment 23: Introduction to UML.................................................................................................................................. 36
Assignment 24: Classes & Objects Hands-on................................................................................................................... 38
Assignment 25: Coding Standards ....................................................................................................................................... 39
Assignment 26: Reference Variables and Objects in Memory ............................................................................................ 40
Assignment 27: Methods Pass by value & Reference- A Simple Demo ......................................................................... 41
Assignment 28: Methods Pass by reference - Hands on practice...................................................................................... 45
Assignment 29a: Recursion Demo.................................................................................................................................... 47
Assignment 29b: Recursion ................................................................................................................................................ 49
Assignment 30: this reference - Demo................................................................................................................................. 50
Data Structures: Assignment 31........................................................................................................................................... 52
Data Structures: Assignment 32........................................................................................................................................... 53
Demo : Data Structures - Array: Assignment 33 ................................................................................................................. 53
Data Structures- Array: Assignment 34 ............................................................................................................................... 55
Data Structures- Array: Assignment 35 ............................................................................................................................... 55
Data Structures- Array: Assignment 36 ............................................................................................................................... 56
Arrays Assignment 37 ...................................................................................................................................................... 57
Data Structures- Linked List: Assignment 38 ...................................................................................................................... 57
Data Structures - Stack: Assignment 39 .............................................................................................................................. 59
Data Structures- Stack: Assignment 40 - Demo .................................................................................................................. 59
Data Structures- Stack: Assignment 41 ............................................................................................................................... 63
Data Structures- Queue: Assignment 42 .............................................................................................................................. 63
Data Structures- Queue: Assignment 43 .............................................................................................................................. 64
Advanced (Non-linear) Data Structures - Trees: Assignment 44......................................................................................... 65
Advanced Data Structures - Binary Search Tree: Assignment 45 ....................................................................................... 66
Advanced Data Structures - Binary Search Tree: Assignment 46 ....................................................................................... 68
Assignment 47: Arrays - Quiz ............................................................................................................................................. 68
Assignment 48: Arrays - Demo ........................................................................................................................................... 69
Assignment 49: Strings Observations from Retail Application ........................................................................................ 71
Assignment 50: Strings - Quiz ............................................................................................................................................. 71
Assignment 51: Strings Demo .......................................................................................................................................... 73
Assignment 52: Strings - Quiz ............................................................................................................................................. 76
Assignment 53: Constructors & Static keyword Observations from Retail Application .................................................. 79
CONFIDENTIAL

Assignment 54: Constructors Default Constructor - Demo .............................................................................................. 79


Assignment 55: Constructors Parameterized Constructor - Demo ................................................................................... 83
Assignment 56: static keyword - Demo ............................................................................................................................... 85
Assignment 57: Command Line Arguments Demo .......................................................................................................... 88
Algorithm Design Techniques: Assignment 58 ................................................................................................................... 94
Algorithm Design Techniques: Assignment 59 ................................................................................................................... 95
Algorithm Design Techniques: Assignment 60-A ............................................................................................................... 97
Algorithm Design Techniques: Assignment 60-B ............................................................................................................... 98
OO constructs II ................................................................................................................................................................ 99
Assignment 61: Method Overloading- Observations from Retail application ..................................................................... 99
Assignment 62: Method Overloading Demo .................................................................................................................. 100
Assignment 63: Method Overloading - Quiz ..................................................................................................................... 101
Assignment 64: Constructor Overloading Demo ............................................................................................................ 104
Assignment 65: Constructor Overloading Hands on practice ......................................................................................... 106
Assignment 66: Relationships Demo .............................................................................................................................. 107
Assignment 67: Inheritance Demo.................................................................................................................................. 109
Assignment 68: Inheritance - Quiz .................................................................................................................................... 115
Assignment 69: Aggregation Demo................................................................................................................................ 119
Assignment 70: Association Demo ................................................................................................................................. 122
Assignment 71: Method Overriding Observations from Retail application .................................................................... 125
Assignment 72 Method Overriding - Demo ...................................................................................................................... 126
Assignment 73: Dynamic polymorphism Observations from Retail Application........................................................... 129
Assignment 74: Dynamic polymorphism A Simple Demo ............................................................................................. 130
Assignment 75: Dynamic polymorphism - Demo ............................................................................................................. 132
Assignment 76: abstract keyword Observations from Retail application ........................................................................ 134
Assignment 77: abstract keyword A Simple Demo ........................................................................................................ 135
Assignment 78: abstract keyword Hands-on ................................................................................................................... 137
Assignment 79: Interfaces Observations from Retail application ................................................................................... 137
Assignment 80: Interfaces - Demo .................................................................................................................................... 138
Assignment 81: Packages Observations from Retail Application................................................................................... 139
Assignment 82: Packages - Demo ..................................................................................................................................... 139
Assignment 83: A System Engineers story continued ................................................................................................... 140
Assignment 84: Code Optimization - Observations from a business application .............................................................. 141
Assignment 85: Source Code tuning techniques Demo 1 ............................................................................................... 141
Assignment 85: Source Code tuning techniques Demo 2 ............................................................................................... 142
Assignment 85: Source Code tuning techniques Demo 3 ............................................................................................... 144
Assignment 85: Source Code tuning techniques Demo 4 ............................................................................................... 145
Assignment 85: Source Code tuning techniques Demo 5 ............................................................................................... 146
Assignment 85: Source Code tuning techniques Demo 6 ............................................................................................... 147
CONFIDENTIAL

Assignment 85: Source Code tuning techniques Demo 7 ............................................................................................... 148


Assignment 86: Clean Code Hands on Practice.............................................................................................................. 149
Assignment 87: Unit testing - Demo ................................................................................................................................. 157
Assignment 88: Boundary value analysis Demo ............................................................................................................ 159
Assignment 89: Boundary value analysis Hands on practice ......................................................................................... 161
Assignment 90: Equivalence partitioning- Demo .............................................................................................................. 163
Assignment 91: Equivalence partitioning- Hands on practice ........................................................................................... 165
Assignment 92: Logic Coverage(Statement) Demo 1 .................................................................................................... 166
Assignment 92: Logic Coverage (Branch) Demo 2 ........................................................................................................ 166
Assignment 92: Logic Coverage (Condition) Demo 3 ................................................................................................... 167
Assignment 92:Logic Coverage (Compound Condition) Demo 4 ................................................................................... 168
Assignment 92: Logic Coverage (Path Condition) Demo 5 ........................................................................................... 169

CONFIDENTIAL

Infosys Limited

Assignments for OO programming using Java part1

Assignments for OO programming using Java


Context
This document contains assignments to be completed as part of the hands on session
for the course - OO programming using Java

Guidelines

The assignments guide has been designed to give hands on experience to


map/apply the concepts learnt in the theory session with practical assignments.
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
These assignments contain coding exercises, debugging exercises, coding
standards exercises assignments
The case study based assignments are threaded, which can be built
incrementally. This will help understanding the concepts and building a complete
application
The estimated time would help a learner to solve problems given a deadline
The assignments need to be completed as instructed by the facilitators
Assignments marked as Demo can be used by the faculty during lecture
and students need to compile and execute it using Eclipse

Problem Solving Assignments


Introduction to Problems: Assignment 1
Objective: Given a business scenario, be able to classify and arrive at an approach for
solving the problem
Problem Description: Problems are of different types. Computers have been
effectively used to solve many complex problems in all domains. Domains like airlines,
retail, education, and many more have effectively used computers to solve their day-today problems and still there is lot of scope for computers to create impact and add value
in multiple dimensions.
Consider the problem of designing a portal for student management system used for
registering students to various branches and calculation of their grades in an
Engineering college.
Decompose the problem by identifying the sub problems to at least three levels.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 1 of 170

Infosys Limited

Assignments for OO programming using Java part1

Hint: You can refer the problem decomposition provided in the slides for designing an
online ticket booking problem.
Estimated Time: 15 minutes

Demo : Algorithms: Assignment 2


Objective: Given a problem, be able to solve the problem by representing the logic as
an algorithm.
Problem Description: Consider the scenario of processing marks of a student John for
a course as part of a student management system. The assumption is that John takes
exams in five different subjects. Find the total and average marks scored by John.
The logic to solve the given problem can be represented using an algorithm. We may
use English statements to represent the same.
Note the name of the algorithm

Algorithm
Input
Output

:
:
:

PROCESS_MARKS
Marks of 5 subjects
Total marks and the average marks

Note the inputs to the algorithm

Step 1: Accept MARKS1, MARKS2, MARKS3, MARKS4, MARKS5


Note the output of the algorithm

Step 2: Sum up the marks in the five subjects and store in sum
Step 3: Display the sum
Step 4: Divide the sum by 5 and store the average marks

Note the sequence of steps

Step 5: Display the average marks


Estimated time: 5 minutes
Summary of this assignment: In this assignment you have learnt that algorithms can
be used to represent the logic to solve a problem

Demo : Algorithms and its representation: Assignment 3


Objective: Given a problem, be able to solve the problem by representing the logic
using pseudo code representation.
Problem Description: Consider the scenario provided in the previous assignment.
Represent the same logic using pseudo code to solve the problem.
Name of the pseudo- code

PROCESSING_MARKS

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 2 of 170

Infosys Limited

Assignments for OO programming using Java part1

1. input M1, M2, M3, M4, M5

Note the input operation and the variables

2. total =0
Note that the statements are executed in sequence

3. total= M1+M2+M3+M4+M5
4. display total
5. average=0

Note the usage of operators, = and / operators

6. average=total/5
7. display average
Estimated Time: 5 minutes

Summary of this assignment: In this assignment you have observed, how algorithms
can be represented using pseudo-code.

Demo : Pseudo-code Testing: Assignment 4


Objective: Given a problem, be able to solve the problem using sequential, iteration
and selection patterns and represent the logic using pseudo-code and test using dry run
technique.
Problem Description: Consider the scenario of processing marks of a student John for
a course as part of a student management system. The assumption is that John takes
exams in five different subjects. Find out the grade scored by John as per the table
given below.
Module Test Marks
>= 80
>=73 and < 80
>=65 and < 73
>=55 and < 65
<55

Grade
A
B+
B
C
D

Consider the following pseudo-code:


CALCULATE_GRADE
1.

input Module_Test_Marks

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 3 of 170

Infosys Limited

2.

if (Module_Test_Marks > = 80) then

3.
4.

display Grade is A
else if (Module_Test_Marks > = 73) then

5.
6.

display Grade is B+
else if (Module_Test_Marks >= 65) then

7.
8.

display Grade is B
else if (Module_Test_Marks >= 55) then

9.
10.

display Grade is C
else

11.
12.

Assignments for OO programming using Java part1

display Grade is D
end-if

Part I: This pseudo-code needs to be tested using trace table for input values 95 and
63.

Line
number

ModuleTestMarks

ModuleTestMarks >
= 80

ModuleTestMarks >
= 73

ModuleTestMarks >=
65

Module-TestMarks >= 55

95

true

3
1
2

Output

Grade is A
63
false

false

false

true

Grade is C

Part II: Please fill the trace table for input values 75, 42 and 68
Estimated time: 20 minutes
Summary of this assignment: In this assignment you have learnt how to dry run and
test pseudo-code using trace table.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 4 of 170

Infosys Limited

Assignments for OO programming using Java part1

Demo - Algorithm Properties: Assignment 5


Objective: Given an algorithm to solve a computational problem, be able to identify the
attributes of good algorithm design
Problem Description: Identify the properties of a good algorithm
TOTAL_MARKS
Finiteness

1. for count =1 to 100

Effectiveness

Input

2.

Total =0

3.

Input M1, M2, M3, M4, M5.


Definiteness
(Unambiguous)

4.

Total= M1+M2+M3+M4+M5

5.

display Total
Output

6. end-for

Note: Effectiveness- Operations to be primitive and verifiable using pencil and paper
Estimated time: 5 minutes
Summary of this assignment: In this assignment you have learnt about the properties
of a good algorithm.

Algorithm Properties: Assignment 6


Objective: Given an algorithm to solve a computational problem, be able to identify the
attributes of good algorithm design
Problem Description: Identify the properties of algorithm which are not followed in the
following algorithms given:

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 5 of 170

Infosys Limited

Assignments for OO programming using Java part1

Algorithm :
SUM_FIRST_TEN_NUMBERS
counter = 1
while (counter>=1) do
sum=sum + counter
end-while
display sum
Estimated Time: 5 minutes
Summary of this assignment: In this assignment you have learnt about the properties
of a good algorithm.

Programming Constructs in Java - Assignments

Observations from a real world problem - Assignment 7


Objective: Given a real world problem, be able to understand the need for
programming fundamentals such as identifiers, variables, data types etc
Problem Description: A retail store management wants to automate the process of
generating the bill amount for its customers. As an initial step, they want to initialize the
bill details of a customer as given below:
Bill id should be 1001, customer id should be 101 and bill amount should be 199.99.
After initializing, all the values must be displayed in the format given below:

Bill Id:1001
Customer Id:101
Bill Amount:Rs.199.99
Analyze the above problem statement and answer the following questions:
1. What do you think is needed to write a program to implement the solution for the
above problem statement?
Estimated time: 5 minutes

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 6 of 170

Infosys Limited

Assignments for OO programming using Java part1

Summary of this assignment: In this assignment, you have understood the need of a
high level programming language and programming fundamentals such as identifiers,
variables, data types, operators etc

Assignment 8: Programming constructs in Java


Objective: Given a real world problem, be able to identify the data types of the
variables required to solve it
Problem Description: For the previous assignment, identify the data types that may
be used to represent bill id, customer id and bill amount.
Estimated time: 5 minutes
Summary of this assignment: In this assignment, you have learnt to identify the data
type for the variables based on the real world problem

Assignment 9-A: Using Eclipse IDE to create and execute Java


Program
Objective: Learn how to use the Eclipse IDE to create and execute java programs.
About Eclipse
Eclipse is a multi-language Integrated Development Environment (IDE) and it has an
extensible plug-in system. It can be used to develop applications in Java and also other
programming languages including C, C++, Ruby, Perl, Python, COBOL , PHP etc. by
means of various plug-ins.
Using the Eclipse IDE
Starting Eclipse and Giving Workspace Information
To start the Eclipse IDE, double click the Eclipse.exe available on your desktop
Fig. 1 Starting Eclipse

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 7 of 170

Infosys Limited

Assignments for OO programming using Java part1

Fig. 2 Eclipse Loading


Once started a prompt will open which will ask you to enter the workspace information
as shown in Fig. 3. A workspace is a folder where all the projects created in Eclipse are
saved. Create a folder in your desired path and give the correct path as shown below.

Fig. 3 Work Space

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 8 of 170

Infosys Limited

Assignments for OO programming using Java part1

Once loaded, you will see the Welcome tab as shown in Fig. 4. Close this Welcome tab
to go to the Project Window.

Fig. 4 Welcome Screen


Next go to the Window menu and select the perspective as Java perspective as shown
in Fig. 5. (Window Open Perspective Java)

Fig. 5 Changing Perspective

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 9 of 170

Infosys Limited

Assignments for OO programming using Java part1

Selecting the java perspective will give you the screen as shown in Fig. 6.

Fig. 6 Project Explorer


Creating a New Project
In Eclipse a workspace can contain one or more projects and each project usually
contains a java application. Each application may contain one or more java files.
To create a new project, go to File New Project as shown in Fig. 7.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 10 of 170

Infosys Limited

Assignments for OO programming using Java part1

Fig. 7 New Project


Select the option Java Project under the Java category as shown in Fig. 8.

Fig. 8 Project Type


Enter a relevant project name and click on finish button as shown in Fig. 9.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 11 of 170

Infosys Limited

Assignments for OO programming using Java part1

Fig. 9 Project Details


This will create a project and you can see the same in the package explorer as
shown in Fig. 10.

Fig. 10 Project Directory Structure

Writing Your First Java Program

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 12 of 170

Infosys Limited

Assignments for OO programming using Java part1

To write your first java program you must first create a class. Right click on the src
folder in the project and go to New Class as shown in Fig. 11.
The concept of packages will be explored later in the OOP module. Eclipse will
create your program in a default package if you follow the given steps.

Fig. 11 New Class


Enter the class name as shown in Fig. 12 and check the first box if you want the
main method to be added to this class and then click on finish.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 13 of 170

Infosys Limited

Assignments for OO programming using Java part1

Fig. 12 Class Details


This will add a class to the project with the main method prototype as shown in
Fig. 13.
You can now add your program logic in the required method, create new methods
etc. in this class. You can also add new classes to the project by following the
above steps.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 14 of 170

Infosys Limited

Assignments for OO programming using Java part1

Fig. 13 Sample Program


Executing Your Java Program
To execute a class, right click on the class-name in the project explorer and go to
Run As Java Application as shown in Fig. 14.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 15 of 170

Infosys Limited

Assignments for OO programming using Java part1

Fig. 14 Executing the Program


The output of the program will be displayed in the Console Tab as shown in Fig.
15.

Fig. 15 Output Window


Dealing with Compilation Errors
If your program has compilation errors then it will be highlighted in your code by
red colored marks and symbols as shown in Fig. 16.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 16 of 170

Infosys Limited

Assignments for OO programming using Java part1

Fig. 16 Compilation Errors


To know what the compilation error is and to obtain hints on how to solve the
errors just move your mouse over to the error symbol.
The error details will be highlighted as shown in Fig. 17.

Fig. 17 Hints to resolve the error


Estimated time: 15 min
Summary of this assignment: You have now learnt how to create projects and how to
create, compile, debug and execute a simple java program using Eclipse IDE.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 17 of 170

Infosys Limited

Assignments for OO programming using Java part1

Assignment 9-B: Programming constructs in Java - Demo


Objective: Given a real world problem, be able to identify the variables and operators
required to solve the problem and implement it using a high level programming
language like Java
Problem Description: Write a Pseudocode and java program to implement the real
world problem discussed in Programming constructs in Java Assignment 7. Compile
and execute the program using Eclipse IDE.
You may want to refer to Programming constructs in Java Assignment 9-A to
understand how Eclipse IDE may be used for writing, compiling and executing a java
program.

INITIALIZE_VARIABLES_DISPLAY
1. Bill_id = 1001
2. Customer_id = 101
3. Bill_Amount = 199.9
4. display "Bill Id:"+billId
5. display "Customer Id:"+customerId
6. display "Bill Amount:Rs."+billAmount
Moreonclassandmain()willbediscussedlater.Inthis
section,wewillonlybeconcentratingonthelogic
class Retail {
writteninsidemain()
public static void main(String[]args){
int billId=1001;
Notethatthesevariablesarealsoknownaslocalvariablesas
int customerId=101;
theyaredeclaredinsidemain().Moreonlocalvariableswillbe
float billAmount=199.99f; discussedlater.
System.out.println("Bill Id:"+billId);
System.out.println("Customer Id:"+customerId);
System.out.println("Bill Amount:Rs."+billAmount);
}
}
NotetheuseofSystem.out.println()statementfor
displayofconsoleoutput

Estimated time: 10 minutes


Summary of this assignment: In this assignment, you have understood how to
implement the solution for a simple real world problem using variables and operators

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 18 of 170

Infosys Limited

Assignments for OO programming using Java part1

Assignment 10: Programming constructs in Java Hands on


practice
Objective: Given a real world problem, be able to identify the variables and operators
required to solve the problem and implement it using a high level programming
language like Java
Problem Description: The finance department of a company wants to calculate the
monthly pay of one of its employee. Monthly pay should be calculated as mentioned in
the below formula and display all the employee details.
Monthly Pay = Number of hours worked in a week * Pay rate per hour * No. of weeks in
a month
Note:
The number of hours worked by the employee in a week should be considered as 40,
Pay rate per hour should be considered as Rs.400 and
Number of weeks in a month should be considered as 4
Write Pseudo code and Java program in Eclipse to implement the above real world
problem.
Estimated time: 20 minutes
Summary of this assignment: In this assignment, you have learnt to implement the
solution for a simple real world problem using variables and operators

Assignment 11: Control Structures Observations from a real


world problem
Objective: Given a real world problem be able to understand the need for control
structures and operators to implement the logic and solve the problem
Problem Description: The scenario discussed in Programming Fundamentals
Assignment 7 is revisited here to include bill calculation logic for a customer. The retail
store management wants to automate the process of generating the bill amount for its
customers.
The business rules/constraints are given below:
1. Assume that there is only one customer and one item purchased by the customer
2. The item ids of the items sold by the retail store are 5001, 5002, 5003, 5004 and
5005
3. Quantity purchased by the customer must be greater than 0 and less than 5
4. Item Price must be minimum Rs.5
5. If the constraints mentioned in 2, 3 and 4 are satisfied, bill amount must be
calculated based on the quantity purchased and item price.Otherwise,

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 19 of 170

Infosys Limited

Assignments for OO programming using Java part1

appropriate error message(s) must be displayed and bill amount must be


considered as 0
6. The retail store also wants to give some discount for some of the item ids.
Discount has to be identified as per the table given below:

ItemId

Discount in %

5001
5002
5003
Others

10
15
12
0

7. Customer Id, Bill Id, Item Id, Item Price and Quantity purchased by the customer
can be assumed to be as mentioned below:
Bill Id:1001
Customer Id:101
Item Id:5002
Item Price:Rs.55.0
Quantity purchased:4
The retail store wants to calculate the discount percentage and bill amount for the
customer based on the details given above and display all the details of the customer.
Answer the following questions:
What do you think is needed to implement this scenario?
Estimated time: 5 minutes
Summary of this assignment: In this assignment, you have understood the need of
operators and control structures using a real world problem

Assignment 12: Selection Control Structures Demo


Objective: Given a real world problem be able to understand the need for control
structures and operators to implement the logic and solve the problem
Problem Description: Write a java program to implement the real world problem
discussed in Programming Fundamentals Assignment 11.

class Retail {
public static void main(String[]args){

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 20 of 170

Infosys Limited

Assignments for OO programming using Java part1

int billId=1001;
Localvariables
int customerId=101;
int itemId=5002;
billAmountisalocalvariablewhichmustbe
float itemPrice=55.0f;
initializedto0.Thisisrequiredbecausethereare
int quantityPurchased=4;
chancesthatthisvariablemaybeusedwithout
float billAmount=0.0f;
initializingbasedonthelogicwritten
if(itemId>=5001 && itemId<=5005){
Notetheuseofnestedifstatementsanduse
if(quantityPurchased>0 && quantityPurchased<5){
oflogicaloperators
if(itemPrice>=5){
billAmount=itemPrice*quantityPurchased;
Notetheuseofarithematicoperators
int discount;
switch(itemId){
case 5001: discount=10;
Notetheuseofswitchstatement
break;
case 5002:
discount=15;
break;
case 5003: discount=12;
Notetheuseofdefaultinswitchstatement
break;
default:
discount=0;
}
billAmount=billAmount billAmount*discount/100;
System.out.println("Bill Id:"+billId);
System.out.println("Customer
Id:"+customerId);
System.out.println("Item Id:"+itemId);
System.out.println("Item
Price:Rs."+itemPrice);
System.out.println("Quantity
Purchased:"+quantityPurchased);
System.out.println("Discount%:"+discount);
System.out.println("Bill
Amount:Rs."+billAmount);
}
else{
System.out.println("Invalid item price.
Item price must be minimum Rs. 5");
}
Notetheuseofelsestatementsinnestedifconstruct
}
toprovideclearerrormessagestotheenduser
else{

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 21 of 170

Infosys Limited

Assignments for OO programming using Java part1

System.out.println("Invalid quanity. Quantity


must be greater than 0 and less than 5");
}
}
else{
System.out.println("Invalid item id. Item Id must be
between 5001 and 5005");
}
}
}

Estimated time: 10 minutes


Summary of this assignment: In this assignment, you have understood the
implementation of operators and control structures using a real world problem

Assignment 13: Selection Control Structures Hands on


practice
Objective: Given a real world problem be able to understand the need for control
structures and operators to implement the logic and solve the problem
Problem Description: The finance department of a company wants to calculate the
monthly net pay of one of its employee by finding the income tax to be paid (in Indian
Rupees) and the net salary after the income tax deduction. The employee should pay
income tax if his monthly gross salary is more than Rs. 10,000 (Indian Rupees) and the
percentage of income tax should be considered as 20% of the gross salary. Display the
employee id, basic salary, allowances, gross pay, income tax and net pay.
Note:
Employee Id must be considered as 1001,
Basic salary of the employee must be considered as Rs.15000.00 and
Allowances must be considered as Rs.6000.00
Write a Pseudo code and Java program in Eclipse to solve the above real world
problem.
Estimated time: 15 minutes
Summary of this assignment: In this assignment, you have understood the
implementation of operators and control structures using a real world problem

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 22 of 170

Infosys Limited

Assignments for OO programming using Java part1

Assignment 14: Iterational Control Structures - Demo


Objective: Given a real world problem, implement the logic and solve the problem
using appropriate constructs (sequential, selection, iteration) using an object oriented
programming language (Java)
Problem Description:
Dry run the below code snippets and predict the output. You may want to confirm the
output by executing the code using Eclipse IDE.
Code-1:
class Demo{
public static void main(String args[]) {
System.out.println("To find the sum of first 10
integers:");
int sum=0;
for (int counter=1; counter<= 10; counter++) {
sum=sum+counter;
}
System.out.println("Sum:"+sum);
}
}

Code-2:
class Demo{
public static void main(String args[]) {
int count=1;
while (count <= 3) {
System.out.println(count);
count++;
}
}
}

Code-3:
class Demo{
public static void main(String args[]) {

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 23 of 170

Infosys Limited

Assignments for OO programming using Java part1

int number=1, sum = 0;


do {
sum = sum + number;
number=number+1;
} while (number < 5);
System.out.println(sum);
}
}

Code-4:
class Demo{
public static void main(String args[]){
int result=0;
for(int index=10;index<=40;index++){
if(index%5==0){
result=result+index;
}
}
System.out.println(result);
}
}

Code-5:
class Demo{
public static void main(String args[]){
double amount=100.0,interest=0.0;
int months=1;
while(months<6){
interest=amount*0.2;
amount=amount+interest;
months++;
System.out.println(amount);
}
}
}

Estimated time: 25 minutes


Summary of this assignment: In this assignment, you have understood the
implementation of iteration control structures.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 24 of 170

Infosys Limited

Assignments for OO programming using Java part1

Assignment 15: break statement - Demo


Objective: Given a real world problem, implement the logic and solve the problem
using appropriate constructs (sequential, selection, iteration) using an object oriented
programming language (Java)
Problem Description:
Dry run the below code snippet and predict the output. You may want to confirm the
output by executing the code using Eclipse IDE.
Code:
class Demo{
public static void main(String args[]){
int count, sum=0;
for (count = 1; count <= 10; count++){
sum=sum+count;
Notetheuseofbreakstatement
if(sum>6){
break;
}
On encounteringthebreak
}
statement,controlwill
moveoutoftheloopas
System.out.println("Sum="+sum);
shownhere
}
}

Estimated time: 10 minutes


Summary of this assignment: In this assignment, you have understood the
implementation of break statement.

Assignment 16: continue statement - Demo


Objective: Given a real world problem, implement the logic and solve the problem
using appropriate constructs (sequential, selection, iteration) using an object oriented
programming language (Java)
Problem Description:
Dry run the below code snippet and predict the output. You may want to confirm the
output by executing the code using Eclipse IDE.
Code:
Notetheuseofcontinuestatement
ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 25 of 170

Infosys Limited

Assignments for OO programming using Java part1

class Demo{
public static void main(String args[]){
int count=0;
for(count = 0 ; count < 10; count++) {
if (4 == count) {
continue;
}
System.out.println(count);
}
}
}

On encounteringthecontinue
statement,controlwillmove
totheincrementportionof
theforloop

Estimated time: 10 minutes


Summary of this assignment: In this assignment, you have understood the
implementation of continue statement.

Assignment 17: Iteration Control Structure - Debugging


Objective: Given a real world problem, implement the logic and solve the problem
using appropriate constructs (sequential, selection, iteration) using an object oriented
programming language (Java)
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.
class ForLoop{
public static void main(String args[]){
for(int i=50;i<80;i++){
if(i%2==0){
System.out.println(i);
}
else{
break;
}
}
}

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 26 of 170

Infosys Limited

Assignments for OO programming using Java part1

Step 2: Correct the logical error in the code, save, compile and execute the code
Step 3: Implement the same logic using while loop
Estimated time: 10 minutes
Summary of this assignment: In this assignment, you have learnt the implementation
of iteration control structure and break statement.

Assignment 18: Control Structures Hands on practice


Objective: Given a real world problem be able to understand the need for control
structures and operators to implement the logic and solve the problem
Problem Description: Extend the program written for Programming Fundamentals Part
I Assignment 13 to find the income tax to be paid (In Indian Rupees) and the total salary
after the income tax deduction as per the details given in below table.
Gross Salary (In Indian Rupees)
Below 5,000
5,001 to 10,000
10,001 to 20,000
More than 20,000

Income Tax percentage


Nil
10 %
20%
30%

Display the employee id, basic salary, allowances, gross pay, income tax and net pay.
Note:
Employee Id must be considered as 1001,
Basic salary of the employee must be considered as Rs.15000.00 and
Allowances must be considered as Rs.6000.00
Write a Pseudo code and Java program in Eclipse to solve the above real world
problem.
Estimated time: 20 minutes
Summary of this assignment: In this assignment, you have understood the
implementation of operators and control structures using a real world problem

Assignment 19: Type Conversion and Casting Demo

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 27 of 170

Infosys Limited

Assignments for OO programming using Java part1

Objective: Given a real world problem, be able to understand the need for
programming fundamentals such as type conversion and casting.
Problem Description: Let us revisit the program written for Programming
Fundamentals Part I Assignment 12.
Note: The formula written for calculation of discounted bill amount has been modified.
class Retail {
public static void main(String[]args){
int billId=1001;
int customerId=101;
int itemId=5002;
float itemPrice=55.0f;
int quantityPurchased=4;
float billAmount=0.0f;
if(itemId>=5001 && itemId<=5005){
if(quantityPurchased>0 && quantityPurchased<5){
if(itemPrice>=5){
billAmount=itemPrice*quantityPurchased;
int discount;
switch(itemId){
case 5001: discount=10;
break;
case 5002:
discount=15;
break;
case 5003: discount=12;
break;
default:
discount=0;
}
billAmount=billAmount billAmount*(discount/100);
System.out.println("Bill Id:"+billId);
System.out.println("Customer
Id:"+customerId);
System.out.println("Item Id:"+itemId);
System.out.println("Item
Price:Rs."+itemPrice);
System.out.println("Quantity
Purchased:"+quantityPurchased);
System.out.println("Discount%:"+discount);

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 28 of 170

Infosys Limited

Assignments for OO programming using Java part1

System.out.println("Bill
Amount:Rs."+billAmount);
}
else{
System.out.println("Invalid item price.
Item price must be minimum Rs. 5");
}
}
else{
System.out.println("Invalid quanity. Quantity
must be greater than 0 and less than 5");
}
}
else{
System.out.println("Invalid item id. Item Id must be
between 5001 and 5005");
}
}
}

Output:
BillId:1001

Estimated time: 10 minutes


CustomerId:101

ItemId:5002
ItemPrice:Rs.55.0
QuantityPurchased:4
Discount%:15
BillAmount:Rs.220.0

Whydoyouthinkthediscount
wasnotreducedfromthebill
amount?

Theformulaforcomputingthebillamountiswrittenas:
billAmount=billAmountbillAmount*(discount/100);
Here,discount/100willbecomputedfirstsinceitisin()bracketsanddiscountand100arebothinteger
variablesresultinginintegerdivision.Hencetheresultwillalwaysbe0asthefractionalpartwillbetruncated.

Revised Code:
class Retail {

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 29 of 170

Infosys Limited

Assignments for OO programming using Java part1

public static void main(String[]args){


int billId=1001;
int customerId=101;
int itemId=5002;
float itemPrice=55.0f;
int quantityPurchased=4;
float billAmount=0.0f;
if(itemId>=5001 && itemId<=5005){
if(quantityPurchased>0 && quantityPurchased<5){
if(itemPrice>=5){
billAmount=itemPrice*quantityPurchased;
int discount;
switch(itemId){
case 5001: discount=10;
break;
case 5002:
discount=15;
break;
case 5003: discount=12;
break;
default:
discount=0;
Notehowtypecastingisdoneonthe
}
discountvariablebeforedividingby
billAmount=billAmount 100
billAmount*((float)discount/100);
System.out.println("Bill Id:"+billId);
System.out.println("Customer
Id:"+customerId);
System.out.println("Item Id:"+itemId);
System.out.println("Item
Price:Rs."+itemPrice);
System.out.println("Quantity
Purchased:"+quantityPurchased);
System.out.println("Discount%:"+discount);
System.out.println("Bill
Amount:Rs."+billAmount);
}
else{
System.out.println("Invalid item price.
Item price must be minimum Rs. 5");
}
}

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 30 of 170

Infosys Limited

Assignments for OO programming using Java part1

else{
System.out.println("Invalid quanity. Quantity
must be greater than 0 and less than 5");
}
}
else{
System.out.println("Invalid item id. Item Id must be
between 5001 and 5005");
}
}
}

Theformulaforcomputingthebillamountcanalsobewrittenas:

Here,billAmount*discountwillbecomputedfirstand
resultofthatwillbeafloatvaluesincebillAmountis
float.Thiswillbefollowedbydivisionby100which
willalsoresultinafloatvaluesincenumeratorisa
floatvalue.

billAmount=billAmountbillAmount*discount/100;or
billAmount=billAmountbillAmount*(discount/100.0f);

Here,(discount/100.0f)willbecomputedfirstand
resultofthatwillbeafloatvaluesincedenominator
isafloatvalue.

Estimated Time: 20 minutes


Summary of this assignment: In this assignment, you have understood the need for
type casting and conversion in solving real world problems

Assignment 20: Type Conversion and Casting Hands on


practice
Objective: Given a real world problem, be able to understand the need for
programming fundamentals such as type conversion and casting.
Problem Description: An employer wants to find the average customer feedback (In a
scale of 10) received by an employee. The employee received feedbacks from three
customers.
The below program written for the above real world problem is providing incorrect result.
class Employee {
public static void main(String[] args){

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 31 of 170

Infosys Limited

Assignments for OO programming using Java part1

int
int
int
int

employeeId=4567;
feedback1=5;
feedback2=6;
feedback3=6;

float avgFeedback=feedback1+feedback2+feedback3/3;
System.out.println("Employee Id:"+employeeId);
System.out.println("Average Feedback:"+avgFeedback);
}
}

Debug the above program so as to produce the below output:


Output:
EmployeeId:4567
AverageFeedback:5.6666665

Estimated Time: 10 minutes


Summary of this assignment: In this assignment, you have learnt the implementation
of type casting and conversion to solve real world problem.

Object Oriented Fundamentals- Assignments

Assignment 21: A system engineers story Observations


Characters in Roys story:
Client: Easy Shop, the international chain which has set up retail outlets in India with its
head office in Delhi
Juan: Client representative in India, a Mexican national. He has shifted to Delhi to
manage the automation operations of Easy Shop. A strict disciplinarian and is particular
about timelines and quality of code

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 32 of 170

Infosys Limited

Assignments for OO programming using Java part1

Tom: The project manager from Infosys, an Indian. He is based out of Mysore and has
5 years of experience managing projects in retail domain. An excellent mentor to the
team and is very particular about teams following standard design and coding practices
Roy: A system engineer from Infosys, an Indian. He has recently moved into Toms
project
Amit Sharma: Co-ordinator of the Infosys Delhi team. He is a business analyst and has
worked in a number of client-facing projects.
Mary Ann: The system team head of Easy shop in Delhi who is responsible for
automation deployment in Delhi and interfaces with Amit Sharma.
Joy Paul: The Retail Store Manager of the Easy Shop Mega store at Delhi
Jane: The admin manager of the Easy Shop Mega store at Delhi
Victor Gyan: The warehouse manager of Easy shop who manages the stock of items
and interfaces with the suppliers
Andrew Stanley: One of the many clerks at the purchase points. He is very agile and
dynamic.
Alphonso: A frequent/regular customer to the Easy Shop outlet in Delhi. He is an
African national studying Arts in Jawaharlal Nehru University, Delhi and visits the food
section of Easy Shop for his African culinary items. He also orders the items online if he
is unable to visit the shop.
Cameron: A US national who visits Easy Shop outlets during her India trips and shops
for traditional Indian art and traditional items which are expensive
Client team and Developemt teams: Teams are in various Indian cities like Delhi,
Chennai, Mumbai and Mysore
The Story.
It was the first day of his project in Infosys, Mysore for Roy. Roy was overwhelmed at
returning back to Mysore. He had joined as a fresher, completed the foundation
program and worked in Infosys, Pune for 2 years in different projects in Finance
domain. He recently shifted to a project in the Retail domain.
Roy meets Tom, the project manager for the Easy Shop application project during the
project orientation session. The induction is arranged through a video conference.
There are teams joining from Delhi, Chennai and Mumbai along with the bigger team
from Mysore. The representative of the client, Juan provides the expectations of the
project from Delhi. Roy learns that the teams in the Indian cities would interface with the

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 33 of 170

Infosys Limited

Assignments for OO programming using Java part1

client offices and the Mysore team would be the development team fulfilling the
functional specifications of the client. Roy learns that the 100 member team is a mix of
fresh engineers, technical leads and technical associates, both experienced and inexperienced in retail domain. Roy is astounded at the mere size and distribution of the
team.
Juan explains that the vision and philosophy of setting up Easy shop retail outlets in
India is to make popular brands and items available to customers under one roof at
economical prices. Easy Shop is an international retail chain which has set up various
retail outlets in various cities of India. Easy Shop is very popular for their schemes and
the value for money that they bring to their customers.
The automation planned needs to take care of the user registration, customer
registration and purchase operations of the stores in India and interface with other
existing systems like the trading, financial, sales analysis etc. The system would also
cater to online shopping by customers for selected items. The maintenance of items
and the supplier management also need to be done. The system would use a host of

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 34 of 170

Infosys Limited

technologies

Assignments for OO programming using Java part1

as

shown

by

Juan

in

the

diagram

below:

J2EE/ORACLE
Pricing
System
Trading
System

MAINFRAME/COBOL/CICS/DB2

TradingInterface

Travel
System

Salary
System

HR
System

Policies
System

AS400/RPG

C++/UNIX

SAP/COTS

Remittance
Processing

Demand
Forecasting

Middleware(MQSeries)

Departments
&Locations

DWH/ORACLE
Middleware(BizTalk)

Webbased
Users

Business
Intelligence

J2EE/WEBSHPERE

Sales
Analysis

System

ElectronicFund
Transfer
C++/UNIX

VB.NET/SQL
VB.NET/SQL

Middleware
(MQSeries)

Customer
Support
System

Order
Payments

Financial
System

Accounting
System

Finance
Analysis
Ageing
Analysis

Subsystem1

SAS
Funds
Brokers

Order
Processing

Customer
Complaints

Subsystem2

Assets

.NET/SQL/COMMERCESERVER

Subsystem3

Banks
SAPSystem

Roy is startled at the magnanimity of the project and has the following questions on the
challenges of developing this system.
Can you help answer him?
1. There is a high dependency of users (admin, managers, customers, store
managers, suppliers etc) on the retail application. What challenges would the
team face in developing such a system? You may categorize challenges from the
users perspective and the technical team perspective
Answer :

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 35 of 170

Infosys Limited

Assignments for OO programming using Java part1

User perspective: User friendly interfaces, illusion of simplicity, high level of


flexibility, availability of a number of reports
Technical team perspective: Diversified team with different capabilities,
communication between teams, huge systems to be developed in parallel by
people geographically distributed and culturally different backgrounds, test
coverage of the entire system
2. How do we ensure that the challenges are mitigated?
Modularize the system, follow standard and proven design and coding best
practices, follow software engineering practices and processes and follow good
testing at different levels, understand the big picture of the system rather than
just the module/unit level details.

Estimated Time: 20 minutes


Summary of this assignment: In this assignment, you have understood the need for
an engineering approach and object oriented approach

Assignment 22: Object Oriented Concepts - Quiz


Objective: Revisit object oriented concepts using a quiz
Answer the following questions:
1. In the ATM machine, the customer chooses the operations using a touch screen.
The customer need not know the internal working of the ATM machine. Which
OO concept(s) can be used in this scenario?
2. Consider the following statement: Vehicles can be of two types viz. Water
vehicles and Land vehicles . Which OO concept may be used to represent this
scenario?
Estimated time: 10 minutes
Summary of this assignment: In this assignment, you have revisited object oriented
concepts using scenarios

Assignment 23: Introduction to UML


Objective: Given a business scenario, be able to identify the components of a use case
diagram

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 36 of 170

Infosys Limited

Assignments for OO programming using Java part1

Problem Description: Refer to the course registration system case study and answer
the following questions.
Situation: 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 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
Questions:
1. Identify all the actors of the course registration system
2. Identify the activities, i.e use cases performed by the actors of the course
registration system.

Estimated time: 20 minutes


Summary of this assignment: In this assignment, you have learnt how to actors and
activities of a use case diagram using a course registration system scenario

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 37 of 170

Infosys Limited

Assignments for OO programming using Java part1

Assignment 24: Classes & Objects Hands-on


Objective: Given a class diagram for a use case representing a computational problem,
be able to recognize the three compartments of the class diagram and implement it
using an object oriented language (Java) using an IDE
Problem Description: In the retail application, there are many customers who visit the
retail outlet to purchase various items. The manager of the retail outlet now wants to
keep track of all its customers data. Let us assume that customer details include
Customer Id and Telephone Number.
For the class diagram identified in OO Fundamentals, implement the class using Eclipse
IDE and execute it by writing a starter class.
Code: Execute the code using Eclipse IDE with the given inputs and understand the
following:
Access Specifiers
Variables Local and Instance variables
Methods
Starter class
Creation of objects
Reference variables
Compilation and Execution of a java program

Notetheuseofaccessspecifiersintheclass,Customer
Notehowtheclass,Customeriswritten
class Customer{
private int customerId;
private long telephoneNo;

Notetheuseofinstancevariablesormember
variablescustomerIdandtelephoneNoin
theclass,Customer

public void setCustomerId(int id) {


customerId = id;
}
public void setTelephoneNo(long teleNo){
telephoneNo=teleNo;
}
public int getCustomerId(){
return customerId;
}

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Notetheuseofmembermethodsintheclass,
Customer
Notethehowlocalvariablesareusedinthe
membermethodsofclass,Customer
Notethehowmethodheader,method
definition,returnstatementiswrittenin
membermethodofclass,Customer

Page 38 of 170

Infosys Limited

Assignments for OO programming using Java part1

public long getTelephoneNo(){


return telephoneNo;
}

Notehowstarterclass,Retailiswrittenand
understandtheneedofstarterclass

}
Notehowthemainmethodiswrittenin
Retail{
starterclass,Retail
public static void main(String args[]){
Customer custObj = new Customer();
custObj.setCustomerId(1001);
NotehowobjectofCustomerclassiscreated
custObj.setTelephoneNo(9201861311L); usingreferencevariableandnewoperator
System.out.println("Customer Id:"+
custObj.getCustomerId());
NotehowmembermethodsofCustomer
System.out.println("Telephone No:"+
classareinvokedusingreferencevariable
custObj.getTelephoneNo());
anddotoperator
}
}
class

NotetheuseofSystem.out.println()
statementfordisplayofconsoleoutput

Estimated time: 15 minutes


Summary of this assignment: In this assignment, you have understood object
oriented fundamentals - Access Specifiers, Variables Local and Instance variables.

Assignment 25: Coding Standards


Objective: Given a set of source code and an identified set of best practices, be able to
implement the techniques during coding
Problem Description: Coding standards are very important for maintenance of code
and for understanding of the code. Identify the sections of the given program where the
coding standards are not followed and correct them.
class item{
private int itemnumber;
private float price;
public void getitem(int num,float itemprice){
itemno=num;
price=itemprice;
}
public void ITEMDisplay(){
System.out.println("Item No:"+itemnumber);

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 39 of 170

Infosys Limited

Assignments for OO programming using Java part1

System.out.println("Item Price:"+price);
}
}

Estimated time: 10 minutes


Summary of this assignment: In this assignment, you have learnt
Java coding standards

Assignment 26: Reference Variables and Objects in Memory


Objective: Create classes and objects, recognize the dynamic memory allocation
segments and interpret the benefits of abstraction and encapsulation
Problem Description: Consider the following code snippets and answer the following
1. Code Snippet
Customer custObj = new Customer();

Where will the memory be allocated for the reference variable and object?
Note: Assume that reference variable declaration is done inside the main()
method

2. Code Snippet:2
Customer
Customer

custObj1 = new Customer();


custObj2 = custObj1;

How many Reference variables and objects are created?


Note: Assume that reference variable declaration is done inside the main()
method

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 40 of 170

Infosys Limited

Assignments for OO programming using Java part1

3. Code Snippet:3
Consider the following code, assume that Customer class is already written:
class

Retail{
public static void main(String args[]){
Customer custObj = new Customer();
custObj.setCustomerId(1001);
custObj.setTelephoneNo(9201861311L);
System.out.println("Customer Id:"+ custObj.getCustomerId());
System.out.println("Telephone No:"+
custObj.getTelephoneNo());
custObj=null;
..
..
}
}

What will happen to the object of Customer class already created?


The reference variable, custObj is no longer pointing to the object of Customer
class. But the object already created is still in Heap memory

Assignment 27: Methods Pass by value & Reference- A


Simple Demo
Objective: Given a class diagram for a use case representing a computational problem,
implement methods and solve it using appropriate parameter passing techniques (pass
by value and pass by reference)

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 41 of 170

Infosys Limited

Assignments for OO programming using Java part1

Problem Description: Consider the following class diagram for a class called Distance
which contains the distance in miles between two locations
Class diagram:
Distance
-distance
+setDistance(int)
+getDistance()

: int
: void
: int

Code:
Execute the code using Eclipse IDE. The first object of Distance class provides the
distance between Phoenix, Arizona and Salt Lake City, Utah in USA. The second object
provides the distance between Phoenix, Arizona and Tampa, Florida in the US. We
want to compare the distances and check which one is far off from Phoenix, Arizona.
Provided below are codes written to solve the above problem using pass by value and
pass by reference techniques.
Method 1: Pass by value
class Distance{
dististheformalargument
private int distance;
public void setDistance(int dist) {
distance = dist;
506istheactualargumentwhich
}
ispassedandassignedtothe
public int getDistance(){
formalargument,dist,whenthe
return distance;
methodsetDistance()isinvoked
}
forphoenixToSLCobject
}
class Demo{
public static void main(String args[]){
Distance phoenixToSLC = new Distance();
Distance phoenixToTampa = new Distance();
phoenixToSLC.setDistance(506);
Thevalues506and1790
phoenixToTampa. setDistance (1790);
arepassedbyvalue
compare(phoenixToSLC.getDistance(),phoenixToTampa.getDistance());
}
Moreabout
staticlater

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 42 of 170

Infosys Limited

Assignments for OO programming using Java part1

public static void compare(int d1,int d2){


if(d1>d2){
System.out.println(SLC is far from Phoenix compared to
Tampa, Florida);
}
else if (d1<d2){
System.out.println(Tampa, Florida is far from Phoenix
compared to SLC);
}
else {
System.out.println(Both locations are equidistant from
Phoenix);
}
}
}

Illustration:

Method 2: Pass by reference


class Distance{
private int distance;
public void setDistance(int dist) {
distance = dist;
}
public int getDistance(){

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Twoobjectsarepassedby
reference

Version No: 1.2

Page 43 of 170

Infosys Limited

Assignments for OO programming using Java part1

return distance;
}
}
class

Demo{
public static void main(String args[]){
Distance phoenixToSLC = new Distance();
Distance phoenixToTampa = new Distance();
phoenixToSLC.setDistance(506);
phoenixToTampa. setDistance (1790);
compare(phoenixToSLC,phoenixToTampa);
}
public static void compare(Distance obj1,Distance obj2){
if(obj1.getDistance()>obj2.getDistance()){
System.out.println("SLC is far from Phoenix compared to
Tampa, Florida");
}
else if (obj1.getDistance()<obj2.getDistance()){
System.out.println("Tampa, Florida is far from Phoenix
compared to SLC");
}
else {
System.out.println("Both locations are equidistant from
Phoenix");
}
}
}

Ilustration:

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 44 of 170

Infosys Limited

Assignments for OO programming using Java part1

Estimated Time: 30 minutes


Summary of this assignment: In this assignment, you have learnt how to pass a value
to a method using a retail application scenario

Assignment 28: Methods Pass by reference - Hands on


practice
Objective: Given a class diagram for an use case representing a computational
problem, Implement methods and solve it using appropriate parameter passing
techniques (pass by value and pass by reference)
Problem Description: At an airport, a traveler is allowed entry into the flight only if he
clears the following checks
i.
ii.
iii.

Baggage Check
Immigration Check
Security Check
Traveler
-travelerId:int
-baggageAmount:int
-expiryYear:int
-nocStatus:boolean
+setTravelerId(int):void
+setBaggageAmount(int):void
+setExpiryYear(int): void
+setnocStatus(boolean):void
+getTravelerId():int
+getBaggageAmount():int
+getExpiryYear():int
+getNocStatus():boolean

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 45 of 170

Infosys Limited

Assignments for OO programming using Java part1

Checks

Demo
+main(String
static

args[]):void

+checkBaggage(Traveler):boolean
+checkImmigration(Traveler):boolean
+checkSecurity(Traveler):boolean

Create the classes as per the class diagram. Notice here that an object of Traveler is
passed to the check methods. The logic for the check methods are given below:
Implementation details
checkBaggage(Traveler):boolean

Check if baggageAmount is greater than or equal to 0 and less than or equal to 40.

If baggageAmount is VALID
o return TRUE
else
o return FALSE

checkImmigration(Traveler):boolean

Check if expiryYear is greater than or equal to 2001 and less than or equal to 2025.

If expiryYear is VALID
o return TRUE
else
o return FALSE

checkSecurity(Traveler):boolean

If nocStatus is TRUE
o return TRUE
else
o return FALSE

main(String args[]):void static


In main method, create the object of class Traveler and initialize the values to the
following table:

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 46 of 170

Infosys Limited

Assignments for OO programming using Java part1

Variable
travelerId
baggageAmount
expiryDate
nocStatus

Value
1001
35
2019
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.
If all values are true,
display Allow Traveller to fly!
else,
display Detain Traveller for Re-checking!
Estimated time: 25 minutes
Summary of this assignment: In this assignment, you have learnt
How to pass objects to a method using the concept pass by reference

Assignment 29a: Recursion Demo


Objective: Given a problem, be able to solve the problem by representing the logic
using pseudo code representation.
Problem Description: Consider the problem of finding factorial of a number. The same
can be implemented in Java using Recursion.
Consider the following pseudo-code:
Note the name of the method factorial and the argumnt passed
number whose factorial is to be calculated

FACTORIAL (number)
1. if (number = 0) then
2.

return(1)
Note the termination condition

3. else
4.

return(number * factorial (number-1))


Note that the factorial () is making a call to itself with one less
the number

5. end-if

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 47 of 170

Infosys Limited

Assignments for OO programming using Java part1

The same can be represented in Java:


//Factorial Class calling a recursive method
public class Factorial {
public int factorial (int number) {
if (number == 0) {
return 1;
} else {
return number * factorial(number - 1);
}
}
}
public static void main(String[] args) {
//Variable declaration
int number = 4;
Factorial fact = new Factorial ();
//Calling factorial function
int result = fact.factorial (number);
//Print the factorial number
System.out.println("The factorial of " +
result);

number + " is " +

}
}

Estimated time: 10 minutes


Summary of this assignment: In this assignment, you have learnt how to implement
recursion.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 48 of 170

Infosys Limited

Assignments for OO programming using Java part1

Assignment 29b: Recursion


Objective: Given a problem, be able to solve the problem by representing the logic
using pseudo code representation.
Problem Description: Consider the problem of generating Fibonocci series using
Recursion. The same can be implemented in Java using Recursion.
Consider the following pseudo-code:
FIBO (number)
1. if (number = 0) then
2. return (0)
3. else if (number = 1) then
4. return (1)
5. else
6. return FIBO(number-1)+FIBO(number-2)
7. endif
Write a program in Java to implement the same using Recursion and execute it in
Eclipse.
Note: The same problem can be implemented using Dynamic Programming to reduce
the time complexity. (Discussed later in Algorithm Design Techniques).
Estimated time: 20 minutes
Summary of this assignment: In this assignment, you have learnt how to implement
recursion.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 49 of 170

Infosys Limited

Assignments for OO programming using Java part1

Assignment 30: this reference - Demo


Objective: Given a class diagram for an use case representing a computational
problem, use the this reference to prevent instance variable hiding and test using a set
of values in an IDE
Problem Description: Let us revisit the class diagram drawn and implemented for
Customer class as part of Object Oriented Fundamentals.
Class diagram:
Customer
-customerId
-telephoneNo

: int
: long

+setCustomerId(int)
+getCustomerId()
+setTelephoneNo(long)
+getTelephoneNo()

: void
: int
: void
: long

Code:
Note: The code given below is a modified version of the code discussed as part of
Object Oriented Programming Fundamentals Part II Assignment 4.The logic written in
setCustomerId(int) method of Customer class has been modified.
Execute the code using Eclipse IDE with the given inputs in the starter class, Retail and
observe the results.
class Customer{
private int customerId;
private long telephoneNo;
public void setCustomerId(int customerId) {
customerId = customerId;
}
public void setTelephoneNo(long teleNo){
telephoneNo=teleNo;
}
public int getCustomerId(){
return customerId;
}

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 50 of 170

Infosys Limited

Assignments for OO programming using Java part1

public long getTelephoneNo(){


return telephoneNo;
}
}
class

Retail{
public static void main(String args[]){
Customer custObj = new Customer();
custObj.setCustomerId(1001);
custObj.setTelephoneNo(9201861311L);
System.out.println("Customer Id:"+
custObj.getCustomerId());
System.out.println("Telephone No:"+
custObj.getTelephoneNo());
}
}

Output:
CustomerId:0
TelephoneNo: 9201861311

Whydoyouthinkcustomerid
is0andnot1001?

Revised Code:

class Customer{
private int customerId;
private long telephoneNo;

Notetheuseofthisreferenceto
preventinstancevariablehiding

public void setCustomerId(int customerId) {


this.customerId = customerId;
}
public void setTelephoneNo(long teleNo){
telephoneNo=teleNo;
}
public int getCustomerId(){

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 51 of 170

Infosys Limited

Assignments for OO programming using Java part1

return customerId;
}
public long getTelephoneNo(){
return telephoneNo;
}
}
class

Retail{
public static void main(String args[]){
Customer custObj = new Customer();
custObj.setCustomerId(1001);
custObj.setTelephoneNo(9201861311L);
System.out.println("Customer Id:"+
custObj.getCustomerId());
System.out.println("Telephone No:"+
custObj.getTelephoneNo());
}
}

Output:
CustomerId:1001
TelephoneNo: 9201861311

Estimated time: 10 minutes


Summary of this assignment: In this assignment, you have learnt the usage of this
reference for resolving the ambiguity between instance variables and local variables
(instance variable hiding) using a retail application scenario

Data Structures: Assignment 31


Objective: Given a problem scenario, be able to identify the ways in which the data is
stored in the computer memory.
Problem description: Open a word editor and type the following.
(Save every time a new character is entered)
(A + B + (C *D))
Now perform Undo operation (Ctrl + Z) 5 times

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 52 of 170

Infosys Limited

Assignments for OO programming using Java part1

Answer the following:


i.
ii.
iii.
iv.

What will be the resultant expression when the first Undo is carried out?
What will be the resultant expression when the 5th Undo is carried out?
In what sequence the inputs are stored?
Will the way of storing the operations make any impact on the working of UNDO
operation?

Estimated Time: 10 minutes


Summary of this assignment: In this assignment you have learnt that there are
different ways in which we can store data in the computer memory for processing.

Data Structures: Assignment 32


Objective: Given a problem scenario, be able to identify the ways in which the data is
stored in the computer memory.
Problem description: John, Mathews and Suzanne are team members working on a
same project. CCD has configured a printer which all the members of the team can
share. For a team meeting the project manager has asked all the three members to
prepare a report individually and carry a print out of the same.
Mathews is able to finish the report first followed by Suzanne and then John and have
given the command to print.
Answer the following:
i.

In the above scenario, what is the order in which the print requests are stored in
the printers memory?

ii.

Whose document the printer retrieves first for printing?

Estimated Time: 10 minutes


Summary of this assignment: In this assignment you have learnt that there are
different ways in which we can store data in the computer memory for processing.

Demo : Data Structures - Array: Assignment 33


Objective: Given a data structure, be able to identify the operations to be performed
and represent the logic using pseudo-code.
Problem description: Consider the following array. Insert new element 7 at index 1

7
ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 53 of 170

Infosys Limited

Assignments for OO programming using Java part1

Assumptions: Array index starts from 0

Algorithm
Input
Output

:
:
:

INSERT_ELEMENT_ARRAY
Element to be inserted
Array with inserted element

Step 1: Shift elements 10 and 6 to index 2 and 3 respectively, to make space at index 1
Step 2: Copy the new element
Pseudo-code is represented below:
INSERT_ELEMENT_ARRAY
1.
2.
3.
4.
5.
6.

input index = 2
// consider the last element of the array
while (index >= 1 ) do
//Position where the new element is to be inserted
array[ index + 1 ] = array [ index ]
index = index 1
end-while
array[ index + 1] = 7

The above pseudo code can be represented in Java as follows:


public class ArrayInsertion {

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 54 of 170

Infosys Limited

Assignments for OO programming using Java part1

public static void main(String[] args) {


int array[] = {3,10,6,0,0};
int index = 2;
while (index >= 1 ){
array[ index + 1 ]
=
array [ index ];
index--;
}
array[ index + 1] = 7;
// To display the elements after insertion
System.out.println("Elements of an Array are ");
for (int i = 0; i<4; i++)
System.out.println(array[i]);
}

Estimated Time: 10 minutes


Summary of this assignment: In this assignment you have learnt to write the pseudocode for inserting an element into an array and its implemention in Java.

Data Structures- Array: Assignment 34


Objective: Given a data structure, be able to identify the operations to be performed
and represent the logic using pseudo-code
Problem description: Modify the pseudo-code of assignment 33 to insert an element
into an array at index 2. Implement and execute the same in Java.
Assumptions: Index starts from 0
Estimated time: 10 minutes
Summary of this assignment: In this assignment you have learnt how to write the
pseudo-code for inserting an element of an array

Data Structures- Array: Assignment 35


Objective: Given a data structure, be able to identify the operations to be performed
and represent the logic using pseudo-code

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 55 of 170

Infosys Limited

Assignments for OO programming using Java part1

Problem description: Represent the logic required for deleting element 6 from the
array using pseudo-code and implement and execute it in Java.

Assumptions: Index starts from 0


Estimated time: 10 minutes
Summary of this assignment: In this assignment you have learnt how to write the
pseudo-code for deleting an element from an array and implement the same in Java.

Data Structures- Array: Assignment 36


Objective: Given a problem scenario, be able to identify the data structure, operations
to be performed and represent the logic using pseudo-code.
Problem description: Smith handled a session on computational problem solving for a
group of 20 professionals as part of learning and development initiative. An assessment
was conducted on the last day the session. Smith is curious to know maximum marks
and also the minimum marks scored in the assessment.
Represent the logic required to identify the maximum and minimum score using a
pseudo-code and write Java code to implement the logic.
Estimated time: 10 minutes
Summary of this assignment: In this assignment you have learnt to identify required
data structure for a problem and write the pseudo-code and Java code for the given
requirement.
Note:
Used when the number of elements is known
Not useful if insertion and deletion operations are frequent
Allows random and sequential access

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 56 of 170

Infosys Limited

Assignments for OO programming using Java part1

Arrays Assignment 37
Objective: Given a real world problem, be able to understand the need for data
structures such as arrays.
Problem Description: An employer wants to identify the number of confirmed
employees in each job band.
Write a Pseudo code and java program in Eclipse to implement the above real world
problem and display each job band followed by the number of confirmed employees.
The employee details can be considered as mentioned below:
Declare an array to store the employee ids and initialize the array with the employee ids
71005, 71006, 71007, 71008, 71009, 71010.
Declare an array to store the job band of employees and initialize the array with the job
bands D, B, C, A,B,C.
Declare another array to store the confirmation status of employees and initialize them
with the following: Y, N, Y,Y,Y,N
There is a one to one correspondence between these arrays. i.e, employee 71005 has
job band D and the confirmation status is Y. Employee 71006 has job band B and
the confirmation status is N and so on.
Estimated time: 20 minutes
Summary of this assignment: In this assignment, you have learnt the implementation
of data structures such as arrays using a real world problem

Data Structures- Linked List: Assignment 38


Objective: Given a data structure, be able to identify the operations to be performed
and represent the logic using pseudo-code.
Problem description: Consider the following linked list. Add a new node with data 35
at the beginning of the linked list.

H
Algorithm

45
:

ETA/CORP/CRS/ FP14-GEN-003

30

10

INSERT_ELEMENT_LINKED_LIST

CONFIDENTIAL

Version No: 1.2

Page 57 of 170

Infosys Limited

Input
Output

Assignments for OO programming using Java part1

:
:

Node to be inserted
Linked list with inserted node

Step 1: Create a new node with the value 35 in its data part
Step 2: Update the link value of new node with the head (address of node having
element 45).
Step 3: Update the head with the address of new node.
Pseudo-code is represented below:
Assumptions:
Dot (.) operator is used to access the parts of a node in linked list.
n.data refers to the data part of the node
n.link refers to the address part of the node

Pseudo code 1

Pseudo code 2

INSERT_NEW_NODE_AT_BEGIN
INSERT_NEW_NODE_AT_BEGIN
1.
2.

Create a new node n


n.data = data /* 35 for this case */

3.
4.
5.
6.
7.
8.

if (head = NULL) then


n.link= NULL
else
n.link = head
end-if
head = n

1. Create a new node n


2. n.data = data /* 35 for this
case */

3. n.link = head
4. head = n

Estimated time: 15 minutes


Summary of this assignment: In this assignment you have learnt to write the
algorithm and pseudo-code for inserting a node into a linked list.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 58 of 170

Infosys Limited

Assignments for OO programming using Java part1

Note:

Used when the requirement is dynamic


Useful If insertion and deletion is frequent
Allows only sequential access

Data Structures - Stack: Assignment 39


Objective: Given a problem scenario, be able to identify the way in which the data is
stored in the computer memory
Problem description: Access your online banking application.
(For Example, the ICICI application at the following link)
http://www.icicibank.com/safe-online-banking/safe-online-banking.html
Once you login to your account select Mini statement. A statement of the last five/Ten
transactions performed will be displayed on your screen
1. What is the order in which the transactions are displayed?
2. How are the previous transactions stored in the memory?
Estimated Time: 5 minutes
Summary of this assignment: In this assignment you have learnt that there are
different ways in which we can store data in the computer memory for processing.

Data Structures- Stack: Assignment 40 - Demo


Objective: Given a data structure, be able to identify the operations to be performed
and represent the logic using pseudo-code.
Problem Description: In stack, the elements are removed in reverse order of their
insertion. So, stack is called Last-In-First-Out (LIFO) List. Stack can be implemented
using either an array or a linked list.
Assumptions: Array of size n is used to implement stack. Array index starts from 0.
Stack is referred using S
Algorithm: ISEMPTY
Input: A stack
Output: True or false (check for stack is empty or not)
1. Check the top index, if Top index = -1 return true.
2. Otherwise return false.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 59 of 170

Infosys Limited

Assignments for OO programming using Java part1

Pseudo-code is represented below:


IS_EMPTY(S)
1. if (S.Top = -1) then
2. return True
3. else
4. return False
5. end-if
Algorithm: ISFULL
Input: A stack
Output: True or false (check for stack is full or not)
1. Check the top index, if Top index = n-1 return true.
2. Otherwise return false.
Pseudo-code is represented below:
IS_FULL(S)
1. if (S.Top = n-1) then
2.
return True
3. else
4.
return False
5. end-if

Algorithm: PUSH
Input: A stack and an element to be inserted
Output: Stack after insertion
1. Check for overflow condition, if ISFULL returns true then,
1.1. Display stack is full and exit.
2. Otherwise
2.1. Increment the Top index by 1
2.2. Place the value in the array at index Top and exit.
Pseudo-code is represented below:
STACK_PUSH (S, new element)

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 60 of 170

Infosys Limited

Assignments for OO programming using Java part1

1. if (ISFULL()) then
2.
display stack is full
3.
return Error Code
4. else
5.
S.Top = S.Top + 1
6.
S.array[Top] = new element
7.
return S
8. end-if

Algorithm: POP
Input: A stack
Output: Deleted element
1. Check for underflow condition, if ISEMPTY returns true then,
1.1. Display Stack is empty and exit.
2. Otherwise
2.1. Place the value at Top index in a variable Item
2.2. Decrement the Top index by 1 and return Item.
Pseudo-code is represented below:
STACK_POP
1. if (ISEMPTY()) then
2.
display stack is empty
3.
return Error Code
4. else
5.
item = S.array[Top]
6.
S.Top = S.Top-1
7.
return item
8. end-if

The above pseudocode can be implemented and executed in Java:


public class Stack {
private final int size = 3;
int arr[] = new int[size];
int top = -1;

Finalvariableisaconstantvariableinjava

public void push(int pushedElement) {


if (top < size - 1) {
top++;

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 61 of 170

Infosys Limited

Assignments for OO programming using Java part1

arr[top] = pushedElement;
System.out.println("Element " + pushedElement
+ " is pushed to Stack !");
// Print the Elements of the stack
CallthePrintElementsmethodto
printElements();
displayalltheelementsinstack
} else {
System.out.println("Stack Overflow !");
}
}
public void pop() {
int item;
System.out.println("pop operation");
if (top >= 0) {
item = arr[top];
top--;
System.out.println(" Element " + item + " is popped ");
} else {
System.out.println("Stack Underflow !");
}
}
public void printElements() {
if (top >= 0) {
System.out.println("Elements in stack :");
for (int i = top; i >= 0; i--){
System.out.println(arr[i]);
}
}
}
public static void main(String[] args) {
Stack stack = new Stack();
stack.push(12);
stack.push(24);
stack.push(70);
stack.push(28);
stack.pop();
stack.pop();

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 62 of 170

Infosys Limited

Assignments for OO programming using Java part1

stack.push(15);
stack.pop();
stack.pop();
}
}

Estimated time: 15 minutes


Summary of this assignment: In this assignment, you have learnt thow to implement
stack using Arrays.

Data Structures- Stack: Assignment 41


Objective: Given a data structure, be able to identify the operations to be performed
and represent the logic using pseudo code.
Problem description: Consider a stack containing the elements 12, 30, 45, 15. The top
element in the stack is 15. Represent the logic required for push an element 35 to stack.
Hint: Refer the pseudo code given in the assignment 40 related to stack
Assumptions: Array of size 10 is used to implement stack. Array index starts from 0.
Estimated Time: 10 minutes
Summary of this assignment: In this assignment you have learnt how to write the
pseudo-code for pushing an element on stack.

Data Structures- Queue: Assignment 42


Objective: Given a problem scenario, be able to identify the way in which the data is
stored in the computer memory
Problem description: You are at a food court and there are several counters through
which the tokens can be purchased for the food.
What is the order in which tokens are issued at counters?
If a new person arrives at the food court, where does he join the queue?
Estimated Time: 5 minutes
Summary of this assignment: In this assignment you have learnt that elements are
removed from the queue in the same order, in which they were inserted into it (FIFO).

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 63 of 170

Infosys Limited

Assignments for OO programming using Java part1

Data Structures- Queue: Assignment 43


Objective: Given a data structure, be able to identify the operations to be performed
and represent the logic.
Background: In queue, elements are removed in the same order, in which they were
inserted. So, queue is called First-In-First-Out (FIFO) List. Queue can be implemented
using either an array or linked list.
Assumptions: Array of size n is used to implement queue. Array index starts from 1.
Queue is referred using Q. Q.front refers to front of the queue and Q.rear refers to end
of the queue.

Algorithm: ENQUEUE
Input: A queue and an element to be inserted
Output: Queue after insertion
1. Check whether queue is full or not, if rear index = n+1 then,
1.1. Display Queue is full and exit.
2. Otherwise
2.1. Place the value at rear index
2.2. Increment the rear index by 1 and exit.
Pseudo-code is represented below:
ENQUEUE(Q, new element)
1. if (Q.rear = n+1) then
2.
display Queue is full
3.
return Error Code
4. else
5.
Q.queue[rear] = new element
6.
Q.rear = Q.rear+1
7.
return Q
ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 64 of 170

Infosys Limited

Assignments for OO programming using Java part1

8. end-if

Algorithm: DEQUEUE
Input: A queue
Output: Removed element
1. Check whether queue is empty or not, if rear index = front index then,
1.1. Display Queue is empty and exit.
2. Otherwise
2.1. Place the front index value in a variable Item
2.2. Increment the front index by 1 and return Item.
Pseudo-code is represented below:
DEQUEUE (Q)
1. if (Q.front = Q.rear) then
2.
display Queue is empty
3.
return Error Code
4. else
5.
item = Q.queue[front]
6.
Q.front = Q.front+1
7.
return item
8. end-if
Write a Java code for the above pseudo code using Arrays and execute it in Eclipse.

Estimated Time: 20 minutes


Summary of this assignment: In this assignment you have learnt about array
implementation of stack data structure

Advanced (Non-linear) Data Structures - Trees: Assignment 44


Objective: Given a problem scenario, be able to identify the way in which the data is
stored in the computer memory.
Problem description: A travel agent plans trips for tourists from Chicago to Miami. He
gives them three ways to get from town to town: airplane, bus, train. Once the tourists

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 65 of 170

Infosys Limited

Assignments for OO programming using Java part1

arrive, there are two ways to get to the hotel: hotel van or taxi. The cost of each type of
transportation is given in the table below.
. Transportation Type
Airplane
Bus
Train
Hotel Van
Taxi

Cost
$350
$150
$225
$60
$40

Draw a tree diagram to illustrate the possible choices for the tourists. Determine the
cost for each outcome
Estimated Time: 20 minutes
Summary of this assignment: In this assignment you have learnt that there are
different ways in which we can store data in the computer memory for processing.

Advanced Data Structures - Binary Search Tree: Assignment 45


Objective: Given a data structure, be able to identify the operations to be performed
and represent the logic
Problem description: Search for a node with the value 18 in the below tree. Record
the steps followed in searching the same.

Step 1: Start at the Root node, 18 is


greater than 10, Search in Right Sub
Tree
Step 2: 18 is greater than 15, search
in 15s Right Sub Tree
Step 3: 18 is less than 20, search in
20s Left Sub tree
Step 4: 18 matches with the node
value return success.

Observing the steps followed for searching a node, we can represent the algorithm
using a recursive function. The pseudo code representation is given below:

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 66 of 170

Infosys Limited

Assignments for OO programming using Java part1

Assumptions: Each node in the binary search tree has 2 link fields (left and right) and
a value field. The recursion starts from refering to the root node by n. n.value refers to
the node value and key refers to the node to be searched in the binary search tree.
The following is the pseudocode for binary tree searchand insertion of a node.

SEARCH_BINARY_TREE (n, key)


1.
2.
3.
4.
5.
6.
7.
8.

if (n = NULL or n.value = key ) then


return n
end-if
if (key < n.value) then
return SEARCH_BINARY_TREE(n.left, key)
else
return SEARCH_BINARY_TREE(n.right, key)
end-if

INSERT_BINARY_TREE (root, data)


1. if (root = null) then
2.
root = new Node(data)
3. else if (data < root->data) then
4. INSERT_BINARY_TREE (root.left, data)
5. else if (data > root->data) then
6.
INSERT_BINARY_TREE (root.right, data)

Implement the above logic in Java after learing through the concept of Relationships in
Java.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 67 of 170

Infosys Limited

Assignments for OO programming using Java part1

Estimated Time: 20 minutes


Summary of this assignment: In this assignment you have learnt about search
operation in Binary search tree.

Advanced Data Structures - Binary Search Tree: Assignment 46


Objective: Given a data structure, be able to identify the operations to be performed
and represent the logic
Problem description: Consider the binary search tree discussed in the previous
assignment.
Insert a new node with the value 4. Record the steps followed in inserting the same.
Insert a new node with the value 16. Record the steps followed in inserting the same.
After inserting the node with the value 4, Record the steps to be followed for searching
the node with value 4.
Estimated Time: 20 minutes
Summary of this assignment: In this assignment you have learnt about insert and
search operations in binary search tree.

Assignment 47: Arrays - Quiz


Objective: Observe the need for features in the retail application scenario to correlate
the application of arrays
Problem Description: Consider the below given code snippet and answer the following
questions:
Code Snippet:
long telephoneNo[] = {48214280200L, 9901911334L, 4821710601L};
System.out.println(telephoneNo[0]);
System.out.println(telephoneNo[3]);

Answer the following questions:


ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 68 of 170

Infosys Limited

Assignments for OO programming using Java part1

1. What is the size of the array, telephoneNo?


2. What will be the output of the first println statement in the code snippet given above?
3. What will be the output of the second println statement in the code snippet given
above?
Answers:
1.

Sizeofthearray,telephoneNois3.
Note:Ifsizeisnotexplicitlymentionedwhiledeclaringanarrayusingnewoperator,itistakenasthe
numberofelementsinitialized

2.

48214280200

3.

Runtimeexception,sincewearetryingtoaccessanelementoutsidethearray.
Note:Arrayboundcheckinghappensexplicitly

Estimated time: 10 minutes


Summary of this assignment: In this assignment, you have understood the need of
length property in arrays

Assignment 48: Arrays - Demo


Objective: Given a class diagram for a use case representing a computational problem,
be able to use the right data structures (arrays and strings) and implement the solution
to the problem and test using a set of values in an IDE
Problem Description: In the retail application, along with the earlier details included for
Customer, the retail shop wants to keep track of customers residence telephone
number, mobile number and office telephone number.
The class diagram discussed in Object Oriented Fundamentals Assignment 7 has been
modified as shown below.
Class diagram:
Customer
-customerId
-telephoneNo

: int
: long[]

+setCustomerId(int)
: void
+getCustomerId()
: int
+setTelephoneNo(long[]) : void
+getTelephoneNo()
: long[]
Code:

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 69 of 170

Infosys Limited

Assignments for OO programming using Java part1

Execute the code using Eclipse IDE with the given inputs in the starter class, Retail and
observe the results.
Notehowanarrayisusedasan
instancevariableofaclass

class Customer{
private int customerId;
private long[] telephoneNo;
public void setCustomerId(int id){
customerId = id;
}

Notehowanarrayisusedasa
formalargument

public void setTelephoneNo(long[] teleNo){


telephoneNo=teleNo;
Notehowanarrayisreturnedfrom
}
amethod
public int getCustomerId(){
return customerId;
}
public long[] getTelephoneNo(){
return telephoneNo;
Notehowthearrayisdeclaredand
}
initialized.Canyouinitializeusing
}

anyothermethod?

class

Retail{
public static void main(String args[]){
Customer custObj = new Customer();
custObj.setCustomerId(1001);
long[] telephoneNo = new long[3];
Notehowanarrayispassedtoa
telephoneNo[0]=9201861311L;
method.Whatkindofparameter
telephoneNo[1]=9201861321L;
passingtechniqueisusedhere?
telephoneNo[2]=9201661311L;
custObj.setTelephoneNo(telephoneNo);
System.out.println("Customer Id:"+
custObj.getCustomerId());
long[] temp = custObj.getTelephoneNo();
System.out.println("Telephone Nos:"+ temp[0]+ " "+temp[1]+"
"+ temp[2]);
Notehowanarrayisreceivedfroma
}
methodandarrayelementsare
}
displayed

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 70 of 170

Infosys Limited

Assignments for OO programming using Java part1

Output:
CustomerId:1001
TelephoneNos:920186131192018613219201661311

Estimated time: 20 minutes


Summary of this assignment: In this assignment, you have understood the
implementation of arrays using a retail application scenario

Assignment 49: Strings Observations from Retail Application


Objective: Observe the need for features in the retail application scenario to correlate
the application of Strings
Problem Description: In the retail application, along with the earlier details included for
Customer, the retail shop wants to keep track of customer name. Customer name
should be between 3 and 20 characters.
Answer the following question:
What do you think is needed to implement the solution for the above problem?
Estimated time: 10 minutes
Summary of this assignment: In this assignment, you have understood the need of
strings using a retail application scenario

Assignment 50: Strings - Quiz


Objective: Observe the need for String concepts
Problem Description: Consider the below given code snippet and answer the following
questions:
Code Snippet 1:
String customerName = new String(Jack);
customerName = John;

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 71 of 170

Infosys Limited

Assignments for OO programming using Java part1

Note: Assume that the code snippet is written inside the main () method
Answer the following questions:
1. Where do you think memory will be allocated for customerName and the String
object with value Jack?
2. What will happen to the String object with value Jack when the second statement
in the code snippet is executed?
NotethatJackisstill
presentinmemory

This means that String objects are immutable


Code Snippet-2:
String customerName = new String(Jack);
String oldCustomerName = customerName;
customerName = John;

Note: Assume that the code snippet is written inside the main () method
Answer the following questions:
1. Where do you think memory will be allocated for customerName and the String
objects with value Jack and John?
2. Identify which reference variable will refer to which String object at the end of
execution of all the three statements in the code snippet?

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 72 of 170

Infosys Limited

Assignments for OO programming using Java part1

Assignment 51: Strings Demo


Problem Description: In the retail application, along with the earlier details included for
Customer, the retail shop wants to keep track of customer name. Customer name
should be between 3 and 20 characters.
Class diagram:
Customer
-customerId
: int
-telephoneNo
: long[]
-customerName
: String
+setCustomerId(int)
: void
+getCustomerId()
: int
+setTelephoneNo(long[])
: void
+getTelephoneNo()
: long[]
+setCustomerName(String) : void
+getCustomerName()
: String
+validateCustomerName() : boolean
Code:
Execute the code using Eclipse IDE with the given inputs in the starter class, Retail and
observe the results.
class Customer{
private int customerId;
private long[] telephoneNo = new long[3];
private String customerName;
NotehowaStringisusedasan
instancevariableofaclass
ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 73 of 170

Infosys Limited

Assignments for OO programming using Java part1

public void setCustomerId(int id){


customerId = id;
}
public void setTelephoneNo(long[] teleNo){
telephoneNo=teleNo;
}
public int getCustomerId(){
return customerId;
}
NotehowStringispassedtoa
public long[] getTelephoneNo(){
method
return telephoneNo;
}
public void setCustomerName(String customerName){
this.customerName=customerName;
}
NotehowStringisreturnedfroma
public String getCustomerName(){
method
return customerName;
}
public boolean validateCustomerName(){
Whatdoyouthinkisneededto
writethelogicforthismethodwhich
shouldcheckwhethercustomer
nameisbetween3and20?

}
}
class

Retail{

public static void main(String args[]){


Customer custObj = new Customer();
custObj.setCustomerId(1001);
long[] telephoneNo = new long[3];
telephoneNo[0]=9201861311L;
telephoneNo[1]=9201861321L;
telephoneNo[2]=9201661311L;
custObj.setTelephoneNo(telephoneNo);
custObj.setCustomerName("Kevin");
}
}

Revised Code:

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 74 of 170

Infosys Limited

Assignments for OO programming using Java part1

class Customer{
private int customerId;
private long[] telephoneNo = new long[3];
private String customerName;
public void setCustomerId(int id){
customerId = id;
}
public void setTelephoneNo(long[] teleNo){
telephoneNo=teleNo;
}
public int getCustomerId(){
return customerId;
}
public long[] getTelephoneNo(){
return telephoneNo;
}
public void setCustomerName(String customerName){
this.customerName=customerName;
}
public String getCustomerName(){
return customerName;
}
public boolean validateCustomerName(){
if(customerName.length()>=3 && customerName.length()<=20){
return true;
}
Notehowlength()methodisused
return false;
forcheckingthenumberof
}
charactersinaStringobject
}
class

Retail{
public static void main(String args[]){
Customer custObj = new Customer();
custObj.setCustomerId(1001);
long[] telephoneNo = new long[3];

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 75 of 170

Infosys Limited

Assignments for OO programming using Java part1

telephoneNo[0]=9201861311L;
Notehowlogiciswrittenusingthe
telephoneNo[1]=9201861321L;
returnvalueof
telephoneNo[2]=9201661311L;
validateCustomerName()method
custObj.setTelephoneNo(telephoneNo);
custObj.setCustomerName("Kevin");
if(custObj.validateCustomerName()){
System.out.println("Customer Id:"+
custObj.getCustomerId());
long[] temp = custObj.getTelephoneNo();
System.out.println("Telephone Nos:"+ temp[0]+ "
"+temp[1]+" "+ temp[2]);
System.out.println("Customer
Name:"+custObj.getCustomerName());
}
else{
System.out.println("Invalid customer name. Customer
name must be between 3 and 20 characters");
}
Notehowtheerrormessageis
}
written
}

Output:
CustomerId:1001
TelephoneNos:920186131192018613219201661311
CustomerName:Kevin

Estimated time: 20 minutes


Summary of this assignment: In this assignment, you have understood the
implementation of Strings and String methods using a retail application scenario

Assignment 52: Strings - Quiz


Objective: Revisit String concepts through a quiz

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 76 of 170

Infosys Limited

Assignments for OO programming using Java part1

Q1. What is the output of the following code snippet?


class Demo{
public static void main(String args[]){
String string1 = new String("Hello");
String string2= new String("Hello");
System.out.println(string1==string2);
System.out.println(string1.equals(string2));
}
}

Q2. What is the output of the following code snippet?


class Demo{
public static void main(String args[]){
String stringOne=new String("Infosys");
String stringTwo=new String("Infosys");
stringOne.toUpperCase();
String stringThree=stringOne;
if(stringThree==stringTwo){
System.out.println("Equal");
}
else{
System.out.println("Not Equal");
}
if(stringThree.equalsIgnoreCase(stringTwo)){
System.out.println("Equal" + " "+stringOne);
}
else{
System.out.println("Not Equal");
}
}
}

Q3. What is the output of the following code snippet?


class Demo {
public static void main(String args[]) {
String str = "Infy";
String str1 = "Mysore";

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 77 of 170

Infosys Limited

Assignments for OO programming using Java part1

String str3 = str.concat(" "+str1);


System.out.println(str3);
}
}

Q4. What is the output of the following code snippet?


class Demo
{
public static void main(String args[])
{
String stringOne="Hello", stringTwo = "";
int length = stringOne.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
stringTwo = stringTwo + stringOne.charAt(i);
System.out.println("Output: "+stringTwo);
}
}

ANSWERS
Q1.
false
true
Q2.
Not Equal
Equal Infosys
Q3.
Infy Mysore
Q4.
Output: olleH
Estimated time: 15 minutes
Summary of this assignment: In this assignment, you have revisited concepts of
strings through code snippets

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 78 of 170

Infosys Limited

Assignments for OO programming using Java part1

Assignment 53: Constructors & Static keyword Observations


from Retail Application
Objective: Observe the need for features in the retail application scenario to correlate
the application of constructors and static keyword
Problem Description: In the retail application, each time a customer is registered,
customer id must be automatically generated starting from 1001 and the details of the
customer must be initialized. Also, retail shop management wants to know how many
customers have registered at a point of time.
Answer the following question:
What do you think is needed to implement the solution for the above problem?
Estimated time: 10 minutes
Summary of this assignment: In this assignment, you have learnt
The need of constructors and static keyword in the retail application scenario

Assignment 54: Constructors Default Constructor - Demo


Objective: Given a class diagram for a use case representing a computational problem,
initialize the data members using default constructors, parameterized constructors and
test using a set of values in an IDE
Problem Description: In the retail application, as a customer is registered to the retail
shop, the details of the customer must also be initialized.
Let us revisit the class diagram discussed in Object Oriented Fundamentals Assignment 48
Class diagram:

Customer
-customerId
: int
-telephoneNo
: long[]
-customerName
: String
+ setCustomerId(int)
: void
+getCustomerId()
: int
+setTelephoneNo(long[])
: void
+getTelephoneNo()
: long[]

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 79 of 170

Infosys Limited

Assignments for OO programming using Java part1

+setCustomerName(String) : void
+getCustomerName()
: String
+validateCustomerName() : boolean
Code:
Execute the code using Eclipse IDE with the given inputs in the starter class, Retail and
observe the results.
class Customer{
private int customerId;
private long[] telephoneNo;
private String customerName;
public void setCustomerId(int id){
customerId = id;
}
public void setTelephoneNo(long[] teleNo){
telephoneNo=teleNo;
}
public int getCustomerId(){
return customerId;
}
public long[] getTelephoneNo(){
return telephoneNo;
}
public void setCustomerName(String customerName){
this.customerName=customerName;
}
public String getCustomerName(){
return customerName;
}
public boolean validateCustomerName(){
if(customerName.length()>=3 && customerName.length()<=20){
return true;
}
return false;
}
}

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 80 of 170

Infosys Limited

class

Assignments for OO programming using Java part1

Notethatsincewehavenotexplicitlycoded
theconstructor,systemprovidesadefault
constructorwhichinitializestheinstance
variablestotheirdefaultvalues

Retail{

public static void main(String args[]){


Customer custObj = new Customer();
System.out.println("Customer Id:"+
custObj.getCustomerId());
long[] temp = custObj.getTelephoneNo();
System.out.println("Telephone Nos:"+ temp[0]+ " "+temp[1]+"
"+ temp[2]);
System.out.println("Customer
Name:"+custObj.getCustomerName());
}
}

Output:
CustomerId:0
TelephoneNos:000
CustomerName:null

Revised Code: The code above has been revised by adding default constructor
class Customer{
private int customerId;
private long[] telephoneNo = new long[3];
private String customerName;
Notehowdefaultconstructorisredefined
public Customer(){
customerId=1000;
telephoneNo[0]=999999999L;
telephoneNo[1]=999999999L;
telephoneNo[2]=999999999L;
customerName="Default";
}
public void setCustomerId(int id){
customerId = id;

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 81 of 170

Infosys Limited

Assignments for OO programming using Java part1

}
public void setTelephoneNo(long[] teleNo){
telephoneNo=teleNo;
}
public int getCustomerId(){
return customerId;
}
public long[] getTelephoneNo(){
return telephoneNo;
}
public void setCustomerName(String customerName){
this.customerName=customerName;
}
public String getCustomerName(){
return customerName;
}
public boolean validateCustomerName(){
if(customerName.length()>=3 && customerName.length()<=20){
return true;
}
return false;
}
}
class Retail{
public static void main(String args[]){
Customer custObj = new Customer();
System.out.println("Customer Id:"+
custObj.getCustomerId());
long[] temp = custObj.getTelephoneNo();
System.out.println("Telephone Nos:"+ temp[0]+ " "+temp[1]+"
"+ temp[2]);
System.out.println("Customer
Name:"+custObj.getCustomerName());
}
}

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 82 of 170

Infosys Limited

Assignments for OO programming using Java part1

Output:
CustomerId:1000
Doyouthinkthiswillsatisfythe
requirementprovidedaspartof
problemdescription?

TelephoneNos:999999999999999999999999999
CustomerName:Default

NoValuesinitializedforeachcustomermustbedifferent.Itdependsoneachcustomer.Thiscanbeachieved
usingparameterizedconstructor

Estimated time: 20 minutes


Summary of this assignment: In this assignment, you have understood the
implementation of default constructor and the need of parameterized constructor using
a retail application scenario.

Assignment 55: Constructors Parameterized Constructor Demo


Objective: Given a class diagram for a use case representing a computational problem,
initialize the data members using default constructors, parameterized constructors and
test using a set of values in an IDE
Problem Description: In the retail application, as a customer is registered to the retail
shop, the details of the customer must also be initialized.
The class diagram discussed in Object Oriented Fundamentals Assignment 51 has
been modified as shown below.
Class diagram:
Customer
-customerId
: int
-telephoneNo
: long[]
-customerName
: String
+ Customer(int, long[], String)
+ setCustomerId(int)
: void
+getCustomerId()
: int
+setTelephoneNo(long[])
: void
+getTelephoneNo()
: long[]
+setCustomerName(String) : void
+getCustomerName()
: String
+validateCustomerName() : boolean

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 83 of 170

Infosys Limited

Assignments for OO programming using Java part1

Code:
Execute the code using Eclipse IDE with the given inputs in the starter class, Retail and
observe the results.
class Customer{
private int customerId;
private long[] telephoneNo;
private String customerName;
public Customer(int customerId, long[] telephoneNo, String
customerName){
this.customerId=customerId;
Notehowparameterizedconstructoriswritten
this.telephoneNo=telephoneNo;
this.customerName=customerName;
}
public void setCustomerId(int id){
customerId = id;
}
public void setTelephoneNo(long[] teleNo){
telephoneNo=teleNo;
}
public int getCustomerId(){
return customerId;
}
public long[] getTelephoneNo(){
return telephoneNo;
}
public void setCustomerName(String customerName){
this.customerName=customerName;
}
public String getCustomerName(){
return customerName;
}
public boolean validateCustomerName(){
if(customerName.length()>=3 && customerName.length()<=20){
return true;

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 84 of 170

Infosys Limited

Assignments for OO programming using Java part1

}
return false;
}
}
class

Retail{

public static void main(String args[]){


long[] telephoneNo = new long[3];
Notehowparameterizedconstructorisinvoked
telephoneNo[0]=9201861311L;
telephoneNo[1]=9201861321L;
telephoneNo[2]=9201661311L;
Customer custObj = new Customer(1001, telephoneNo,
"Kevin");
if(custObj.validateCustomerName()){
System.out.println("Customer Id:"+
custObj.getCustomerId());
long[] temp = custObj.getTelephoneNo();
System.out.println("Telephone Nos:"+ temp[0]+ "
"+temp[1]+" "+ temp[2]);
System.out.println("Customer
Name:"+custObj.getCustomerName());
}
else{
System.out.println("Invalid customer name. Customer
name must be between 3 and 20 characters");
}
}
}

Output:
CustomerId:1001
TelephoneNos:920186131192018613219201661311
CustomerName:Kevin

Assignment 56: static keyword - Demo


Objective: Given a class diagram for a use case representing a computational problem,
use static keyword and test using a set of values in an IDE

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 85 of 170

Infosys Limited

Assignments for OO programming using Java part1

Problem Description: In the retail application, each time a customer is registered,


customer id must be automatically generated starting from 1001. Also, retail shop
management wants to know how many customers have registered at a point of time.
The class diagram discussed in Object Oriented Fundamentals Part II Assignment 10
has been modified as shown below.
Note: Few instance variables are not shown in the class diagram so as to keep the
code simple to understand.
Class diagram:
Customer
-customerId
+Customer()
+setCustomerId(int)
+getCustomerId()
+totalNoOfCustomers()

: int
: void
: int
: int

Code:
Execute the code using Eclipse IDE with the given inputs in the starter class, Retail and
observe the results.
class Customer{
private int customerId=1000;
public Customer(){
this.customerId++;
}
public void setCustomerId(int id){
customerId = id;
}
public int getCustomerId(){
return customerId;
}
public int totalNoOfCustomers(){
return 0;
}
}
class

Howdowefindthetotal
numberofcustomerswhohave
registeredtotheretailshop?

Retail{

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 86 of 170

Infosys Limited

Assignments for OO programming using Java part1

public static void main(String args[]){


Customer custObjOne = new Customer();
System.out.println("Customer Id:"+
custObjOne.getCustomerId());
Customer custObjTwo = new Customer();
System.out.println("Customer Id:"+
custObjTwo.getCustomerId());

}
}
Output:
CustomerId:1001
Whydoyouthinkcustomeridis
notautoincrementedforeach
customer?

CustomerId:1001

customerId is an instance variable of Customer class and it will be created separately for each and every
object of Customer class. Hence each time an object of Customer class is created, constructor is called
and customerId will be initialized to 1000 and will be incremented by 1 in the constructor as a result for
all the objects customerId will remain as 1001. Hence we need to have a variable common to all the
objects of Code:
Customer
Modified
A class
modified version of the above code is provided below

Execute the code using Eclipse IDE with the given inputs in the starter class, Retail and
observe the results.
class Customer{
Notehowastaticvariableisdeclared
private int customerId;
private static int counter;
Notehowastaticblockiswrittenandhowitis
static{
usedtoinitializeastaticvariable
counter=1000;
}
Notehowautogenerationlogicisimplemented
public Customer(){
this.customerId=++counter;
}
public void setCustomerId(int id){

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 87 of 170

Infosys Limited

Assignments for OO programming using Java part1

customerId = id;
}
public int getCustomerId(){
Notehowstaticmethodiswritten
return customerId;
}
public static int totalNoOfCustomers(){
return counter-1000;
}
}
class

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

Customer custObjOne = new Customer();


System.out.println("Customer Id:"+
custObjOne.getCustomerId());
Customer custObjTwo = new Customer();
System.out.println("Customer Id:"+
custObjTwo.getCustomerId());
System.out.println("Total number of
customers:"+Customer.totalNoOfCustomers());
Notehowstaticmethodisinvokedusing
theclassname

}
}
Output:
CustomerId:1001

Estimated time: 20 minutes


CustomerId:1002
Totalnumberofcustomers:2

Assignment 57: Command Line Arguments Demo


Objective: Given a class diagram for a use case representing a computational problem,
be able to, initialize the data members using default constructors, parameterized
constructors, command line arguments (integer and String) and test using a set of
values in an IDE

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 88 of 170

Infosys Limited

Assignments for OO programming using Java part1

Problem Description: The customers of the Retail Store have the option of paying the
bill by cash or by using credit card. In case the customer uses credit card, processing
charges are applicable which is computed as a percentage of the bill amount.

Class diagram:
PurchaseBill
-billId: int
-billAmount:double
+setBillId(int): void
+setBillAmount(double):void
+getBillId(): int
+getBillAmount():double
+calculateBill(String, int): void
Assumption: In this problem, it has been assumed that
mode of payment and processing charge will be keyed in as inputs to the
program
processing charge is considered as an integer value
Note: In the retail application provided to you, a graphical user interface is provided for
entry of data. As these classes and methods are out of scope of this course, the data
entry through command line arguments is introduced here as a provision to input data.
Code:
Execute the code using Eclipse IDE by passing mode of payment and processing
charge using command line arguments and observe the results.
class PurchaseBill{
private int billId;
private double billAmount;
public void setBillId(int id){
billId=id;
}
public void setBillAmount(double amount){
billAmount=amount;
}
public int getBillId(){
return billId;
}
public double getBillAmount(){
return billAmount;
}

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 89 of 170

Infosys Limited

Assignments for OO programming using Java part1

public void calculateBill(String modeOfPayment,int


processingCharge){
int discount=0;
if(billAmount>=1000.0){
discount=10;
Notethehowprocessingchargeis
}
addedtobillamountbasedonmode
else if(billAmount>=500.0){
ofpayment
discount=5;
}
System.out.println("Discount %:"+discount);
billAmount=billAmount-billAmount*discount/100.0;
if(modeOfPayment.equalsIgnoreCase("Credit")){
billAmount=billAmount +
(billAmount*processingCharge/100.00);
Whydoyouthink
}
commandline
}
argumentsare
consideredasString?
}
Notehowcommandlinearguments
class Retail{
arepassedtomainmethodasString
public static void main(String args[]){
arguments
String modeOfPayment=args[0];
int processingCharge=args[1];
PurchaseBill purObj=new PurchaseBill();
Notehowcommandlinearguments
purObj.setBillId(1001);
areaccessedinaprogram
purObj.setBillAmount(1055.00);
System.out.println("Bill Id:"+purObj.getBillId());
purObj.calculateBill(modeOfPayment,processingCharge);
System.out.println("Final Bill
Amount:"+purObj.getBillAmount());
}
}

Output:
CompilationError:CannotconvertStringtoint
Whatdoyouthinkisthe
reasonforthiserror?

In this case, processingCharge is an integer and we are assigning a String to it.


Hence, we need to convert the String to integer before assigning it to processingCharge
ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 90 of 170

Infosys Limited

Assignments for OO programming using Java part1

Revised Code:

class PurchaseBill{
private int billId;
private double billAmount;
public void setBillId(int id){
billId=id;
}
public void setBillAmount(double amount){
billAmount=amount;
}
public int getBillId(){
return billId;
}
public double getBillAmount(){
return billAmount;
}
public void calculateBill(String modeOfPayment,int
processingCharge){
int discount=0;
if(billAmount>=1000.0){
discount=10;
}
else if(billAmount>=500.0){
discount=5;
}
System.out.println("Discount %:"+discount);
billAmount=billAmount-billAmount*discount/100.0;
if(modeOfPayment.equalsIgnoreCase("Credit")){
billAmount=billAmount +
(billAmount*processingCharge/100.00);
}
}
}
class Retail{
public static void main(String args[]){

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 91 of 170

Infosys Limited

Assignments for OO programming using Java part1

String modeOfPayment=args[0];
int processingCharge=Integer.parseInt(args[1]);
PurchaseBill purObj=new PurchaseBill();
Notethehowargs[1]isconvertedto
purObj.setBillId(1001);
integerbeforeassigningitto
purObj.setBillAmount(1055.00);
processingcharge
System.out.println("Bill Id:"+purObj.getBillId());
purObj.calculateBill(modeOfPayment,processingCharge);
System.out.println("Final Bill
Amount:"+purObj.getBillAmount());
}
}

Execute the above revised code using the following values as command line arguments
Case 1:
Command line arguments to be passed Cash and 0
Case 2:
Command line arguments to be passed Credit and 5
Case1Output:
BillId:1001
FinalBillAmount:1055.0

Case2Output:
BillId:1001
FinalBillAmount:1107.75

Note: Follow the steps below to use the Command Line arguments to execute
Java Program in Eclipse
To pass command line arguments while, go to RunRun Configurations

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 92 of 170

Infosys Limited

Assignments for OO programming using Java part1

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.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 93 of 170

Infosys Limited

Assignments for OO programming using Java part1

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.

Estimated time: 15 minutes


Summary of this assignment: In this assignment, you have learnt the need and use of
command line arguments using a retail application scenario

Algorithm Design Techniques: Assignment 58


Objective: Given a problem scenario, be able to identify the logical approaches to solve
the problem using algorithm design techniques.
Problem description: Observe the following scenarios and make note of your
observations:
1. You are in a party; suddenly you realized that your friend is missing. How would
you search him in the party?

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 94 of 170

Infosys Limited

Assignments for OO programming using Java part1

2. The manager of a retail store would like to know how many customers have
purchased items worth more than $500. What would be your approach to get the
list of customers?
3. The sales clerk of a medical shop would like to arrange the medicines in
separate shelves as per manufacturer so that the time taken to retrieve a
particular medicine would be less. What is the approach followed by sales clerk?

Algorithm Design Techniques: Assignment 59


Objective: Given a problem scenario, be able to identify the logical approach to solve
the problem using algorithm design techniques.
Problem description: Observe the following scenarios and make note of your
observations:
1. A lock manufacturing company manufactures 10 locks and keys in a day. These
locks and keys are uniquely numbered. Locks are all kept in one box and keys in
another. You are asked to put the right key with the lock in a box.
What is your approach to solve the problem?
Assume that the company manufactures 1000000 locks and keys in a day. Will
you change your approach to solve the problem? Do you see a noticeable
change in the time to solve?
Given below is one approach to perform the above operation.
Assumptions: Array index starts from 1

Algorithm: Linear search


Input: A list of N elements and a search key S
Output: Search key S position if present in the list otherwise unsuccessful
Step 1: Assign 1 to i
Step 2: Compare value at ith index with the search key S
Step 3: if key S is found, display index i and exit
Step 4: Otherwise, increment the value of i by 1 and repeat from step 2 until last
element of the
list is compared
Step 5: Display search unsuccessful and exit.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 95 of 170

Infosys Limited

Assignments for OO programming using Java part1

Pseudo-code is represented below:


1. for i=1 to N
2.
if (ith element of the list = S) then
3.
return i
4.
end-if
5. end-for
6. display Search Unsuccessful
Write a Java code to implement linear search algorithm and execute it using
Eclipse.

You have a bundle of currency of varied denominations. You want to arrange them in
ascending order.
Given below is one approach to perform the above operation.
Algorithm: Bubble Sort (Array of N element)
Input: An array of N elements to be sorted
Output: An array of sorted (increasing order) of N elements
Step 1: Repeat steps 2 and 3 for n-1 times
Step 2: Repeat step 3 for 1 time less than n
Step 3: Compare first element with next element and swap if second element is greater

Pseudo-code is represented below:


1. for i =1 to N -1
2.
for j = 1 to N - i
3.
if ( Arr[ j ] > Arr[ j + 1]) then
4.
interchange (Arr[ j ] , Arr[ j +1])
5.
end-if
6.
end-for
7. end-for
Write a Java code to implement bubble sort technique and execute it using
Eclipse.

Estimated Time: 20 minutes


Summary of this assignment: In this assignment you have learnt that Brute force is
straight forward, simple and widely applicable approach to solve a problem but time

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 96 of 170

Infosys Limited

Assignments for OO programming using Java part1

consuming approach if problem size is large using linear search and bubble sort
algorithms.

Algorithm Design Techniques: Assignment 60-A


Objective: Given a problem scenario, be able to identify the logical approach to solve
the problem using algorithm design techniques.
Problem description: Assume that you need to check the status of the PNR number of
your ticket (Assume that the chart is in sorted order based on PNR number). What
might be the approach to solve the problem?
Given below is one approach to perform the above operation.
Assumptions: Array index starts from 0
Algorithm: Binary Search (Array of N elements, Search element S)
Input: An array A of N elements in sorted order and a search key S
Output: Search key S position if present in the list
Step 1: Assign 0 to low, N-1 to high
Step 2: Repeat steps 3 to 5 until low is smaller than or equal to high
Step 3: Assign (low + high) / 2 to midpoint
Step 4: If S is equal to value at midpoint index then, Display midpoint index and exit
Step 5: Otherwise, If S is smaller than value at midpoint index then, Assign midpoint 1
to
High. Otherwise Assign midpoint + 1 to low
Pseudo-code is represented below:
1. Low = 0
2. High = N-1
3. while (High>=Low) do
4.
mid = (High + Low)/2
5.
if (A [mid] = S) then
6.
return mid
7.
else
8.
if (A [mid] < S) then
9.
low = mid +1
10.
else
11.
high = mid -1

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 97 of 170

Infosys Limited

Assignments for OO programming using Java part1

12.
end-if
13.
end-if
14. end-while
Write a Java code to implement binary search technique and execute it using
Eclipse.

Estimated Time: 20 minutes


Summary of this assignment: In this assignment you have learnt that divide and
conquer, divides the problems in to independent sub problems and solve each sub
problem to get the desired solution with the help of binary search algorithm.

Algorithm Design Techniques: Assignment 60-B


Objective: Understand the benefit of dynamic programming.
Problem Description: Refer to Assignment 29b where you implemented generation of
Fibonocci series using Recursion. To do a small analysis of recursion, let nk denote
number of recursive calls made by Fib(k).
Then
n0 = 1

n1 = 1

n2 = n1 + n0 + 1 = 1 + 1 + 1 = 3

n 3 = n2 + n1 + 1 = 3 + 1 + 1 = 5

n 4 = n3 + n2 + 1 = 5 + 3 + 1 = 9

n5 = n4 + n3 + 1 = 9 + 5 + 1 = 15

n6 = n5 + n4 + 1 = 15 + 9 + 1 = 25

n7 = n6 + n5 + 1 = 25 + 15 + 1 = 41

n8 = n7 + n6 + 1 = 41 + 25 + 1 = 67.

Note that the value at least doubles for every other value of nk. That is, nk > 2k/2. It is
exponential!

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 98 of 170

Infosys Limited

Assignments for OO programming using Java part1

Implement the same Fibonacci series generation program using dynamic programming.
Consider the following pseudo-code:
FIBO (number)
2. F[0] = 0
3. F[1] = 1
4. for i = 2 to number
5. F[i] = F[i-1] + F[i-2]
6. end for
7. return F[number]

Write a program in Java to implement the same and execute it in Eclipse.


In order to understand the benefit, compare the time taken to compute FIBO(100) using
both strategies i.e.Brute force recursive algorithm (assignment 29b) and dynamic
programming.
Estimated time: 20 minutes
Summary of this assignment: In this assignment, you have learnt how to implement
dynamic programming.

OO constructs II
Assignment 61: Method Overloading- Observations from Retail
application
Objective: Observe the need for features in the retail application scenario to correlate
the application of method overloading
Problem Description: The Retail Store has the requirement for printing many reports
including the bill. All reports contain header. The header may be

a line containing a character printed 70 times or


a title of a report or
a line containing a character specified number of times

Answer the following questions:

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 99 of 170

Infosys Limited

Assignments for OO programming using Java part1

1. Which object oriented concept do you think is needed to implement this


scenario?
Estimated time: 10 minutes
Summary of this assignment: In this assignment, you have understood the need of
method overloading using a retail application scenario

Assignment 62: Method Overloading Demo


Objective: Given a class diagram for a use case representing a computational problem,
use method and constructor overloading techniques to solve the problem and test using
a set of values in an IDE and recognize the benefits of static polymorphism

Problem Description: The scenario discussed in OO Concepts Part I Assignment 1 is


revisited here. The Retail Store has the requirement for printing many reports including
the bill. All reports contain header. The header may be

a line containing a character printed 70 times or


a title of a report or
a line containing a character specified number of times

A new class called PrintDetails with overloaded methods have to be created as shown
below:

Code:
Execute the code using Eclipse IDE with the given inputs in the starter class, Retail and
observe the results.

Notehowthreemethodswiththe
samename,printHeader()but
differentargumentlistiswrittenin
classPrintDetails

class PrintDetails{

public void printHeader(char c){


for(int counter=0;counter<70;counter++){
System.out.print(c);
}
}

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 100 of 170

Infosys Limited

Assignments for OO programming using Java part1

public void printHeader(char c, int no){


for(int counter=0;counter<no;counter++){
System.out.print(c);
}
}
public void printHeader(String s){
System.out.println(s);
}
}
class Retail{
public static void main(String args[]){
PrintDetails obj=new PrintDetails();
obj.printHeader('*',10);
System.out.println(" ");
obj.printHeader("Report");
Notehowtheoverloadedmethods
System.out.println(" ");
areinvokedbypassingthe
appropriatearguments
obj.printHeader('*',10);
}
}

Output:
**********
Report

**********

Estimated time: 20 minutes


Summary of this assignment: In this assignment, you have learnt the need and
implementation of method overloading using a retail application scenario.

Assignment 63: Method Overloading - Quiz


Objective: Revisit method overloading concepts through a quiz
Q1. What is the output of the following code snippet?
class Example{

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 101 of 170

Infosys Limited

Assignments for OO programming using Java part1

public void disp(float num1,int num2){


System.out.println("First disp method in the Example Class");
System.out.println("num1="+num1);
}
public void disp(int num1,int num2){
System.out.println("Second disp method in the Example Class");
System.out.println("num1="+num1);
}
}
class Demo{
public static void main(String args[]){
Example obj=new Example();
obj.disp((int)60.80,20);
}
}

Q2. What is the output of the following code snippet?


class Example{
public void disp(float num1,int num2){
System.out.println("First disp method in the Example Class");
System.out.println("num1="+num1);
}
public int disp(int num1,int num2){
System.out.println("Second disp method in the Example Class");
System.out.println("num1="+num1);
return num1;
}
}
class Demo{
public static void main(String args[]){
Example obj=new Example();
obj.disp(60,20);
}
}

Q3. What is the output of the following code snippet?


class Example{
public int disp(int num1,int num2){
System.out.println("First disp method in the Example Class");
System.out.println("num1="+num1);

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 102 of 170

Infosys Limited

Assignments for OO programming using Java part1

return num1;
}
public int disp(int no1,int no2){
System.out.println("Second disp method in the Example Class");
System.out.println("no1="+no1);
return no1;
}
}
class Demo{
public static void main(String args[]){
Example obj=new Example();
obj.disp(60,20);
}
}

Q4. What is the output of the following code snippet?


class Example{
public void disp(int num1,int num2){
System.out.println("First disp method in the Example Class");
System.out.println("num1="+num1);
}
public int disp(int num1,int num2){
System.out.println("Second disp method in the Example Class");
System.out.println("num1="+num1);
return num1;
}
}
class Demo{
public static void main(String args[]){
Example obj=new Example();
obj.disp(60,20);
}
}

ANSWERS
Q1.
Second disp method in the Example Class
num1=60
Q2.
Second disp method in the Example Class
num1=60
ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 103 of 170

Infosys Limited

Assignments for OO programming using Java part1

Q3.
Compilation Error: more than one method with the same name and argument list cannot
be given in a class
Q4.
Compilation Error: a class cannot have more than one method with the same name and
argument list
Estimated time: 15 minutes
Summary of this assignment: In this assignment, you have revisited concepts of
method overloading through code snippets

Assignment 64: Constructor Overloading Demo


Objective: Given a class diagram for a use case representing a computational problem,
use method and constructor overloading techniques to solve the problem and test using
a set of values in an IDE and recognize the benefits of static polymorphism

Problem Description:

The class diagram discussed in OO Fundamentals has been modified as shown below
to demonstrate constructor overloading.
Note: Few methods are not shown in the class diagram so as to keep the code simple
to understand.
Class diagram:
Customer
-customerId
-telephoneNo
-customerName
-counter
+Customer()
+Customer(long[], String)
+getCustomerId()
+getTelephoneNo()
+getCustomerName()

: int
: long[]
: String
: int -> static

: int
: long[]
: String

Code:
Execute the code using Eclipse IDE with the given inputs in the starter class, Retail and
observe the results.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 104 of 170

Infosys Limited

Assignments for OO programming using Java part1

class Customer{
private int customerId;
private long[] telephoneNo = new long[3];
private String customerName;
Notethattwoconstructorsare
private static int counter =1000;
written,onewhichisthedefault
constructorandotherwhichisa
public Customer(){
parameterizedconstructor
customerId=++counter;
}
public Customer( long[] telephoneNo, String customerName){
this.telephoneNo=telephoneNo;
this.customerName=customerName; Notethatdefaultconstructoristakingcareofauto
}
generationlogicandtheparameterizedconstructoris
public int getCustomerId(){
return customerId;
}
public long[] getTelephoneNo(){
return telephoneNo;
}

initializingtheotherinstancevariables.Understandthat
logiciswrittenlikethistoillustrateconstructor
overloading,shouldnotbegeneralizedasarule

public String getCustomerName(){


return customerName;
}
}
class

Retail{
public static void main(String args[]){
long[] telephoneNo = new long[3];
Notethatfortheobject,custObj1,
telephoneNo[0]=9201861311L;
defaultconstructorisbeinginvoked
telephoneNo[1]=9201861321L;
telephoneNo[2]=9201661311L;
Customer custObj1 = new Customer();
System.out.println("Customer Id:"+
custObj1.getCustomerId());
long[] temp = custObj1.getTelephoneNo();

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 105 of 170

Infosys Limited

Assignments for OO programming using Java part1

System.out.println("Customer
Name:"+custObj1.getCustomerName());
System.out.println("Telephone Nos:"+ temp[0]+ " "+temp[1]+"
"+ temp[2]);
Notethatfortheobject,custObj2,
parameterizedconstructorisbeing
invoked

telephoneNo[0]=9201861331L;
telephoneNo[1]=9201861341L;
telephoneNo[2]=9201661321L;
Customer custObj2 = new Customer(telephoneNo, "James");
System.out.println("Customer Id:"+
custObj2.getCustomerId());
temp = custObj2.getTelephoneNo();
System.out.println("Customer
Name:"+custObj2.getCustomerName());
System.out.println("Telephone Nos:"+ temp[0]+ " "+temp[1]+"
"+ temp[2]);
}
}

Output:
CustomerId:1001
CustomerName:null
TelephoneNos:000
CustomerId:0
CustomerName:James
TelephoneNos:92018613319201861341 9201661321

Estimated time: 15 minutes


Summary of this assignment: In this assignment, you have learnt the implementation
of constructor overloading using a retail application scenario.

Assignment 65: Constructor Overloading Hands on practice


Objective: Given a class diagram for a use case representing a computational problem,
use method and constructor overloading techniques to solve the problem and test using
a set of values in an IDE and recognize the benefits of static polymorphism

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 106 of 170

Infosys Limited

Assignments for OO programming using Java part1

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,
When hits a specific hotkey generates tickets from a preset start point and end point
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
+getTicketAmount():int
+validateTravelPoints():boolean
+calcTicketAmt():int
The ticket amount is calculated by calcTicketAmt() and stored in ticketAmount by the
formula: (endpoint startPoint) * 10, and then return ticketAmount.
The preset endPoint and startPoint are 9 and 3 respectively.
Create an object of Ticket Class by the following statements: Ticket newTicketObj1=new Ticket();
Ticket newTicketObj2=new Ticket(10,1);
Ticket newTicketObj3=new Ticket(1,10);
At the end of each calculation, display the amount of money to be paid and observe the
changes.
Ensure a validation with validateTravelPoints() using the following criteria: endPoint and startPoint must be greater than 0
endPoint must always be greater than startPoint
Estimated time: 30 minutes
Summary of this assignment: In this assignment, you have learnt the implementation
of constructor overloading

Assignment 66: Relationships Demo


Objective: Observe the need for features in the retail application scenario to correlate
the application of relationships concept
ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 107 of 170

Infosys Limited

Assignments for OO programming using Java part1

Problem Description:
1. The retail shop has two types of customers, Regular and Privileged.
a. What are the properties common to all Customers?
b. What are the properties which are different for the two kinds of customers?
c. What is the relationship between
i.
Customer and Regular customer
ii.
Customer and Privileged customer?
d. How can this relationship be represented using class diagram?
Regularcustomersareentitledtogetsomediscountoneachpurchaseapartfromhavingallthepropertiesofa
customer.Ontheotherhand,privilegedcustomersholdmembershipcardPlatinum,GoldorSilverbasedon
whichtheyreceivegiftsoneachpurchase.Thisisinadditiontohavingallthepropertiesofacustomer.Thusin
thiscase,CustomeristhegeneralizedcaseandRegularandPrivilegedcustomerarethespecializedcasesof
Customer.Thisrelationshipisknownasisarelationshipandcanberepresentedusingclassdiagramasshown
below:

is-a relationship

2. The retail store management wants to keep track of the address of every customer so
as to allow for home delivery at a later point of time.
a. How many fields represent the address?
b. Do you think address qualifies to be a class?
c. What do you think is the relationship between Customer and Address?
d. How can this relationship be represented using class diagram?
Addresscanbeconsideredasaseparateclasssincethesameclassifrequiredcanbereusedatalaterpointof
time.Forexample,ifretailstoreneedstokeeptrackofitsemployeesaddress,thesameaddressclasscanbe
reused.TherelationshipbetweenCustomerclassandAddressclasswillbeHasArelationshipsinceevery
customerhasanaddress.Thisrelationshipcanberepresentedusingclassdiagramasshownbelow:

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 108 of 170

Infosys Limited

Assignments for OO programming using Java part1

3. Consider PurchaseBill and PrintDetails classes, the bill needs to be created in a


particular format. PrintDetails class contains methods which can be used to display the
bill in the required format.
a. What do you think is the relationship between PurchaseBill and PrintDetails
classes?
b. How can this relationship be represented using class diagram?
Asstated,PrintDetailsclasscontainsmethodswhichcanbeusedtodisplaythebillintherequiredformat.
HencetherelationshipbetweenPurchaseBillandPrintDetailsclassisusesarelationship.Thisrelationshipcan
berepresentedusingclassdiagramasshownbelow:

Estimated time: 20 minutes


Summary of this assignment: In this assignment, you have understood the need of
relationships and its representation using a retail application scenario

Assignment 67: Inheritance Demo


Objective: Given a class diagram for a use case representing a computational problem,
implement inheritance (single level, multilevel and hierarchical) to solve the problem,
trace the flow of the program between the base and derived classes and test using a
set of values in an IDE and recognize the benefits of inheritance
Problem Description: In the retail application, we have already seen that customers
are of two types Regular and Privileged. Regular customers are entitled for discount
on each purchase and Privileged customers hold membership cards Platinum, Gold or
Silver based on which they are entitled to get gifts on each purchase.
The class diagram presented to you as part of OO Concepts Part I Assignment 5 has
been modified to represent the inheritance relationship.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 109 of 170

Infosys Limited

Assignments for OO programming using Java part1

Note: Few instance variables and methods are not shown in the class diagram so as to
keep the code simple to understand.
Class diagram:
Customer
-customerId
-customerName

: int
: String

+setCustomerId(int)
+setCustomerName(String)
+getCustomerId()
+getCustomerName()

RegularCustomer
- discount
+setDiscount(float)
+getDiscount ()

: void
: void
: int
: String

PrivilegedCustomer

: float
: void
:float

- memCardType
: String
+setMemCardType(String)
: void
+getMemCardType()
:String

Code:
Execute the code using Eclipse IDE with the given inputs in the starter class, Retail and
observe the results.
class Customer{
private int customerId;
private String customerName;

NotethatbothRegularCustomer
andPrivilegedCustomerarehaving
Customerastheparentclass,hence
thisisanexampleofhierarchical
inheritance

public void setCustomerId(int customerId){


this.customerId=customerId;
}
public void setCustomerName(String customerName){
this.customerName=customerName;
}
public int getCustomerId(){
return customerId;

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 110 of 170

Infosys Limited

Assignments for OO programming using Java part1

}
public String getCustomerName(){
return customerName;
}

Notetheuseofextendskeyword
torealizeinheritanceinJava

}
class RegularCustomer extends Customer{
private float discount;
public void setDiscount(float discount){
this.discount=discount;
}
public float getDiscount(){
Notetheuseofextendskeyword
return discount;
torealizeinheritanceinJava
}
}
class PrivilegedCustomer extends Customer{
private String memCardType;
public void setMemCardType(String memCardType){
this.memCardType=memCardType;
}
public String getMemCardType(){
return memCardType;
}
}

Notehowchildclassobjectis
created

class Retail{
public static void main(String args[]){
RegularCustomer regObj=new RegularCustomer();
regObj.setCustomerId(1001);
regObj.setCustomerName("Kevin");
regObj.setDiscount(10.0f);
System.out.println("Regular Customer Details");
System.out.println("Customer Id:"
+regObj.getCustomerId());
System.out.println("Customer
Name:"+regObj.getCustomerName());
System.out.println("Discount:"+regObj.getDiscount());

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 111 of 170

Infosys Limited

Assignments for OO programming using Java part1

PrivilegedCustomer prvObj = new PrivilegedCustomer();


prvObj.setCustomerId(1002);
Notehowparentclassmethodsare
prvObj.setCustomerName("James");
invokedusingchildclassobjectreference
prvObj.setMemCardType("Gold");
System.out.println("Privileged Customer Details");
System.out.println("Customer
Id:"+prvObj.getCustomerId());
System.out.println("Customer
Name:"+prvObj.getCustomerName());
System.out.println("Membership Card
Type:"+prvObj.getMemCardType());
}
}
Output:
RegularCustomerDetails
CustomerId:1001
CustomerName:Kevin
Discount:10.0
PrivilegedCustomerDetails
CustomerId:1002
CustomerName:James
MembershipCardType:Gold

Howcantheinstancevariables
beinitializedalongwithobject
creation??

Instance variables can be initialized at object creation using constructors

Revised Code:
class Customer{
private int customerId;
private String customerName;
public Customer(int customerId, String customerName){
this.customerId=customerId;
this.customerName=customerName;
}
public void setCustomerId(int customerId){
this.customerId=customerId;
}

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 112 of 170

Infosys Limited

Assignments for OO programming using Java part1

public void setCustomerName(String customerName){


this.customerName=customerName;
}
public int getCustomerId(){
return customerId;
}
public String getCustomerName(){
return customerName;
}
}
class RegularCustomer extends Customer{
private float discount;

Notehowparameterizedconstructoris
writtenforRegularCustomer

public RegularCustomer(int customerId, String customerName, float


discount){
super(customerId,customerName);
Notehowsuper()invocationisusedto
this.discount=discount;
invokeparentclassconstructor
}
public void setDiscount(float discount){
this.discount=discount;
}
public float getDiscount(){
return discount;
}
}
class PrivilegedCustomer extends Customer{
private String memCardType;

Notehowparameterizedconstructoris
writtenforPrivilegedCustomer

public PrivilegedCustomer(int customerId, String customerName,


String memCardType){
Notethatwhensuper()invocationis
super(customerId,customerName);
used,itshouldbethefirststatementin
this.memCardType=memCardType;
thechildclassconstructor
}
public void setMemCardType(String memCardType){
this.memCardType=memCardType;
}

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 113 of 170

Infosys Limited

Assignments for OO programming using Java part1

public String getMemCardType(){


return memCardType;
}
}
class Retail{
public static void main(String args[]){
RegularCustomer regObj=new
RegularCustomer(1001,"Kevin",10.0f);
System.out.println("Regular Customer Details");
System.out.println("Customer Id:"
+regObj.getCustomerId());
System.out.println("Customer
Name:"+regObj.getCustomerName());
System.out.println("Discount:"+regObj.getDiscount());
PrivilegedCustomer prvObj = new
PrivilegedCustomer(1002,"James", "Gold");
System.out.println("Privileged Customer Details");
System.out.println("Customer
Id:"+prvObj.getCustomerId());
System.out.println("Customer
Name:"+prvObj.getCustomerName());
System.out.println("Membership Card
Type:"+prvObj.getMemCardType());
}
}

Output:
RegularCustomerDetails
CustomerId:1001
CustomerName:Kevin
Discount:10.0
PrivilegedCustomerDetails
CustomerId:1002
CustomerName:James
MembershipCardType:Gold

Estimated time: 30 minutes

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 114 of 170

Infosys Limited

Assignments for OO programming using Java part1

Summary of this assignment: In this assignment, you have understood


implementation of inheritance relationship and use of super() invocation to invoke
parent class constructor using a retail application scenario.

Assignment 68: Inheritance - Quiz


Objective: Revisit inheritance concepts through a quiz

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 115 of 170

Infosys Limited

Assignments for OO programming using Java part1

Q1. What is the output of the following code snippet?


class Base{
public Base(){
System.out.println("Base class constructor");
}
}
class Der extends Base{
public Der(){
System.out.println("Derived class constructor");
}
}
class Demo{
public static void main(String args[]){
Der derObj=new Der();
}
}

Q2. What is the output of the following code snippet?


class Base{
public int baseVar;
public int var;
public Base(int v){
baseVar=v;
System.out.println("Base class
parameterized
constructor");
}
}
class Der extends Base{
public int derVar;
public int var;
public Der(int v){
super(v);
derVar=v;
System.out.println("Derived class
parameterized constructor");
}
public void display(){
System.out.println("Base variable value="+baseVar);
System.out.println("Derived variable value="+derVar);

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 116 of 170

Infosys Limited

Assignments for OO programming using Java part1

}
public void useOfSuper(){
var=15;
var=20;
System.out.println("Base variable var=" +
super.var);
System.out.println("Derived variable var="+var);
}
}
class Demo{
public static void main(String args[]){
Der derObj=new Der(10);
derObj.display();
derObj.useOfSuper();
}
}

Q3. What is the output of the following code snippet?

class Base{
public int baseVar;
public Base(int v){
baseVar=v;
System.out.println("Base class parameterized constructor");
}
}
class Der extends Base{
public int derVar;
public Der(int v){
derVar=v;
System.out.println("Derived class parameterized
constructor");
}
public void display(){
System.out.println("Base variable value="+baseVar);
System.out.println("Derived variable value="+derVar);
}
}
class Demo{
public static void main(String args[]){

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 117 of 170

Infosys Limited

Assignments for OO programming using Java part1

Der derObj=new Der(10);


derObj.display();
}
}

Q4. Say true or false


a) Multilevel inheritance is not supported in Java
b) Inheritance can be done with the help of extends keyword in Java
c) In derived class constructors, super should be the first statement
d) All the private data members of the base class are directly accessible in
the derived class

ANSWERS
Q1.
Base class constructor
Derived class constructor
Q2.
Base class parameterized constructor
Derived class parameterized constructor
Base variable value=10
Derived variable value=10
Base variable var=0
Derived variable var=20
Q3.
Compilation Error: This is because, in the Base class a parameterized constructor has
been defined, but when the object of derived class is made, there is no explicit
invocation of the base class constructor and hence the system tries to invoke the default
constructor of Base class which is not available.
Q4.
a)False
b)True
c)True
d)False

Estimated time: 15 minutes


Summary of this assignment: In this assignment, you have revisited concepts of
inheritance through code snippets

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 118 of 170

Infosys Limited

Assignments for OO programming using Java part1

Assignment 69: Aggregation Demo


Objective: Given a class diagram for a use case representing a computational problem,
implement has-a and uses-a relationships to solve the problem and test using a set of
values in an IDE and recognize the benefits of the mentioned relationships
Problem Description: In the retail application, we have already seen that every
customer has an address. Address consists of address line, city, state and zipcode.
The class diagram presented to you as part of aggregation (has-a) example in OO
Concepts Part I Assignment 7 has been modified.
Note: Few instance variables and methods are not shown in the class diagram so as to
keep the code simple to understand. Similarly, regular and privileged customer classes
are also not shown here.
Class diagram:

Code:
Execute the code using Eclipse IDE with the given inputs in the starter class, Retail and
observe the results.
class Address {
private String
private String
private String
private String

addressLine;
city;
state;
zip;

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

NotehowAddressclassiswritten
likeanyotherclass

Version No: 1.2

Page 119 of 170

Infosys Limited

Assignments for OO programming using Java part1

public Address(String addressLine, String city, String state,


String zip){
this.addressLine=addressLine;
this.city=city;
this.state=state;
this.zip=zip;
}
public String getAddressLine() {
return addressLine;
}
public void setAddressLine(String addressLine) {
this.addressLine = addressLine;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 120 of 170

Infosys Limited

Assignments for OO programming using Java part1

}
class Customer{
private int customerId;
private Address address;
private static int counter=1000;
public Customer(Address address){
this.customerId=++counter;
this.address=address;
}
public int getCustomerId(){
return customerId;
}
public Address getAddress(){
return address;
}
}

Notehowaggregationrelationshipis
implemented

Notehowaddressreferenceis
returnedfromamethod

class Retail{
public static void main(String args[]){
Address add = new Address("No.333,Oak street",
"Strathfield", "New South Wales", "570018");
Whattypeofparameter
Customer custObj = new Customer(add);
passingtechniqueisused
here?
System.out.println("Customer Id:"+
custObj.getCustomerId());
//Check if address is correctly saved
Notehowaddressreferenceis
Address temp=custObj.getAddress();
passedtotheconstructorof
System.out.println("Address:");
Customerclass
System.out.println(temp.getAddressLine());
System.out.println(temp.getCity());
System.out.println(temp.getState());
Notehowaddressreferenceis
System.out.println(temp.getZip());
retrievedfromthecustomerclass
}
}

Output:
CustomerId:1001
Address:
No.333,Oakstreet
Strathfield
NewSouthWales
570018

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 121 of 170

Infosys Limited

Assignments for OO programming using Java part1

In this example, Address reference is passed to the constructor of Customer class. Since it is a
reference of an object that is passed, the parameter passing technique used is pass by referene.

Estimated time: 30 minutes


Summary of this assignment: In this assignment, you have understood the
implementation of aggregation relationship using a retail application scenario.

Assignment 70: Association Demo


Objective: Given a class diagram for a use case representing a computational problem,
implement has-a and uses-a relationships to solve the problem and test using a set of
values in an IDE and recognize the benefits of the mentioned relationships
Problem Description: In the retail application, we have already seen that purchase bill
has to be created in a particular format.
The class diagram presented to you as part of association (uses-a) example in OO
Concepts Part I Assignment 7 has been modified to include instance variables and
methods
Note: Few instance variables and methods are not shown in the class diagram so as to
keep the code simple to understand.

Class diagram:
PurchaseBill
-billId: int
-billAmount:double
-counter: int->static
+PurchaseBill(double)
+getBillId(): int
+getBillAmount():double
+calculateBill(String,int): void
+displayBill(): void

Code:

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 122 of 170

Infosys Limited

Assignments for OO programming using Java part1

Execute the code using Eclipse IDE with the given inputs in the starter class, Retail and
observe the results. Few changes are made to PurchaseBill class, the changes are
highlighted in the code below:
class PrintDetails{
public void printHeader(char c){
for(int counter=0;counter<70;counter++){
System.out.print(c);
}
}
public void printHeader(char c, int no){
for(int counter=0;counter<no;counter++){
System.out.print(c);
}
}
public void printHeader(String s){
System.out.println(s);
}
}
class PurchaseBill{
Notethatbillidisautogenerated
private int billId;
startingfrom5001
private double billAmount;
private static int counter=5000;
public PurchaseBill(double billAmount){
Notethatconstructorfor
this.billAmount=billAmount;
PurchaseBillclassisintroduced
billId=++counter;
}
public int getBillId(){
Notethatdiscountcalculationlogic
return billId;
isremovedsincewehaveseenthat
}
discountisapplicableonlyfor
public double getBillAmount(){
regularcustomers.Wewillrevisit
return billAmount;
thismethodafterlearningfewmore
}
concepts
public void calculateBill(String modeOfPayment,int
processingCharge){
if(modeOfPayment.equalsIgnoreCase("Credit")){
NotehowPrintDetailsclassisused
billAmount=billAmount +
indisplayBill()methodof
(billAmount*processingCharge/100.00);
PurchaseBillclass.Thismethodis
}
introducedtodisplaythebillinthe
}
requiredformat.
public void displayBill(){

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 123 of 170

Infosys Limited

Assignments for OO programming using Java part1

PrintDetails printObj=new PrintDetails();


printObj.printHeader('-',80);
System.out.println("");
printObj.printHeader("
Easy Shop Retail
Store Bill");
printObj.printHeader('-',80);
System.out.println("");
System.out.println("Bill Id
:"+ billId);
System.out.println("Final bill amount to be paid
:Rs."+billAmount);
System.out.println("");
printObj.printHeader('-',80);
System.out.println("");
printObj.printHeader("
Thank You!!!
Visit Again");
printObj.printHeader('-',80);
}
}
class Retail{
public static void main(String args[]){
String modeOfPayment=args[0];
int processingCharge=Integer.parseInt(args[1]);
PurchaseBill purObj=new PurchaseBill(1055.00f);
purObj.calculateBill(modeOfPayment,processingCharge);
purObj.displayBill();
}
}

Execute the above code using the following values for command line arguments
Case 1:
Command line arguments to be passed Cash and 0
Case 2:
Command line arguments to be passed Credit and 5

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 124 of 170

Infosys Limited
Case1Output:

Assignments for OO programming using Java part1

EasyShopRetailStoreBill

BillId

Finalbillamounttobepaid

:5001
:Rs.1055.0

ThankYou!!!VisitAgain

Case2Output:

EasyShopRetailStoreBill

BillId

Finalbillamounttobepaid

:5001
:Rs.1107.75

ThankYou!!!VisitAgain

Estimated time: 20 minutes


Summary of this assignment: In this assignment, you have understood the
implementation of association relationship using a retail application scenario.

Assignment 71: Method Overriding Observations from Retail


application
Objective: Observe the need for features in the retail application scenario to correlate
the application of object oriented concepts
Problem Description: The Retail Store wants to display the customer information. The
information depends on the type of customer. The developer wants to write a single
method that would display all the customer related information.
Observations:

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 125 of 170

Infosys Limited

Assignments for OO programming using Java part1

We can have a displayCustomerInformation() method for displaying customer


details
Wherecanweimplementthis
method?

If this method is placed in Customer class, it can access only the instance
variables of Customer class
If this method is placed in child classes, it cannot access the instance variables
of Customer class since all the instance variables of Customer class are private
in nature
We need to know how to define the method in both the parent class and child
class(es) and invoke it based on the type of Customer

Estimated time: 10 minutes


Summary of this assignment: In this assignment, you have understood the need for
method overriding in the retail application scenario.

Assignment 72 Method Overriding - Demo


Objective: Implement method overriding to solve the problem and test using a set of
values in an IDE and recognize the benefits of dynamic polymorphism
Problem Description: The Retail Store wants to display the customer information. The
information depends on the type of customer. The developer wants to write a single
method that would display all the customer related information.
Code: Execute the code using Eclipse IDE with the given inputs and observe the
results.
class Customer{
private int customerId;
private static int counter=1000;
Notethebaseclassversionof
public Customer(){
displayCustomerInformation()
customerId=++counter;
}
public void displayCustomerInformation(){
System.out.println("Customer Id:"+
customerId);
}
}

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 126 of 170

Infosys Limited

Assignments for OO programming using Java part1

class RegularCustomer extends Customer{


private float discount;
public RegularCustomer(float discount){
Notethemethodoverridingof
super();
displayCustomerInformation()in
this.discount=discount;
thechildclass
}
public void displayCustomerInformation(){
System.out.println("Discount:"+discount);
}
}
class PrivilegedCustomer extends Customer{
private String memCardType;
public PrivilegedCustomer (String cardType){
super();
this.memCardType=cardType;
Notethemethodoverridingof
}
displayCustomerInformation()in
public void displayCustomerInformation(){
thechildclass
System.out.println("Membership Card Type:"+memCardType);
}
}
class Retail{
public static void main(String args[]){
RegularCustomer regObj=new RegularCustomer(20.0f);
System.out.println("Regular Customer Information");
regObj.displayCustomerInformation();
PrivilegedCustomer prvObj= new PrivilegedCustomer("Gold");
System.out.println("Privileged Customer Information");
prvObj.displayCustomerInformation();
}
}

Output:
WhyisitthatthecustomerIdis
notdisplayedforbothRegular
&Privilegedcustomer?

RegularCustomerDetails
Discount:20.0
PrivilegedCustomerDetails
MembershipCardType:Gold
ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 127 of 170

Infosys Limited

Assignments for OO programming using Java part1

This is because displayCustomerInformation() method of Customer class is not invoked


To invoke the overridden method of parent class super keyword has to be used

Revised code:
class Customer{
private int customerId;
private static int counter=1000;
public Customer(){
customerId=++counter;
}
public void displayCustomerInformation(){
System.out.println("Customer Id:"+ customerId);
}
}
class RegularCustomer extends Customer{
private float discount;
public RegularCustomer(float discount){
super();
Whensuperisusedtoinvokethe
this.discount=discount;
overriddenmethodofparentclass,it
}
neednotbethefirststatementinthe
public void displayCustomerInformation(){
childclassmethodunliketheuseof
super.displayCustomerInformation();
super()forconstructorinvocation
System.out.println("Discount:"+discount);
}
}
class PrivilegedCustomer extends Customer{
private String memCardType;
public PrivilegedCustomer (String cardType){
super();
this.memCardType=cardType;
}
public void displayCustomerInformation(){
super.displayCustomerInformation();
System.out.println("Membership Card Type:"+memCardType);
}
}
Notehow
displayCustomerInformation()
methodofCustomerclassisinvoked
using superkeyword
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Version No: 1.2
Page 128 of 170

Infosys Limited

Assignments for OO programming using Java part1

class Retail{
public static void main(String args[]){
RegularCustomer regObj=new RegularCustomer(20.0f);
System.out.println("Regular Customer Information");
regObj.displayCustomerInformation();
PrivilegedCustomer prvObj= new PrivilegedCustomer("Gold");
System.out.println("Privileged Customer Information");
prvObj.displayCustomerInformation();
}
}

Estimated time: 20 minutes


Summary of this assignment: In this assignment, you have understood the
implementation of dynamic polymorphism using a retail application scenario.

Assignment 73: Dynamic polymorphism Observations from


Retail Application
Objective: Observe the need for features in the retail application scenario to correlate
the application of object oriented concepts
Problem Description:
The Retail store now wants to display the information of the customer based on the kind
of customer.
Observations :
Call the appropriate displayCustomerInformation() method for displaying the
details based on the type of customer which is decided at run-time(during
payment of bill)
We need to understand
o Dynamic polymorphism where the base reference can be made to point to
an object of derived class
Estimated time: 10 minutes
Summary of this assignment: In this assignment, you have understood the need for
dynamic polymorphism in the retail application scenario.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 129 of 170

Infosys Limited

Assignments for OO programming using Java part1

Assignment 74: Dynamic polymorphism A Simple Demo


Objective: Use hybrid references (base class reference=derived class object) in
programs and implement the benefits of dynamic polymorphism
Problem Description:
Consider a gaming company developing a library for shapes. Consider few classes from
the library to understand dynamic polymorphism.The class diagram is given below:
Code :
Execute the code using Eclipse IDE with the given inputs and observe the results.
class Shape {
public double area(){
System.out.println("Area method of Shape class");
return 0.0;
}
public double perimeter(){
System.out.println("Perimeter method of Shape class");
return 0.0;
Notethemethodsarea()and
}
perimeter()definedinShapeclass
}
class Rectangle extends Shape{
private int length;
private int breadth;
public Rectangle(int length, int breadth){
this.length=length;
Notethemethodsarea()and
this.breadth=breadth;
perimeter()areredefinedin
}
Rectangleclass
public double area(){
System.out.println("Area method of Rectangle class");
double area=length*breadth;
return area;
}
public double perimeter(){
System.out.println("Perimeter method of Rectangle class");
double perimeter=2*(length+breadth);
return perimeter;
}
}

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 130 of 170

Infosys Limited

Assignments for OO programming using Java part1

class Square extends Shape{


private int length;
Notethemethodsarea()and
public Square(int length){
perimeter()areredefinedinSquare
this.length=length;
class
}
public double area(){
System.out.println("Area method of Square class");
double area=length*length;
return area;
}
public double perimeter(){
System.out.println("Perimeter method of Square class");
double perimeter=4*length;
return perimeter;
NotehowtheShapeobjectismade
topointtoRectangleorSquareclass
}
objectdependingontheinput
}
providedinthecommandline
class Demo{
public static void main(String args[]){
Shape shapeObj=null;
if(args[0].equals("Rectangle")){
shapeObj =new Rectangle(10,20);
System.out.println("Area of given
rectangle:"+shapeObj.area());
}
else if(args[0].equals("Square")){
shapeObj =new Square(10);
System.out.println("Area of given
Square:"+shapeObj.area());
}
}
}

Execute the above code using the following values as command line arguments
Output: Use the following values and observe the output in the IDE
Case-1: Command line argument to be passed - Rectangle
Case-2: Command line argument to be passed Square

Case1Output:
AreamethodofRectangleclass
Areaofgivenrectangle:200.0
ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 131 of 170

Infosys Limited

Assignments for OO programming using Java part1

Case2Output:
AreamethodofSquareclass
AreaofgivenSquare:100.0

Note that the area() and perimeter() methods of Shape class is overridden in the Rectangle and
Squareclasses.Also,notethattheversionofthearea()andperimeter()beingcalleddependsonthe
kindofshape
Estimated time: 20 minutes
Summary of this assignment: In this assignment, you have learnt the implementation
of dynamic polymorphism using a real world scenario.

Assignment 75: Dynamic polymorphism - Demo


Objective: Use hybrid references (base class reference=derived class object) in
programs and implement the benefits of dynamic polymorphism
Problem Description:
The Retail store now wants to display the information of the customer based on the kind
of customer.
Code :
Execute the code using Eclipse IDE with the given inputs and observe the results.
class Customer{
private int customerId;
private String customerName;
public Customer(int customerId,String customerName){
this.customerId=customerId;
this.customerName=customerName;
}
public void displayCustomerInformation(){
System.out.println("Customer Id :"+customerId);
System.out.println("Customer Name :"+customerName);
}

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 132 of 170

Infosys Limited

Assignments for OO programming using Java part1

}
class RegularCustomer extends Customer{
private float discount;
public RegularCustomer(int customerId,String customerName, float
discount){
super(customerId,customerName);
this.discount=discount;
}
public void displayCustomerInformation(){
super. displayCustomerInformation();
System.out.println("Discount :"+discount);
}
}
class PrivilegedCustomer extends Customer{
private String memCardType;
public PrivilegedCustomer(int customerId,String customerName,
String memCardType){
super(customerId,customerName);
this.memCardType=memCardType;
}
public void displayCustomerInformation(){
super. displayCustomerInformation();
System.out.println("Membership card type :"+memCardType);
}
Notehowthebaseclassreferenceis
}
madetopointtoachildclassobject
class Retail{
public static void main(String args[]){
Customer custObj=null;
if(args[0].equalsIgnoreCase("Regular")){
custObj=new RegularCustomer(1001,"Jack",12.3f);
}
else if(args[0].equalsIgnoreCase("Privileged")){
custObj=new PrivilegedCustomer(2001,"Jane","Gold");
}
custObj.displayCustomerInformation();
}
Notethecallingoftheappropriate
methodbasedontheobject
}

Execute the above revised code using the following values as command line arguments
Output: Use the following values and observe the output in the IDE

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 133 of 170

Infosys Limited

Assignments for OO programming using Java part1

Case-1: Command line argument to be passed - Regular


Case-2: Command line argument to be passed Privileged
Case1Output:
CustomerId:1001
CustomerName:Jack
Discount:12.3

Case2Output:
CustomerId:2001
CustomerName:Jane
Membershipcardtype:Gold

NotethatthedisplayCustomerInformation()methodofCustomerclassoverriddenintheRegularand
Privileged Customer classes .Also, note that the version of the displayCustomerInformation() being
calleddependsonthekindofcustomer

Estimated time: 20 minutes


Summary of this assignment: In this assignment, you have learnt the implementation
of dynamic polymorphism.

Assignment 76: abstract keyword Observations from Retail


application
Objective: Use Abstract keyword to create abstract classes through methods ,
implement overriding and dynamic polymorphism
Problem Description:
The Retail Store application consists of the Customer, PrivilegedCustomer and
RegularCustomer classes. The review team felt that the Customer class does not
display much functionality, however provides a placeholder for the generic attributes of
Customers. They want to fine tune this structure of classes.
Observations:
We need the Customer class to provide the structure but allow the child classes
to override or redefine the specific functionalities
Howcanthisbedone?

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 134 of 170

Infosys Limited

Assignments for OO programming using Java part1

The abstract keyword can be used with classes to provide the prototype of the
methods, however leave the implementation to the child classes.

Estimated time: 10 minutes


Summary of this assignment: In this assignment, you have understood the need for
the abstract keyword in the retail application scenario.

Assignment 77: abstract keyword A Simple Demo


Objective: Use Abstract keyword to create abstract classes through methods ,
implement overriding and dynamic polymorphism
Problem Description: Consider a gaming company developing a library for shapes.
Consider few classes written earlier. The code and design need to be fine tuned. The
Shape class cannot define the formula for area() or the perimeter().
Code: Execute the code using Eclipse IDE with the given inputs and observe the
results.
NotehowtheShapeclassis
abstract class Shape {
declaredabstract
abstract public double area();
abstract public double perimeter();
Notehowthemethodsinthe
}
Shapeclassaredeclared
class Rectangle extends Shape{
abstract
private int length;
private int breadth;
public Rectangle(int length, int breadth){
this.length=length;
this.breadth=breadth;
}
public double area(){
System.out.println("Area method of Rectangle class");
double area=length*breadth;
return area;
}
public double perimeter(){
System.out.println("Perimeter method of Rectangle class");
double perimeter=2*(length+breadth);

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 135 of 170

Infosys Limited

Assignments for OO programming using Java part1

return perimeter;
}
}
class Square extends Shape{
private int length;
public Square(int length){
this.length=length;
}
public double area(){
System.out.println("Area method of Square class");
double area=length*length;
return area;
}
public double perimeter(){
System.out.println("Perimeter method of Square class");
double perimeter=4*length;
return perimeter;
}
}
class Demo{
public static void main(String args[]){
Shape shapeObj=null;
if(args[0].equals("Rectangle")){
shapeObj =new Rectangle(10,20);
System.out.println("Area of given
rectangle:"+shapeObj.area());
}
else if(args[0].equals("Square")){
shapeObj =new Square(10);
System.out.println("Area of given
Square:"+shapeObj.area());
}
}
}

Estimated time: 20 minutes


Summary of this assignment: In this assignment, you have understood the
implementation of dynamic polymorphism with the help of abstract keyword

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 136 of 170

Infosys Limited

Assignments for OO programming using Java part1

Assignment 78: abstract keyword Hands-on


Objective: Use Abstract keyword to create abstract classes through methods ,
implement overriding and dynamic polymorphism
Problem Description: The Retail Store application consists of the Customer
,PrivilegedCustomer and RegularCustomer classes. The review team felt that the
Customer class does not display much functionality, however provides a placeholder for
the generic attributes of Customers. They want to fine tune this structure.
Modify the code given as part of Assignment 75 using abstract keyword and execute it
in Eclipse.
Estimated time: 20 minutes
Summary of this assignment: In this assignment, you have understood the
implementation of dynamic polymorphism with the help of abstract keyword

Assignment 79: Interfaces Observations from Retail


application
Objective: Observe the need for features in the retail application scenario to correlate
the application of object oriented concepts
Problem Description: In the retail application scenario, the tax needs to be computed
based on the bill amount.

Howcanthisbedone?
Observations:
We need a means
To declare a constant percentage of VAT
To have a class which can be used by any other class that needs to include VAT
in the calculation
Estimated time: 10 minutes
Summary: In this assignment, you have understood the need for interfaces

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 137 of 170

Infosys Limited

Assignments for OO programming using Java part1

Assignment 80: Interfaces - Demo


Objective: Use the concept of interface and their properties
Problem Description: In the retail application scenario, the tax needs to be computed
based on the bill amount.
Code :
interface Tax{
float TAX = 4.0f;
public float computeTax();
}

NotehowtheTaxinterfaceis
defined

NotehowthePurchaseBillclass
class PurchaseBill implements Tax{
implementstheTaxinterface
float billAmount;
public PurchaseBill(float billAmount){
this.billAmount=billAmount;
}
public float computeTax(){
float taxAmount=0.0f;
taxAmount=(billAmount*TAX)/100.00f;
return taxAmount;
}
public void calculateBill(String modeOfPayment,int
processingCharge){
//Assume that the earlier written logic for calculation of
bill amount is available here
billAmount=billAmount + computeTax();
}
}
NotehowthetaxisincludedinthebillAmountby
invokingthecomputeTax()
class Retail{
public static void main(String args[]){
String modeOfPayment=args[0];
int processingCharge=Integer.parseInt(args[1]);
PurchaseBill purObj=new PurchaseBill(1055.00f);
purObj.calculateBill(modeOfPayment,processingCharge);
}
}

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 138 of 170

Infosys Limited

Assignments for OO programming using Java part1

Estimated time: 10 minutes


Summary: In this assignment, you have learnt to write a java program using interfaces

Assignment 81: Packages Observations from Retail


Application
Objective: Observe the need for features in the retail application scenario to correlate
the application of object oriented concepts
Problem Description: In the Retail Application, assume that the code has been written
by development teams distributed across various development centers. When the code
is integrated, class name clashes may occur if two or more programmers have used the
same name for their classes. Also, the access levels of the members of each individual
class by other classes need to be defined by each programmer.
Howcanthisbeachieved?

Observations:
We need a means
To organize the classes in a logical way
To provide access level to members of a class based on access requirement
Estimated time: 10 minutes
Summary: You have understood the need for packages

Assignment 82: Packages - Demo


Objective: Given a set of programs, be able to arrange them into packages and
recognize the benefits of using 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
Code:
Creation of a Package

Notehowthepackageiscreatedusingpackage
package addition;
statement
public class AddTwo{
private int sum;
public void calSum(int varOne,int varTwo){
sum=varOne+varTwo;

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 139 of 170

Infosys Limited

Assignments for OO programming using Java part1

System.out.println("Sum= "+sum);
}
}

Using fully qualified name


package calculation;
class PackEx{
public static void main(String args[]){
addition.AddTwo obj=new addition.AddTwo();
obj.calSum(23,46);
}
NotehowanobjectofAddTwoclassinaddition
}
packageiscreatedherebyaccessingtheclass
Import package and use class name directly
usingfullyqualifiedname
package calculation;
import addition.AddTwo;
class PackEx{
public static void main(String args[]){
AddTwo obj=new AddTwo();
obj.calSum(23,46);
}
Notehowaclassisimportedusingimport
}
statementandlateraccessedinthemain()
method

Estimated time: 10 minutes


Summary: You have learnt to create user defined packages and access them.

Assignment 83: A System Engineers story continued


Tom, the project managers, team which included Roy has come up with the first version
of the retail application.
1.
2.
3.
4.
5.
6.
7.

Do you observe clear separation of functionality?


Do you observe hierarchy in the system?
Do you observe smaller sub-systems?
How many lines of code do you think is written for the entire system?
How many classes have been identified?
How have you addressed the complexity of the code?
What are the advantages of following OO approach?

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 140 of 170

Infosys Limited

Assignments for OO programming using Java part1

Roy had a good experience developing this application using object orientation. He has
realized the benefits of using this approach and is confident of taking more projects in
this area. However, he feels the code can be fine-tuned and cleaned. We would focus
on this in the next section.

Assignment 84: Code Optimization - Observations from a


business application
Objective: Given an application, identify the need for code tuning and optimization
techniques
Problem Description 1: Explore the internet application icicbank.com
Answer the following questions:
1.
2.
3.
4.

What is the availability requirement of the application?


How many users do you think access Sparsh on a daily basis?
Should the application be user friendly?
Should the application load quickly?

Assignment 85: Source Code tuning techniques Demo 1


Objective: Given a set of source code and code optimization techniques and set of best
practices, identify and be aware of optimized code.
Problem Description: The Retail Store wants to assign default tax amount on the item
price for all the it ems in the store as per the item category
Business Rules:
Howwillyou
Valid values of item categories are A, B, C and D
implementthis?
Tax amount is a non-integral value
Code :
char itemCategory[]=new char[100];
double itemPriceTax[]=new double[100];
int loopIndex;
for (loopIndex =1; loopIndex < 100; loopIndex ++){
switch (itemCategory[loopIndex]){
case 'A' : itemPriceTax[loopIndex] = 8000;
break;
case 'B' : itemPriceTax[loopIndex] = 12000;
break;

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 141 of 170

Infosys Limited

Assignments for OO programming using Java part1

case 'C' : itemPriceTax[loopIndex] = 10000;


break;
case 'D' : itemPriceTax[loopIndex] = 14000;
break;
}

itemCategoryarraycontainstheitemcategoriesforthe100itemsand
itemPriceTaxarraywouldbeinitializedtothetaxvalues

Revised code:
char itemCategory[]=new char[100];
double itemPriceTax[]=new double[100];
int loopIndex;
for (loopIndex =1; loopIndex < 100; loopIndex ++){
switch (itemCategory[loopIndex]){
case 'A' : itemPriceTax[loopIndex] = 8000.0;
break;
case 'B' : itemPriceTax[loopIndex] = 12000.0;
break;
case 'C' : itemPriceTax[loopIndex] = 10000.0;
break;
case 'D' : itemPriceTax[loopIndex] = 14000.0;
break;
Usingfloatingpointconstantshelps!!!
}
}

Observations:
Type conversions though done by the compiler are a costly overhead which can be
avoided where ever possible, by the programmers.
Estimated time: 10 minutes
Summary of this assignment: In this assignment, you have learnt the code
optimization technique Use constants of correct type.

Assignment 85: Source Code tuning techniques Demo 2


Objective: Given a set of source code and code optimization techniques and set of best
practices, identify and be aware of optimized code.
Problem Description:
In the Retail Store most items belong to category D followed by B then by C and
lastly A
Business Rules:
Howwillyou
implementthis?
ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 142 of 170

Infosys Limited

Assignments for OO programming using Java part1

Valid values of item categories are A, B, C and D


Tax amount is a non-integral value

Code :
char itemCategory[]=new char[100];
double itemPriceTax[]=new double[100];
int loopIndex;
for (loopIndex=1; loopIndex < 100; loopIndex++){
switch (itemCategory[loopIndex]){
case 'A' : itemPriceTax[loopIndex] = 8000.0;
break;
case 'B' : itemPriceTax[loopIndex] = 12000.0;
break;
case 'C' : itemPriceTax[loopIndex] = 10000.0;
break;
case 'D' : itemPriceTax[loopIndex] = 14000.0;
break;
}
For every item of category D
}
tax calculation, 3 extra
comparisons have to be made
toreachthecasestatement

Revised code:
char itemCategory[]=new char[100];
double itemPriceTax[]=new double[100];
int loopIndex;
for (loopIndex=1; loopIndex < 100; loopIndex++){
switch (itemCategory[loopIndex]){
case 'D' : itemPriceTax[loopIndex] = 14000.0;
break;
case 'B' : itemPriceTax[loopIndex] = 12000.0;
break;
case 'C' : itemPriceTax[loopIndex] = 10000.0;
break;
case 'A' : itemPriceTax[loopIndex] = 8000.0;
break;
Thecasestatementshavebeen
}
ordered by frequency reducing
thenumberofcomparisons
}

Observations:
ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 143 of 170

Infosys Limited

Assignments for OO programming using Java part1

Comparisons are costly operations which take up the processor time. Tweaking code to
reduce number of comparisons helps in optimization of code.
Estimated time: 10 minutes
Summary of this assignment: In this assignment, you have learnt the code
optimization technique Order case statements by frequency.

Assignment 85: Source Code tuning techniques Demo 3


Objective: Given a set of source code and code optimization techniques and set of best
practices, identify and be aware of optimized code.
Problem Description:
The Retail Store administrator wants to identify the item with maximum price and the
item with minimum price in the store
Business Rules:
Howwillyou
implementthis?
Item price is stored in an array of appropriate type

Code:
double itemPrice[] = new double[100];
int loopIndex1,loopIndex2;
double MAX = itemPrice[0], MIN = itemPrice[0] ;
for (loopIndex1=1;loopIndex1<100;loopIndex1++){
if(itemPrice[loopIndex1] > MAX)
MAX = itemPrice[loopIndex1];
}
for (loopIndex2=1;loopIndex2<100;loopIndex2++){
if(itemPrice[loopIndex1] < MIN)
MIN = itemPrice[loopIndex1];
}
Aboveloopswillhave2*100loopchecks

Revised code:
double itemPrice[] = new double[100];
int loopIndex1;
double MAX = itemPrice[0], MIN = itemPrice[0] ;
for (loopIndex1=1;loopIndex1<100;loopIndex1++){
if(itemPrice[loopIndex1] > MAX)
MAX = itemPrice[loopIndex1];

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 144 of 170

Infosys Limited

Assignments for OO programming using Java part1

else if(itemPrice[loopIndex1] < MIN)


MIN = itemPrice[loopIndex1];
}

Observations:
Jamming of loops can be applied to other similar examples like finding the maximum
and minimum, from a given set of elements, in one loop. In the above example, we have
highlighted the fact that boundary checks in a loop are expensive.
Estimated time: 10 minutes
Summary of this assignment: In this assignment, you have learnt the code
optimization technique Jamming of loops.

Assignment 85: Source Code tuning techniques Demo 4


Objective: Given a set of source code and code optimization techniques and set of best
practices, identify and be aware of optimized code.
Problem Description:
The Retail Store administrator wants to give some flat 25% discount on base price of all
the items in the month of December as year ending stock clearance
Business Rules:
Assume that if month is December, a variable used in the program
is set to D
Howwillyou
implementthis?

Code :
double itemPrice[] = new double[100];
int itemFlatDiscount[] = new int[100];
int loopIndex1;
char currentMonth;
for (loopIndex1=0;loopIndex1<100;loopIndex1++){
if( 'D' == currentMonth )
...
}

Revised code:
double itemPrice[] = new double[100];
int itemFlatDiscount[] = new int[100];
int loopIndex1;
char currentMonth;
if( 'D' == currentMonth ){
for (loopIndex1=0;loopIndex1<100;loopIndex1++){

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 145 of 170

Infosys Limited

Assignments for OO programming using Java part1

...
}
}

Observations:
Unswitch loops that contain if tests, as the results of these tests do not change inside
the loop.
Estimated time: 10 minutes
Summary of this assignment: In this assignment, you have learnt the code
optimization technique Un-switching of loops.

Assignment 85: Source Code tuning techniques Demo 5


Objective: Given a set of source code and code optimization techniques and set of best
practices, identify and be aware of optimized code.
Problem Description:
The Retail Store wants to calculate the salary amount for the employees working with
the retail store
Business Rules:
There are 1000 employees working in the store
The salary will be calculated based on
Howwillyou
implementthis?
Basic Salary
HRA
City Allowance

Code:
int loopIndex, max=1000;
float salary[] = new float[1000];
float basic=6500.0f,hra=1500.0f,cityAllowances=500.0f;
for (loopIndex = 0; loopIndex<= max-1;loopIndex++){
salary[loopIndex] =basic + hra + cityAllowances;
}
These computations are done
every time the loop runs
Revised code:
consumingtheCPUtime
int loopIndex, max=1000;
float salary[] = new float[1000];
Float grossSalary;
float basic=6500.0f,hra=1500.0f,cityAllowances=500.0f;
grossSalary = basic + hra + cityAllowances;
for (loopIndex = 0; loopIndex<= max-1;loopIndex++){
These computations are done
onlyoncesavingtheCPUtime
ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 146 of 170

Infosys Limited

Assignments for OO programming using Java part1

salary[loopIndex] = grossSalary;
}

Observations:
The work performed inside loops should be minimum
Estimated time: 10 minutes
Summary of this assignment: In this assignment, you have learnt the code
optimization technique Minimize work performed inside Loops.

Assignment 85: Source Code tuning techniques Demo 6


Objective: Given a set of source code and code optimization techniques and set of best
practices, identify and be aware of optimized code.
Problem Description:
The designer of Retail Store automation system want to redesign the employee dataset
with one 2D array instead of two separate 1D array which maintains the employee ids
and salary, and print the updated value from this 2D array
The Retail Store also wants to give a salary hike of flat $5000 to each employee
Business Rules:
There are 1000 employees working in the store
The salary will be calculated based on
Howwillyou
Basic Salary
implementthis?
HRA
City Allowance

Code :
float empDetails[][] = new float[1000][2];
float salary[] = new float[1000];
int empID[] = new int[1000];
float empDetails[][] = new float[1000][2];
float salary[] = new float[1000];
int empId[] = new int[1000];
int loopIndex1, loopIndex2;
for (loopIndex1=0;loopIndex1<1000;loopIndex1++){
for (loopIndex2=0;loopIndex2<2;loopIndex2++){
empDetails[loopIndex1][0] = empId[loopIndex1];

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 147 of 170

Infosys Limited

Assignments for OO programming using Java part1

empDetails[loopIndex1][1]

salary[loopIndex1]+

5000.0f;
System.out.println("Details:"+empDetails[loopIndex1][loopIndex2])
;
}
The array reference has a
}
formula which is repeated for

Revised code:

everyrunoftheloop
float empDetails[][] = new float[1000][2];
float salary[] = new float[1000];
int empId[] = new int[1000];
int loopIndex1,loopIndex2;
for (loopIndex1=0;loopIndex1<1000;loopIndex1++){
empDetails[loopIndex1][0] = empId[loopIndex1];
empDetails[loopIndex1][1] = salary[loopIndex1]+5000.0f;
for (loopIndex2=0;loopIndex2<2;loopIndex2++){

System.out.println("Details:"+empDetails[loopIndex1][loopIndex2])
;
}
}

Observations:
The array references should be minimum within a loop
Estimated time: 10 minutes
The array reference has been
Summary of this assignment: In this assignment, reduced
you have learnt the code

optimization technique Minimize array references.

Assignment 85: Source Code tuning techniques Demo 7


Objective: Given a set of source code and code optimization techniques and set of best
practices, identify and be aware of optimized code.
Problem Description:
The Retail Store wants to identify whether there were any transactions in the past with a
bill amount more than $50000
Business Rules:
The store maintains only 100 transactions values at most
Each transaction is identified by a transaction Id
The bill amount is maintained for each transaction
Note: The 2D array structure holds:
Howwillyou
implementthis?
ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 148 of 170

Infosys Limited

Assignments for OO programming using Java part1

Transaction Id(1st Column)


Transaction Amount (2nd Column)

Code :
double transactionDetails[][] = new double[100][2];
int loopIndex1;
char isAvailable = 'N';
for (loopIndex1=0;loopIndex1<100;loopIndex1++){
if (transactionDetails[loopIndex1][1] >= 50000) {
isAvailable = 'Y';
The store want to identify presence of at
}
leastoneTransactionwithvalue>50000
}
everyrunoftheloop

Revised code:
double transactionDetails[][] = new double[100][2];
int loopIndex1;
char isAvailable = 'N';
for (loopIndex1=0;loopIndex1<100;loopIndex1++){
if (transactionDetails[loopIndex1][1] >= 50000){
isAvailable = 'Y';
break;
}
Thestorewanttoidentifypresenceofatleast
}
oneTransactionwithvalue>50000
everyrunoftheloop

Observations:
Stop testing when the result is known
Estimated time: 10 minutes
Summary of this assignment: In this assignment, you have learnt the code
optimization technique Stop testing when the result is known.

Assignment 86: Clean Code Hands on Practice


Objective: Given a set of source code identify and practice techniques for writing clean
code
Problem Description: Consider the requirements for validation of email id field in a
web application.
Email id can have only numbers 0-9 and chars A-z and a-z, . should come only after
@. Minimum one and maximum two . are allowed after the @ as part of the email id.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 149 of 170

Infosys Limited

Assignments for OO programming using Java part1

Presence of @ and . are mandatory. This is to be written in a validate method inside


the customer class.
Concepts revisited: Control structures, classes, objects, methods and method calling
and usage of String class as a data structure
Consider the code written by Richard for this purpose:
Richards code :
class Customer{
private String emailId;
public boolean validateEmailId(String string)
{
boolean flag=true;
int startIndex=0,lastIndex=0,counter=0,i,j;
for(i=0;i<string.length();i++){
if((string.charAt(i)>='a' &&
string.charAt(i)<='z')||(string.charAt(i)>='A' &&
string.charAt(i)<='Z')||(string.charAt(i)>='0' &&
string.charAt(i)<='9')||(string.charAt(i)=='@')){
flag=true;
}
if(flag==false){
System.out.println("not an allowed character");
break;
}
else if(flag==true){
if(string.charAt(0)>='0' && string.charAt(0)<='9'){
flag=false;
System.out.println("not a digit");
break;
}
else{
for(j=0;j<string.length() &&
string.charAt(j)!='@';j++,lastIndex++){
if(string.charAt(j)=='.'){
flag=false;
System.out.println(". not after
@");
break;

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 150 of 170

Infosys Limited

Assignments for OO programming using Java part1

}
}
for(j=lastIndex;j<string.length();j++){
if(string.charAt(j)=='.'){
counter++;
if(counter>2){
flag=false;
System.out.println("more
than 2 dots ");
break;
}
}
}
if(counter==0){
flag=false;
break;
}
}
}
}
return flag;
}
}
class Demo{
public static void main(String args[]){
Customer obj=new Customer();
if(obj.validateEmailId("Richard")){
System.out.println("Valid email id");
}
else{
System.out.println("Invalid email id ");
}
if(obj.validateEmailId("Richard@yahoo.com")){
System.out.println("Valid email id");
}
else{
System.out.println("Invalid email id ");
}

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 151 of 170

Infosys Limited

Assignments for OO programming using Java part1

}
}

Stana identifies the messy portions of Richards code:


Variable names do not
class Customer{
reflecttheintent
private String emailId;
public boolean validateEmailId(String string)
{
boolean flag=true;
int startIndex=0,lastIndex=0,counter=0,i,j;
for(i=0;i<string.length();i++){
if((string.charAt(i)>='a' &&
string.charAt(i)<='z')||(string.charAt(i)>='A' &&
string.charAt(i)<='Z')||(string.charAt(i)>='0' &&
The charAt method is called
string.charAt(i)<='9')||(string.charAt(i)=='@')){
multipletimes
flag=true;
}
if(flag==false){
System.out.println("not an allowed character");
break;
Unnecessary use of flag variable,
}
duplicationofdigitcheckcode
else if(flag==true){
if(string.charAt(0)>='0' && string.charAt(0)<='9'){
flag=false;
System.out.println("not a digit");
break;
Codeisnotelegant,verymessyand
}
doesnotindicateintent
else{
for(j=0;j<string.length() &&
string.charAt(j)!='@';j++,lastIndex++){
if(string.charAt(j)=='.'){
flag=false;
System.out.println(". not after
@");
break;
}

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 152 of 170

Infosys Limited

Assignments for OO programming using Java part1

}
for(j=lastIndex;j<string.length();j++){
if(string.charAt(j)=='.'){
counter++;
if(counter>2){
flag=false;
System.out.println("more
than 2 dots ");
break;
}
}
}
if(counter==0){
flag=false;
break;
}
}
}
}
return flag;
}
}
class Demo{
public static void main(String args[]){
Customer obj=new Customer();
if(obj.validateEmailId("Richard")){
System.out.println("Valid email id");
}
else{
System.out.println("Invlaid email id ");
}
if(obj.validateEmailId("Richard@yahoo.com")){
System.out.println("Valid email id");
}
else{
System.out.println("Invlaid email id ");
}
}
}

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 153 of 170

Infosys Limited

Assignments for OO programming using Java part1

Richard cleans up his code which is as follows:


class Customer{
private String emailId;
public boolean validateEmailId(String string)
{
int loopCounter=0;
Variable names reflect the
intent
boolean flag=false;
char c;
//Checking for valid characters characters, digits,@ and .
if(isDigit(string.charAt(0))){
return false;
Compactcode
}
for(loopCounter=0;loopCounter<string.length();loopCounter++){
c=string.charAt(loopCounter);
if
(!(isCharacter(c)||isDigit(c)||isAttheRate(c)||isDot(c))){
return false;
}
else{
//Checking presence of @
if(c=='@'){
flag=true;
}
else{
if(isDotValidation(string)==false){
return false;
}
}
}
}
if(flag==false){
return false;
}
else{
return true;
}
}

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 154 of 170

Infosys Limited

Assignments for OO programming using Java part1

private boolean isCharacter(char c){


if((c>='a' && c<='z')||(c>='A' && c<='Z')){
return true;
}
Modularization of
else{
makingitreusable
return false;
}
}
private boolean isDigit(char c){
if(c>='0' && c<='9'){
return true;
}
else{
return false;
}
}
private boolean isDot(char c){
if(c=='.'){
return true;
}
else{
return false;
}
}
private boolean isAttheRate(char c){
if(c=='@'){
return true;
}
else{
return false;
}
}
private boolean isDotValidation(String string){
int loopCounter,countDot=0,loopCounter1,lastIndex=0;
for(loopCounter=0;loopCounter<string.length() &&
string.charAt(loopCounter)!='@';loopCounter++,lastIndex++){
if(string.charAt(loopCounter)=='.'){
return false;
}
}

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

code

Page 155 of 170

Infosys Limited

Assignments for OO programming using Java part1

for(loopCounter1=lastIndex;loopCounter1<string.length();loopCount
er1++){
if(string.charAt(loopCounter1)=='.'){
countDot++;
if(countDot>2){
return false;
}
}
}
return true;
}
}
class Demo{
public static void main(String args[]){
Customer obj=new Customer();
if(obj.validateEmailId("Richard")){
System.out.println("Valid email id");
}
else{
System.out.println("Invlaid email id ");
}
if(obj.validateEmailId("Richard@yahoo.com")){
System.out.println("Valid email id");
}
else{
System.out.println("Invlaid email id ");
}
}
}

Estimated Time: 20 minutes


Observations: The code is now modular, elegant, with no duplication. The names of
the variables and methods are meaningful. If you feel you can clean up more, please
do so !!!
Summary: In this assignment, you have learnt the importance of clean code. You have
revisited the concepts of Control structures, classes, objects, methods and method
calling and usage of String class as a data structure and the best practices to write
clean code using these.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 156 of 170

Infosys Limited

Assignments for OO programming using Java part1

Assignment 87: Unit testing - Demo


Objective: Given a business scenario, be able to generate/identify test cases
Problem Description: The Retail store now wants to display the information of the
customer based on the kind of customer.
Code: You have written/modified the given code in the earlier assignments. Please
execute the given code with the input values.
class Customer{
private int customerId;
private String customerName;
public Customer(int customerId,String customerName){
this.customerId=customerId;
this.customerName=customerName;
}
public void displayCustomerInformation(){
System.out.println("Customer Id :"+customerId);
System.out.println("Customer Name :"+customerName);
}
}
class RegularCustomer extends Customer{
private float discount;
public RegularCustomer(int customerId,String customerName, float
discount){
super(customerId,customerName);
this.discount=discount;
}
public void displayCustomerInformation(){
super. displayCustomerInformation();
System.out.println("Discount :"+discount);
}
}
class PrivilegedCustomer extends Customer{
private String memCardType;
public PrivilegedCustomer(int customerId,String customerName,
String memCardType){
super(customerId,customerName);
this.memCardType=memCardType;

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 157 of 170

Infosys Limited

Assignments for OO programming using Java part1

}
public void displayCustomerInformation(){
super. displayCustomerInformation();
System.out.println("Membership card type :"+memCardType);
}
}
class Retail{
public static void main(String args[]){
Customer custObj=null;
if(args[0].equalsIgnoreCase("Regular")){
custObj=new RegularCustomer(1001,"Jack",12.3f);
}
if(args[0].equalsIgnoreCase("Privileged")){
custObj=new PrivilegedCustomer(2001,"Jane","Gold");
}
custObj.displayCustomerInformation();
}
}

Input values on the command line:


Case1:args[0]=Regular
Output:
CustomerId:1001
CustomerName:Jack
Discount:12.3

Case2:args[0]=Privileged
Output:
CustomerId:2001
CustomerName:Jane
Membershipcardtype:Gold

Case3:args[0]=Platinum
Output:
Exceptioninthread"main"java.lang.NullPointerExceptionatRetail.main(Retail.java:46)

Answer the following questions:


1. Why do you think command line arguments provided and what is the reason for
creating the Retail class?
2. Why is the output so in case 3? Is the program unable to handle values other
than Regular and Privileged in the command line?
3. Do you think case 3 values are required for successful running of the code?

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 158 of 170

Infosys Limited

Assignments for OO programming using Java part1

Estimated time: 15 minutes


Summary of this assignment: In this assignment, you have unit tested the code a
module of the retail application.

Assignment 88: Boundary value analysis Demo


Objective: Given a business scenario, be able to generate/identify test cases based on
identified set of unit test case mechanisms.

Problem Description: The scenario discussed in OO Fundamentals Part I Assignment


14 is revisited here. The Retail Store needs to keep track of the bill amount paid by the
customer for a purchase and providesome discount based on the bill amount. Discount
has to be identified as per the table given below:
Bill Amount

Discount %

>=1000

10

>=500

0-500

You have written the code for this functionality before. It is given below for your
reference:
PurchaseBill
-billId: int
-billAmount:double
+setBillId(int): void
+setBillAmount(double):void
+getBillId(): int
+getBillAmount():double
+calculateBill(): void
Code:
class PurchaseBill{
private int billId;
private double billAmount;
public void setBillId(int id){
billId=id;

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 159 of 170

Infosys Limited

Assignments for OO programming using Java part1

}
public void setBillAmount(double amount){
billAmount=amount;
}
public int getBillId(){
return billId;
}
public double getBillAmount(){
return billAmount;
}
public void calculateBill(){
int discount=0;
if(billAmount>=1000.0){
discount=10;
}
else if(billAmount>=500){
discount=5;
}
System.out.println("Discount %:"+discount);
billAmount=billAmount-billAmount*discount/100;
}
}
class

Retail{
public static void main(String args[]){
PurchaseBill obj= new PurchaseBill();
obj.setBillId(1001);
obj.setBillAmount(999.99);
System.out.println("Bill Id:"+obj.getBillId());
System.out.println("Bill Amount:"+obj.getBillAmount());
obj.calculateBill();
System.out.println("Bill Amount after providing the
discount:"+obj.getBillAmount());
}
}

Boundary value analysis for generation of test cases:

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 160 of 170

Infosys Limited

Assignments for OO programming using Java part1

Boundary value analysis assumes that errors are most likely to exist at the boundaries
between partitions. Test cases are designed to exercise the software on and at either
side of boundary values.

Valid Range of Input Values

Lower
Limit -1

Lower
Limit

Lower
Limit + 1

Upper
Limit -1

Upper
Limit

Upper
Limit + 1

The test values could be given as follows:


Bill Amount

Discount %

Test inputs based on boundary


value analysis

>=1000

10

999,1000,1001

>=500 and <1000

499,500,501 for the lower limit


999,1000,1001 for the higher limit

<500(assume the lower


limit as 0)

-1,0,1 for the lower limit


499,500,501 for the upper limit

Set the bill amount to the values given in the test inputs column of the table given and
check the output. This constitutes unit testing of the code.
Test case documentation template: Please refer to the BoundaryValueAnalysis.xlsx
Estimated time: 10 minutes
Summary: In this assignment, you have understood the generation of test cases using
the boundary value analysis technique

Assignment 89: Boundary value analysis Hands on practice


Objective: Given a business scenario, be able to generate/identify test cases based on
identified set of unit test case mechanisms.
Problem Description: Consider an example to find the grade of a student based on the
percentage score. The criterion for grades is as given below:
Percentage Score
ETA/CORP/CRS/ FP14-GEN-003

Grade to be assigned

CONFIDENTIAL

Version No: 1.2

Page 161 of 170

Infosys Limited

Assignments for OO programming using Java part1

80 to 100
73 to 79
65 to 72
55 to 64
0 to 54
Z

A
B+
B
C
D
for invalid grades
(Score <0 or score >100)

Code:
class Student{
private float percentScore;
private String grade;
public Student(float percent){
percentScore=percent;
}
public void findGrade () {
if (percentScore >=80&& percentScore <=100) {
grade= "A";
}
else if (percentScore >=73 && percentScore <=79) {
grade= "B+";
}
else if (percentScore >=65 && percentScore <=72) {
grade="B";
}
else if (percentScore >=55 && percentScore <=64) {
grade="C";
}
else if (percentScore >=0 && percentScore <=54) {
grade="D";
}
else {
grade="Z";
}
}
public String getGrade(){
return grade;
}
public float getPercentScore(){

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 162 of 170

Infosys Limited

Assignments for OO programming using Java part1

return percentScore;
}
}
class Demo{
public static void main(String args[]){
Student studentOne=new Student(98.0f);
studentOne.findGrade();
System.out.println("Percentage
score:"+studentOne.getPercentScore());
System.out.println("Grade:"+studentOne.getGrade());
}
}

Arrive at the test inputs for the given code.Test the code using the input values.
Document the test cases in an excel sheet template similar to the one used in
Assignment 88.
Estimated time: 25 minutes
Summary: In this assignment, you have understood the generation of test cases using
the boundary value analysis technique

Assignment 90: Equivalence partitioning- Demo


Problem Description: The scenario discussed in OO Fundamentals Part I Assignment
14 is revisited here. The Retail Store needs to keep track of the bill amount paid by the
customer for a purchase and provide some discount based on the bill amount. Discount
has to be identified as per the table given below:
Bill Amount

Discount %

>=1000

10

>=500

0-500

You have written the code for this functionality before. It is given below for your
reference:
PurchaseBill
-billId: int
-billAmount:double
+setBillId(int): void

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 163 of 170

Infosys Limited

Assignments for OO programming using Java part1

+setBillAmount(double):void
+getBillId(): int
+getBillAmount():double
+calculateBill(): void
Code:
class PurchaseBill{
private int billId;
private double billAmount;
public void setBillId(int id){
billId=id;
}
public void setBillAmount(double amount){
billAmount=amount;
}
public int getBillId(){
return billId;
}
public double getBillAmount(){
return billAmount;
}
public void calculateBill(){
int discount=0;
if(billAmount>=1000.0){
discount=10;
}
else if(billAmount>=500){
discount=5;
}
System.out.println("Discount %:"+discount);
billAmount=billAmount-billAmount*discount/100;
}
}
class

Retail{
public static void main(String args[]){
PurchaseBill obj= new PurchaseBill();
obj.setBillId(1001);
obj.setBillAmount(999.99);
System.out.println("Bill Id:"+obj.getBillId());

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 164 of 170

Infosys Limited

Assignments for OO programming using Java part1

System.out.println("Bill Amount:"+obj.getBillAmount());
obj.calculateBill();
System.out.println("Bill Amount after providing the
discount:"+obj.getBillAmount());
}
}

Equivalence partitioning for generation of test cases:


It is based upon splitting the inputs and outputs of the software under test into a number
of partitions, where the behavior of the software is equivalent for any value within a
particular partition. Data which forms partitions is not just routine parameters. This
method can be used in conjunction with the boundary value analysis to increase test
coverage.
The test inputs for this code using equivalence partitioning is given in the table below:
Bill Amount

Discount %

Test inputs based on boundary


value analysis

>=500 and <1000

-5,758,3000

<500(assume the lower


limit as 0)

-9,432,800

Set the bill amount to the values given in the test inputs column of the table given and
check the output. This constitutes unit testing of the code.
Test case documentation template: Please refer to the EquivalencePartitioning.xlsx
Estimated time: 20 minutes
Summary:
In this assignment, you have learnt to generate test cases using equivalence
partitioning technique.

Assignment 91: Equivalence partitioning- Hands on practice


Objective: Given a business scenario, be able to generate test cases using
equivalence partitioning technique and document them.
Problem Description:
Consider the code written in Assignment 11. Generate the test cases using equivalence
partitioning for each of the ranges given, test using the inputs and document using the
excel sheet template which was used in Assignment 90.

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 165 of 170

Infosys Limited

Assignments for OO programming using Java part1

Estimated time: 25 minutes


Summary:
In this assignment, you have learnt to generate test cases using equivalence
partitioning technique.

Assignment 92: Logic Coverage(Statement) Demo 1


Objective: Given a business scenario, be able to generate unit test cases for statement
coverage and document them.
Problem Description: Consider the scenario where the discount is provided to senior
citizens (male and female) during railway ticket booking. The statement coverage can
be understood as follows:

Estimated time: 10 minutes


Summary: In this assignment, you have learnt to generate unit test cases for statement
coverage.

Assignment 92: Logic Coverage (Branch) Demo 2

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 166 of 170

Infosys Limited

Assignments for OO programming using Java part1

Objective: Given a business scenario, be able to generate unit test cases for branch
coverage and document them
Problem Description: Consider the scenario where the discount is provided to senior
citizens (male and female) during railway ticket booking. The branch coverage can be
understood as follows:

Estimated time: 10 minutes


Summary: In this assignment, you have learnt to generate unit test cases for branch
coverage.

Assignment 92: Logic Coverage (Condition) Demo 3


Objective: Given a business scenario, be able to generate unit test cases for condition
coverage and document them
Problem Description: Consider the scenario where the discount is provided to senior
citizens (male and female) during railway ticket booking. The condition coverage can be
understood as follows:

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 167 of 170

Infosys Limited

Assignments for OO programming using Java part1

Estimated time: 10 minutes


Summary: In this assignment, you have learnt to generate unit test cases for condition
coverage.

Assignment 92:Logic Coverage (Compound Condition) Demo 4


Objective: Given a business scenario, be able to generate unit test cases for
compound condition coverage and document them
Problem Description: Consider the scenario where the discount is provided to senior
citizens (male and female) during railway ticket booking. The compound condition
coverage can be understood as follows:

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 168 of 170

Infosys Limited

Assignments for OO programming using Java part1

Estimated time: 10 minutes


Summary: In this assignment, you have learnt to generate unit test cases for
compound condition coverage.

Assignment 92: Logic Coverage (Path Condition) Demo 5


Objective: Given a business scenario, be able to generate unit test cases for path
coverage and document them
Problem Description: Consider the scenario where the discount is provided to senior
citizens (male and female) during railway ticket booking. The path coverage can be
understood as follows:

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 169 of 170

Infosys Limited

Assignments for OO programming using Java part1

Estimated time: 10 minutes


Summary: In this assignment, you have learnt to generate unit test cases for path
condition coverage

ETA/CORP/CRS/ FP14-GEN-003

CONFIDENTIAL

Version No: 1.2

Page 170 of 170

S-ar putea să vă placă și