Java Assignments
Java Assignments
Java Assignments
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
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
Meenakshi S
1.2
Apr-May
2014
Meenakshi S
1.3
May 2014
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
Version
Date
Author(s)
Reviewer(s)
Description
4.0
Sep 2014
K.N.Vani
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
CONFIDENTIAL
Infosys Limited
Guidelines
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 1 of 170
Infosys Limited
Hint: You can refer the problem decomposition provided in the slides for designing an
online ticket booking problem.
Estimated Time: 15 minutes
Algorithm
Input
Output
:
:
:
PROCESS_MARKS
Marks of 5 subjects
Total marks and the average marks
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
PROCESSING_MARKS
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 2 of 170
Infosys Limited
2. total =0
Note that the statements are executed in sequence
3. total= M1+M2+M3+M4+M5
4. display total
5. average=0
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.
Grade
A
B+
B
C
D
input Module_Test_Marks
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 3 of 170
Infosys Limited
2.
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.
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
Page 4 of 170
Infosys Limited
Effectiveness
Input
2.
Total =0
3.
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.
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 5 of 170
Infosys Limited
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.
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
Page 6 of 170
Infosys Limited
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
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 7 of 170
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 8 of 170
Infosys Limited
Once loaded, you will see the Welcome tab as shown in Fig. 4. Close this Welcome tab
to go to the Project Window.
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 9 of 170
Infosys Limited
Selecting the java perspective will give you the screen as shown in Fig. 6.
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 10 of 170
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 11 of 170
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 12 of 170
Infosys Limited
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.
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 13 of 170
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 14 of 170
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 15 of 170
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 16 of 170
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 17 of 170
Infosys Limited
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
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 18 of 170
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 19 of 170
Infosys Limited
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
class Retail {
public static void main(String[]args){
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 20 of 170
Infosys Limited
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
Page 21 of 170
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 22 of 170
Infosys Limited
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
Page 23 of 170
Infosys Limited
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);
}
}
}
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 24 of 170
Infosys Limited
CONFIDENTIAL
Page 25 of 170
Infosys Limited
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
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 26 of 170
Infosys Limited
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.
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
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 27 of 170
Infosys Limited
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
Page 28 of 170
Infosys Limited
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
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
Page 29 of 170
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 30 of 170
Infosys Limited
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.
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 31 of 170
Infosys Limited
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);
}
}
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 32 of 170
Infosys Limited
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
Page 33 of 170
Infosys Limited
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
Page 34 of 170
Infosys Limited
technologies
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
Page 35 of 170
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 36 of 170
Infosys Limited
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.
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 37 of 170
Infosys Limited
Notetheuseofaccessspecifiersintheclass,Customer
Notehowtheclass,Customeriswritten
class Customer{
private int customerId;
private long telephoneNo;
Notetheuseofinstancevariablesormember
variablescustomerIdandtelephoneNoin
theclass,Customer
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Notetheuseofmembermethodsintheclass,
Customer
Notethehowlocalvariablesareusedinthe
membermethodsofclass,Customer
Notethehowmethodheader,method
definition,returnstatementiswrittenin
membermethodofclass,Customer
Page 38 of 170
Infosys Limited
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
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 39 of 170
Infosys Limited
System.out.println("Item Price:"+price);
}
}
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
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 40 of 170
Infosys Limited
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;
..
..
}
}
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 41 of 170
Infosys Limited
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
Page 42 of 170
Infosys Limited
Illustration:
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Twoobjectsarepassedby
reference
Page 43 of 170
Infosys Limited
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
Page 44 of 170
Infosys Limited
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
Page 45 of 170
Infosys Limited
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
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 46 of 170
Infosys Limited
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
FACTORIAL (number)
1. if (number = 0) then
2.
return(1)
Note the termination condition
3. else
4.
5. end-if
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 47 of 170
Infosys Limited
}
}
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 48 of 170
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 49 of 170
Infosys Limited
: 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
Page 50 of 170
Infosys Limited
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
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 51 of 170
Infosys Limited
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
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 52 of 170
Infosys Limited
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?
In the above scenario, what is the order in which the print requests are stored in
the printers memory?
ii.
7
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 53 of 170
Infosys Limited
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
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 54 of 170
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 55 of 170
Infosys Limited
Problem description: Represent the logic required for deleting element 6 from the
array using pseudo-code and implement and execute it in Java.
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 56 of 170
Infosys Limited
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
H
Algorithm
45
:
ETA/CORP/CRS/ FP14-GEN-003
30
10
INSERT_ELEMENT_LINKED_LIST
CONFIDENTIAL
Page 57 of 170
Infosys Limited
Input
Output
:
:
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.
3.
4.
5.
6.
7.
8.
3. n.link = head
4. head = n
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 58 of 170
Infosys Limited
Note:
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 59 of 170
Infosys Limited
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
Page 60 of 170
Infosys Limited
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
Finalvariableisaconstantvariableinjava
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 61 of 170
Infosys Limited
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
Page 62 of 170
Infosys Limited
stack.push(15);
stack.pop();
stack.pop();
}
}
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 63 of 170
Infosys Limited
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
Page 64 of 170
Infosys Limited
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.
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 65 of 170
Infosys Limited
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.
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
Page 66 of 170
Infosys Limited
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.
Implement the above logic in Java after learing through the concept of Relationships in
Java.
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 67 of 170
Infosys Limited
CONFIDENTIAL
Page 68 of 170
Infosys Limited
Sizeofthearray,telephoneNois3.
Note:Ifsizeisnotexplicitlymentionedwhiledeclaringanarrayusingnewoperator,itistakenasthe
numberofelementsinitialized
2.
48214280200
3.
Runtimeexception,sincewearetryingtoaccessanelementoutsidethearray.
Note:Arrayboundcheckinghappensexplicitly
: int
: long[]
+setCustomerId(int)
: void
+getCustomerId()
: int
+setTelephoneNo(long[]) : void
+getTelephoneNo()
: long[]
Code:
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 69 of 170
Infosys Limited
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
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
Page 70 of 170
Infosys Limited
Output:
CustomerId:1001
TelephoneNos:920186131192018613219201661311
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 71 of 170
Infosys Limited
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
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
Page 72 of 170
Infosys Limited
CONFIDENTIAL
Page 73 of 170
Infosys Limited
}
}
class
Retail{
Revised Code:
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 74 of 170
Infosys Limited
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
Page 75 of 170
Infosys Limited
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
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 76 of 170
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 77 of 170
Infosys Limited
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
Page 78 of 170
Infosys Limited
Customer
-customerId
: int
-telephoneNo
: long[]
-customerName
: String
+ setCustomerId(int)
: void
+getCustomerId()
: int
+setTelephoneNo(long[])
: void
+getTelephoneNo()
: long[]
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 79 of 170
Infosys Limited
+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
Page 80 of 170
Infosys Limited
class
Notethatsincewehavenotexplicitlycoded
theconstructor,systemprovidesadefault
constructorwhichinitializestheinstance
variablestotheirdefaultvalues
Retail{
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
Page 81 of 170
Infosys Limited
}
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
Page 82 of 170
Infosys Limited
Output:
CustomerId:1000
Doyouthinkthiswillsatisfythe
requirementprovidedaspartof
problemdescription?
TelephoneNos:999999999999999999999999999
CustomerName:Default
NoValuesinitializedforeachcustomermustbedifferent.Itdependsoneachcustomer.Thiscanbeachieved
usingparameterizedconstructor
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 83 of 170
Infosys Limited
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
Page 84 of 170
Infosys Limited
}
return false;
}
}
class
Retail{
Output:
CustomerId:1001
TelephoneNos:920186131192018613219201661311
CustomerName:Kevin
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 85 of 170
Infosys Limited
: 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
Page 86 of 170
Infosys Limited
}
}
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
Page 87 of 170
Infosys Limited
customerId = id;
}
public int getCustomerId(){
Notehowstaticmethodiswritten
return customerId;
}
public static int totalNoOfCustomers(){
return counter-1000;
}
}
class
Retail{
public static void main(String args[]){
}
}
Output:
CustomerId:1001
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 88 of 170
Infosys Limited
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
Page 89 of 170
Infosys Limited
Output:
CompilationError:CannotconvertStringtoint
Whatdoyouthinkisthe
reasonforthiserror?
CONFIDENTIAL
Page 90 of 170
Infosys Limited
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
Page 91 of 170
Infosys Limited
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
Page 92 of 170
Infosys Limited
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
Page 93 of 170
Infosys Limited
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.
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 94 of 170
Infosys Limited
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?
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 95 of 170
Infosys Limited
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
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 96 of 170
Infosys Limited
consuming approach if problem size is large using linear search and bubble sort
algorithms.
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 97 of 170
Infosys Limited
12.
end-if
13.
end-if
14. end-while
Write a Java code to implement binary search technique and execute it using
Eclipse.
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
Page 98 of 170
Infosys Limited
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]
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
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Page 99 of 170
Infosys Limited
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{
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
Output:
**********
Report
**********
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
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);
}
}
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
Infosys Limited
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
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
Infosys Limited
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
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
Infosys Limited
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
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
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
CONFIDENTIAL
Infosys Limited
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
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
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
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
}
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
Infosys Limited
Howcantheinstancevariables
beinitializedalongwithobject
creation??
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
Infosys Limited
Notehowparameterizedconstructoris
writtenforRegularCustomer
Notehowparameterizedconstructoris
writtenforPrivilegedCustomer
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
Output:
RegularCustomerDetails
CustomerId:1001
CustomerName:Kevin
Discount:10.0
PrivilegedCustomerDetails
CustomerId:1002
CustomerName:James
MembershipCardType:Gold
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
}
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();
}
}
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
Infosys Limited
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
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
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
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
}
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
Infosys Limited
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.
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
Infosys Limited
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
Infosys Limited
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
Infosys Limited
Case1Output:
EasyShopRetailStoreBill
BillId
Finalbillamounttobepaid
:5001
:Rs.1055.0
ThankYou!!!VisitAgain
Case2Output:
EasyShopRetailStoreBill
BillId
Finalbillamounttobepaid
:5001
:Rs.1107.75
ThankYou!!!VisitAgain
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
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
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
Output:
WhyisitthatthecustomerIdis
notdisplayedforbothRegular
&Privilegedcustomer?
RegularCustomerDetails
Discount:20.0
PrivilegedCustomerDetails
MembershipCardType:Gold
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
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
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();
}
}
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
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
Infosys Limited
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.
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
}
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
Infosys Limited
Case2Output:
CustomerId:2001
CustomerName:Jane
Membershipcardtype:Gold
NotethatthedisplayCustomerInformation()methodofCustomerclassoverriddenintheRegularand
Privileged Customer classes .Also, note that the version of the displayCustomerInformation() being
calleddependsonthekindofcustomer
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
The abstract keyword can be used with classes to provide the prototype of the
methods, however leave the implementation to the child classes.
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
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());
}
}
}
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
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
Infosys Limited
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
Infosys Limited
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
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
Infosys Limited
System.out.println("Sum= "+sum);
}
}
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
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.
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
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.
CONFIDENTIAL
Infosys Limited
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
Infosys Limited
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.
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
Infosys Limited
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.
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
Infosys Limited
...
}
}
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.
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
Infosys Limited
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.
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
Infosys Limited
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
CONFIDENTIAL
Infosys Limited
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.
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
}
}
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
Infosys Limited
}
}
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
}
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
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
code
Infosys Limited
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 ");
}
}
}
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
}
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();
}
}
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)
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
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
Infosys Limited
}
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());
}
}
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
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.
Lower
Limit -1
Lower
Limit
Lower
Limit + 1
Upper
Limit -1
Upper
Limit
Upper
Limit + 1
Discount %
>=1000
10
999,1000,1001
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
Grade to be assigned
CONFIDENTIAL
Infosys Limited
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
Infosys Limited
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
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
Infosys Limited
+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
Infosys Limited
System.out.println("Bill Amount:"+obj.getBillAmount());
obj.calculateBill();
System.out.println("Bill Amount after providing the
discount:"+obj.getBillAmount());
}
}
Discount %
-5,758,3000
-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.
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
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:
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL
Infosys Limited
ETA/CORP/CRS/ FP14-GEN-003
CONFIDENTIAL