You are on page 1of 99

Object Oriented Concepts using Java Lab Guide

CONFIDENTIAL

Infosys Limited

Object Oriented Concepts Using Java

COPYRIGHT NOTICE
All ideas and information contained in this document are the intellectual property of Education and Research
Department, Infosys Limited. This document is not for general distribution and is meant for use only for the person
they are specifically issued to. This document shall not be loaned to anyone, within or outside Infosys, including its
customers. Copying or unauthorized distribution of this document, in any form or means including electronic,
mechanical, photocopying or otherwise is illegal.

Education and Research Department


Infosys Limited
Electronic City
Hosur Road
Bangalore - 560 100, India.
Tel: 91 80 2852 0261
Fax: 91 80 2852 0362
www.infosys.com
mailto:E&R@infosys.com

1|Page

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Contents
COPYRIGHT NOTICE ......................................................................................................1
CONTENTS ..................................................................................................................2
CONTEXT ....................................................................................................................6
GUIDELINES .................................................................................................................6
TOPIC 1: INTRODUCTION TO OBJECT ORIENTATION ..............................................................6
1.1: INTRODUCTION AND NEED FOR OBJECT ORIENTED APPROACH ..........................................6
ASSIGNMENT 1.1.1: CASE STUDY ............................................................................................. 6
1.2: INTRODUCTION TO OOAD AND UML .............................................................................7
ASSIGNMENT 1.2.1: USE CASE DIAGRAM FOR COURSE REGISTRATION SYSTEM ................................................ 7
ASSIGNMENT 1.2.2: USE CASE DIAGRAM...................................................................................... 8
ASSIGNMENT 1.2.3 : CASE STUDY OF SPEDFAST COURIER COMPANY ........................................................... 8
1.3: OBJECT ORIENTED CONCEPTS ...................................................................................9
ASSIGNMENT 1.3.1: IDENTIFY THE OO CONCEPTS ............................................................................. 9
ASSIGNMENT 1.3.2: OBJECT ORIENTED CONCEPTS ......................................................................... 10
ASSIGNMENT 1.3.3: OBJECT ORIENTED TERMINOLOGIES .................................................................... 11
TOPIC 2: BASICS OF OBJECT ORIENTED PROGRAMMING ........................................................ 12
2.1: CONCEPT OF VARIABLES, CONSTANTS & DATATYPES .................................................... 12
ASSIGNMENT 2.1.1: UNDERSTANDING THE VARIABLES, CONSTANTS & DATATYPES ........................................... 12
ASSIGNMENT 2.1.2: UNDERSTANDING CONSTANTS .......................................................................... 13
2.2: OPERATORS & TYPECASTING ................................................................................... 14
ASSIGNMENT 2.2.1: TYPE CASTING ......................................................................................... 14
2.3: CLASSES AND OBJECTS .......................................................................................... 15
ASSIGNMENT 2.3.1: UNDERSTANDING THE TERMS ........................................................................... 15
ASSIGNMENT 2.3.2: DEBUGGING ............................................................................................ 16
ASSIGNMENT 2.3.3: CLASSES AND OBJECTS ................................................................................. 17
2.4: UNDERSTANDING JAVA ARCHITECTURE ...................................................................... 19
ASSIGNMENT 2.4.1: BYTE CODES AND .CLASS FILES.......................................................................... 19
2.5: IMPLEMENTATION OF CLASS .................................................................................... 20
ASSIGNMENT 2.5.1: CLASS CREATION ....................................................................................... 20
2.6: REFERENCES AND OBJECTS ..................................................................................... 21
ASSIGNMENT 2.6.1: PASS BY VALUE AND REFERENCE ........................................................................ 21
ASSIGNMENT 2.6.2: OBJECT PASSING BY REFERENCE ........................................................................ 22
2.7: SELECTIONAL CONTROL STRUCTURE ......................................................................... 25

2|Page

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

ASSIGNMENT 2.7.1: SELECTIONAL CONTROL STRUCTURES ................................................................... 25


ASSIGNMENT 2.7.2: SELECTIONAL CONTROL STRUCTURES ................................................................... 26
ASSIGNMENT 2.7.3: SWITCH CASE STATEMENT .............................................................................. 28
2.8: ITERATIONAL CONTROL STRUCTURES ........................................................................ 29
ASSIGNMENT 2.8.1: UNDERSTANDING LOOPS ................................................................................ 29
ASSIGNMENT 2.8.2: BUILDING LOGIC USING ITERATIONAL CONTROL STRUCTURES ............................................ 31
2.9: CONTROL STATEMENTS.......................................................................................... 32
ASSIGNMENT 2.9.1: BREAK & CONTINUE .................................................................................... 32
2.10: THIS REFERENCE ............................................................................................. 34
ASSIGNMENT 2.10.1: USAGE OF THIS KEYWORD .......................................................................... 34
ASSIGNMENT 2.10.2: USAGE OF THIS KEYWORD .......................................................................... 35
ASSIGNMENT 2.10.3: DEBUGGING THIS REFERENCE .................................................................... 36
2.11: CONSTRUCTOR ................................................................................................... 37
ASSIGNMENT 2.11.1: DEFAULT CONSTRUCTOR .............................................................................. 37
ASSIGNMENT 2.11.2: DEFAULT AND PARAMETERIZED CONSTRUCTORS ....................................................... 38
ASSIGNMENT 2.11.3: DEFAULT AND PARAMETERIZED CONSTRUCTORS ....................................................... 39
2.12: STATIC KEYWORD ............................................................................................... 41
ASSIGNMENT 2.12.1: STATIC VARIABLE, BLOCK AND METHOD................................................................ 41
ASSIGNMENT 2.12.2: DEFAULT CONSTRUCTOR AND STATIC KEYWORD ....................................................... 41
TOPIC 3: CODING STANDARDS & INDUSTRY BEST PRACTICES ................................................. 44
3.1: OPTIMIZATION OF CODE ......................................................................................... 44
ASSIGNMENT 3.1.1: OPTIMIZATION OF CODE ................................................................................ 44
3.2: CODING STANDARDS .............................................................................................. 49
ASSIGNMENT 3.2.1: TO UNDERSTAND THE IMPORTANCE OF CODING STANDARDS ............................................ 49
TOPIC 4: ARRAYS ........................................................................................................ 50
4.1: ARRAYS .............................................................................................................. 50
ASSIGNMENT 4.1.1: ARRAYS ................................................................................................ 50
4.2: MULTIDIMENSIONAL ARRAY ..................................................................................... 51
ASSIGNMENT 4.2.1: MULTIDIMENSIONAL ARRAY(JAGGED ARRAY) ........................................................... 51
TOPIC 5: STRINGS ....................................................................................................... 52
5.1: STRING & ARRAY OF STRINGS .................................................................................. 52
ASSIGNMENT 5.1.1: STRINGS ................................................................................................ 52
ASSIGNMENT 5.1.2: STRINGS ................................................................................................ 55
ASSIGNMENT 5.1.3: ARRAY OF STRINGS ..................................................................................... 57
5.2: STRING HANDLING FUNCTIONS................................................................................. 58

3|Page

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

ASSIGNMENT 5.2.1: STRINGS ............................................................................................... 58


5.3: COMMAND LINE ARGUMENTS ................................................................................... 59
ASSIGNMENT 5.3.1: COMMAND LINE ARGUMENTS ........................................................................... 59
TOPIC 6: RELATIONSHIPS .............................................................................................. 62
6.1: INHERITANCE ...................................................................................................... 62
ASSIGNMENT 6.1.1: RELATIONSHIPS IS A RELATIONSHIP .................................................................. 62
ASSIGNMENT 6.1.2: DEFAULT & ADVANCED PARAMETERIZED CONSTRUCTOR ................................................ 66
6.2: AGGREGATION ..................................................................................................... 67
ASSIGNMENT 6.2.1: RELATIONSHIPS HAS-A RELATIONSHIP ............................................................... 68
6.3: ASSOCIATION ....................................................................................................... 70
ASSIGNMENT 6.3.1: RELATIONSHIPS USES A RELATIONSHIP ................................................................ 70
TOPIC 7: POLYMORPHISM ............................................................................................. 71
7.1: METHOD OVERLOADING ......................................................................................... 71
ASSIGNMENT 7.1.1: METHOD OVERLOADING ................................................................................ 71
7.2: INTRODUCTION TO POLYMORPHISM AND TYPES ........................................................... 72
ASSIGNMENT 7.2.1: PARAMETERIZED CONSTRUCTOR AND CONSTRUCTOR OVERLOADING ..................................... 72
ASSIGNMENT7.2.2: DEFAULT & PARAMETERIZED CONSTRUCTOR ADVANCED................................................. 74
7.3: METHOD OVERRIDING ............................................................................................ 76
ASSIGNMENT 7.3.1: METHOD OVERRIDING .................................................................................. 76
7.4: DYNAMIC POLYMORPHISM ....................................................................................... 78
ASSIGNMENT 7.4.1: DYNAMIC POLYMORPHISM............................................................................... 78
TOPIC 8: ABSTRACT KEYWORD AND INTERFACES ................................................................ 83
8.1: ABSTRACT KEYWORD............................................................................................. 83
ASSIGNMENT 8.1.1: ABSTRACT CLASS AND METHOD .......................................................................... 83
8.2: INTERFACES ........................................................................................................ 84
ASSIGNMENT 8.2.1: INTERFACES ............................................................................................ 84
TOPIC 9: PACKAGES .................................................................................................... 86
ASSIGNMENT 9.1.1: PACKAGES .............................................................................................. 86
ASSIGNMENT 9.1.2: PACKAGES FOR COURSE REGISTRATION SYSTEM ........................................................ 90
TOPIC 10: ANALYSIS OF ALGORITHMS .............................................................................. 91
ASSIGNMENT 10.1.1: ANSWER THE QUESTIONS .............................................................................. 91
ASSIGNMENT 10.1.2: STEP COUNT .......................................................................................... 91
ASSIGNMENT 10.1.3: TIME COMPLEXITY .................................................................................... 92
ASSIGNMENT 10.1.4: IDENTIFYING TIME COMPLEXITY OF WELL-KNOWN ALGORITHMS ........................................ 95

4|Page

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

TOPIC 11: CODE TUNING TECHNIQUES ............................................................................. 96


ASSIGNMENT 11.1.1: USAGE OF
ASSIGNMENT 11.1.2: USAGE OF
ASSIGNMENT 11.1.3: USAGE OF
ASSIGNMENT 11.1.4: USAGE OF

5|Page

CODE TUNING TECHNIQUES (1)


CODE TUNING TECHNIQUES (2)
CODE TUNING TECHNIQUES (3)
CODE TUNING TECHNIQUES (4)

......................................................... 96
......................................................... 96
......................................................... 97
......................................................... 97

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Context
This document contains Practice Questions to be completed as a part of the practice session
for module Introduction to Object Oriented Programming.

Guidelines
x
x

x
x
x
x

The lab guide has been designed to give a hands on experience to map the concepts
learnt in the session with practical assignments
The assignments have been categorized into solved assignments to hand hold a
beginner, partially solved assignments to begin trying out on their own and unsolved
assignments to let learners write code completely on their own
These assignments contain coding exercises, debugging exercises, coding standards
exercises and self-review assignments
Lab guide assignments are threaded assignment which can be built incrementally every
day. This will help understanding the concepts and building a complete application
Solving these exercises methodically would provide confidence to the learner to
attempt the module and Hands-On exams
The estimated time would help a learner to solve problems given a deadline

Topic 1: Introduction to object orientation


1.1: Introduction and need for object oriented approach
Assignment 1.1.1: Case Study
Objective: Analysis of the following Case Study from the perspective of Object Oriented
Approach
Problem Description: Course Registration System
A Course Registration System needs to be developed for an engineering college. The college
wants an automated system to replace its manual system for the purpose of registration of
students to branches and calculation of fees for each year. The engineering college provides
graduation courses in various branches of engineering.
The system will be used by the admin staff to register students, admitted to the college to
the branches, at the time of joining the college and also to calculate the yearly fees for the
students. The student has to register every year for the next academic year. The Admin takes
care of the yearly registration of the students and the calculation of yearly fees. The system
needs to be authenticated with a login id and password.
Registration of a student to a branch is based on the qualifying exam marks and the entrance
counseling. For every branch, a yearly branch fee is applicable. Discounts are given to the
6|Page

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

branch fees of the first year based on the qualifying exam marks. In addition to this, there is
a registration fee which is applicable to the first year students. Students can opt to be a day
scholar or hostelite. Annual bus fee is applicable to the day scholars based on the distance
they travel. Annual hostel fee is applicable for all the hostelites. Annual infrastructure fees
and library fee is 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 on the branch of study, which will be allocated to a student is not within the
scope of this case study
Estimated time: 15 minutes
Summary of this assignment:
In this assignment, you have learnt
x Understanding from the perspective of Object oriented approach

1.2: Introduction to OOAD and UML


Assignment 1.2.1: Use Case Diagram for Course Registration System
Consider the above case study Course Registration System (Assignment 1.1.1).
Answer the following questions:
1. Identify all the actors of the Course Registration System
2. Identify the activities i.e. use cases of the system
3. Connect the actors to the use cases and draw the use case diagram for the system
Note:
x

7|Page

The use case diagram can be drawn in a Microsoft Word Document

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Estimated time: 25 minutes


Summary of this assignment:
In this assignment, you have learnt
x To analyze and design the Use case diagram for a given problem statement

Assignment 1.2.2: Use Case Diagram


Objective: Understand requirements of the system and draw the use case diagram.
Problem Description: Consider the scenario of an online auction including buyers and sellers.
Buyer and Seller have to create accounts and searches listing for an item (buyer to buy at
lowest price and seller to sell at profitable price). The seller has to create an auction and has
to ship the item if an acceptable bid is made. The buyer has to place a favorable bid and
purchases the item.
x
x

Identify the system, actors, use cases and the relationship


Draw use case diagram
Note:
x

The use case diagram can be drawn in a Microsoft Word Document

Estimated time: 15 minutes


Summary of this assignment:
In this assignment, you have learnt
x To analyze a scenario and identify actors, use cases and relationships and draw the
use case diagram

Assignment 1.2.3 : Case study of SpedFast Courier Company


Objective: Understand requirements of the system and draw the use case diagram.
Problem Description: A courier company SpedFast wants to automate their process of
collecting and dispatching shipments. The company has a set of customers, many of whom are
already in the companys database. Each customer has a unique Customer ID. Each customer
has an address as well, which is used as Senders address for shipments.
8|Page

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Customers approach the Dispatchers1 at SpedFast counters to send shipments. One customer
can send as many shipments as required. The Dispatcher initiates a shipment after the
payment from the customer.
Each shipment has a Shipment ID associated with it. A shipment also has a Recipients
address, priority, weight of the shipment, shipping date and date of delivery. The amount is
calculated based on the weight of the shipment and priority. Currently SpedFast provides
LOW, NORMAL and URGENT priorities with different rates on shipments.
SpedFast also intends to have a Greeting Shipment service for customers to send Gifts for
celebrations. This is similar to the normal shipments, but it also carries a Greeting message
from the customer.
Step 1: Design the Use Case diagram
Note:
x

The use case diagram can be drawn in a Microsoft Word Document

Estimated time: 15 minutes


Summary of this assignment:
In this assignment, you have learnt
x To understand the requirements and design the use case diagram

1.3: Object Oriented Concepts


Assignment 1.3.1: Identify the OO concepts
Objective: Analysis of the scenarios picked from the case study discussed in Assignment 1.1.1
and identification of the OO concepts associated to the scenarios
Problem Description: Identify the OO concepts associated with the scenarios given below
1. There are around 10000 students studying in various branches of engineering in the
college. Every student has some attributes and performs some activities. How can the
attributes and activities be represented using OO concepts .
1

Dispatcher: The person who dispatches shipments in a postal organization or courier company.

9|Page

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

2. Students can opt to be a Day Scholar or a Hostelite. In case of Day Scholar, bus fee is
applicable based on the distance from the residential location to the college. In case
of Hostelite, hostel fee is applicable. Identify the OO concept discussed .Identify the
generalized and specialized classes for this scenario.
3. The Admin staff calculates the fee to be paid for all students irrespective of the type
of student. The formula for calculation however depends on the kind of student.
Which is the OO concept discussed here?
4. Certain attributes of the student need to be accessed by the admin staff directly, and
certain attributes need not be accessed. How can this be implemented and what is the
OO concept discussed here?
Estimated time: 15 minutes
Summary of this assignment:
In this assignment, you have learnt
x To analyze a scenario and apply the OO concepts

Assignment 1.3.2: Object Oriented Concepts


Objective: Understand the various Object Oriented concepts and their definitions
Problem Description: Fill in the blanks for the statements given below
1. The properties exhibited by a complex system are ____, _____ and ____
2. A ___________ is a software design that describes the common attributes and behavior
of objects
3. OO concept derived from the words meaning In a Capsule is _____________
4. A class diagram is represented by a ____________ with the components of a class
5. ______________ are used to expose or hide the attributes/activities of a class
6. UML diagram which can be used to identify the functionalities of the system under
development is called ___________
7. OO concept wherein a class shares some common structure or behavior with one or
more classes is called _____________
10 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

8. OO concept which refers to an objects ability to behave differently depending on its


type is called ________________
9. The Unified Modelling Language (UML) is a language for specifying, constructing,
____________, and _____________ the software system and its components
10. Process of focusing on essential details and ignoring non-essential details is called
__________
Estimated time: 10 minutes
Summary of this assignment:
In this assignment, you have learnt
x Object Oriented concepts and their definitions

Assignment 1.3.3: Object Oriented Terminologies


Objective: Understand the various Object Oriented Terminologies
Problem Description: Fill in the crossword based on the scenario and clues given below:
Ashok and Amit are two employees who joined the Human Resources Department of a
technology driven firm this financial year. Ashok has opted to be a full time employee while
Amit has opted to be a part time one. The Accounting Group Head has to take care of
calculating the employees salary based on the status of work. For Ashok, the salary includes
DA, HRA, PF Contributions, Conveyance Charges and Fixed Salary component. For Amit ,the
salary includes DA, HRA and Fixed Salary Component only. On receiving salary, the employees
have to submit their signatures as a proof of receiving the salary from the accounting group.
Across
1. Ashok is an ________ of Employee class
2. Accounting group head represents an ________ of the course registration
system
3. Ashok and Amit are two kinds of employees. This represents the
_____________ OO concept.
4. The Accounting Group Head calculates the salary to be handed over for all
employees irrespective of the type of student. The formula for calculation
however depends on the kind of employee. This represents the
______________ OO concept.
Down
5. The notation that can be used for representing the salary system:
6. Ashok has access to details which are essential for him, whereas the
Accounting Group Head has access to all information related to the
employees. This represents the _________ OO concept
11 | P a g e

Infosys Foundation Program

Infosys Limited

7.

Object Oriented Concepts Using Java

The attributes and activities of an employee can be bundled into a


__________
6
1

2
7
3
5
4

Estimated time: 10 minutes


Summary of this assignment:
In this assignment, you have learnt
x Object Oriented Terminologies

Topic 2: Basics of Object oriented Programming


2.1: Concept of variables, constants & datatypes
Assignment 2.1.1: Understanding the variables, constants & datatypes
Objective: To define variables and constants & datatypes and to print the same.
Background: Java supports different basic data types (int, float, double,char etc).
Note: A java file VariablesDemo.java is provided to you in Supplied Source Code folder within
the Lab Guide folder.

12 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Problem Description: Declare variables to store employee id, gender, basic salary and
allowances. Display all the details.
Step 1: Create a class file in the java project with the name VariablesDemo.java. Now copy
the source code, given in VaribalesDemo.java to the one created in the project
Step 2: In the supplied code, a variable called empId is declared of type int to store the
Employee id. Similarly declare the variable for storing gender, basic salary and allowances.
Variable Name
Gender
Allowances
basicSalary

Datatype
char
float
double

Step 3: Once when variables are declared, assign some values to it and display the same.
Step 4: Compile and run the program to view the outcome of the program.

Note:
While assigning value to char variable, the data should be in
single quotes. For example consider a variable option which
takes Y for Yes and N for No.
char option = 'Y' ;
And check what happens when you assign a value using double
quotes ( ) for char variable.

Estimated time: 20 minutes


Summary of this assignment:
In this assignment, you have learnt:
x Variable declarations
x Datatypes
At the end of the assignment you would have the following files:
VariablesDemo.java

Assignment 2.1.2: Understanding Constants


Objective: To define constant variable and print the same.
13 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Problem Description: Refer Assignment 2.1.1, make the basic salary as constant and assign
the value 25000.0 to it.
Example: To make a variable as constant, the keyword final should be used.
final int age = 21 ;

Note:
Try assigning some values to the final (constant) variable in your
code and observe what happens

Estimated time: 20 minutes


Summary of this assignment:
In this assignment, you have learnt:
x Constants
At the end of the assignment you would have the following files:
VariablesDemo.java

2.2: Operators & Typecasting


Assignment 2.2.1: Type Casting
Objective: Understand type casting
Problem Description: A Musical store wants to automate the process of calculating discount
based on the bill amount, which was done out manually.
Step 1: Use the formula as follows to get the right bill amount after discount:
billAmount = billAmount - (billAmount * ((double)discount/100))
[HINT: Use of two variable for fetching billAmount and discount.]
Compile and execute the program and you will notice that the discount calculation is taking
place correctly.

14 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Note:
The discount calculation did not happen, because the calculation
discount/100 resulted in an integer value (there is loss of the
precision part) and hence did not reflect in the output.
Step 2: Try out the same problem with the below mentioned changes to the formula
billAmount = billAmount - (billAmount * (discount/100.0))
Note:
The discount calculation did happen, because the discount is type
casted to double explicitly and hence the desired output is
obtained
Facts:
x
x

Widening conversions are allowed whereas narrowing


conversions result in compilation error
It is not possible to assign a double to a float value

Estimated time: 15 minutes


Summary of this assignment:
In this assignment, you have learnt
x Type Casting and Conversions
At the end of the assignment you would have the following files:
VariablesDemo.java

2.3: Classes and Objects


Assignment 2.3.1: Understanding the terms
Objective: Understand the terms -class, objects, state, behavior and identity
Problem Description: Fill the crossword based on the clues given
8.
9.

Jack is the name of a student- represents ________


Graduates, post graduates , day scholars and host-elites share common behavior of this
________
10. Tom is a Post Graduate student and is a topper represents _____________
11. The attribute and the activities related to a student are put as part of Student class15 | P a g e

Infosys Foundation Program

Infosys Limited

12.
13.
14.
15.
16.

Object Oriented Concepts Using Java

represents _________________
There is a student in graduation class , whose id is1001 , name Jack and attending
Operating systems course represents an __________________
The student pays fees and the calculation is done by the admin represents _______
A day scholar is a type of student represents ___________
A student can only view marks, he cannot update itrepresents ________________
I use calculateFees method , be it host-elite or day scholar represents
__________________________
8
6

1
2

Estimated time: 20 mins


Summary of this assignment:
In this assignment, you have learnt
x Object Oriented terminologies

Assignment 2.3.2: Debugging


Objective: Debug a program containing classes and objects and understand the common
programming errors
Problem Description: Consider the revised Demo class with the main method given below.
Identify the errors and debug the same to get the output as shown:
class Demo{
public static void main(String args[]){

16 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Student student;
student.setStudentId(1002);
student.setQualifyingExamMarks(68);
student.setResidentialStatus('H');
System.out.println("Student Id:"+student.studentId);
System.out.println("Qualifying marks:"+getQualifyingExamMarks());
System.out.println("Residential Status:"+getResidentialStatus());
System.out.println("Year Of Engineering:"+getYearOfEngg());
}
}

Output expected:
Student Id:1002
Qualifying Marks:68.0
Residential Status:H
Year Of Engineering:3

Note:
x
x
x

Initialization of variables before usage is important


Invocation of methods is done with the help of objects
Private access specifier is accessible only within the class where it
is declared

Estimated time: 15 minutes


Summary of this assignment:
In this assignment, you have learnt
x Debugging the common errors while creating objects
At the end of the assignment you would have the following files:
Demo.java

Assignment 2.3.3: Classes and Objects


Objective: To understand the concept of Abstract Data Type used for achieving

encapsulation and abstraction.


Problem Description:

17 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Implement the following class diagram using Java.

Student
-studentId :int
-studentType:char
+setStudentId(id:int):void
+setStudentType(type:char):void
+getStudentId():int
+getStudentType():char

Note:
x Using a class, you can create any number of objects
x For every instance variable there should be a setter and getter
method associated to it. Setter method is to set the value of the
instance variable and getter method is to return the value of the
instance variable
x studentType instance variable can have F (fresher) or L (lateral)

Step 1: Define a class Student and save it in Student.java


Step 2: Define all the member methods of Student Class
Step 3: Define a class CourseManagement with main method and save it in
CourseManagement.java
a. In the main method, assign the student details in the corresponding
temporary variables.
b. Create a reference variable with the name student.
c. Create an object of type Student and assign it to reference variable
named student.
d. Invoke the corresponding setter methods to set the instance variable
with the given values stored in temporary variables.
e. Using getter methods, display the student details.
Step 4: Compile the program, fix the errors if any
Step 5: Execute the program and verify the output
Estimated time: 30 mins
Note:
x Create a folder for storing every assignment

18 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Summary of this assignment:


In this assignment, you have learnt
x To implement ADT in Java
x To implement getter and setter methods
x To create reference variables
x To create object and pass messages
At the end of the assignment you would have the following files:
Student.java
CourseManagement.java

2.4: Understanding Java architecture


Assignment 2.4.1: Byte codes and .class files
Objective: Understand the creation of byte codes and .class files
Problem Description: Java programs are compiled to get the byte codes, which are verified
and executed by the JVM. Consider the Java program created in Assignment 2.3.3 to explore
and understand byte codes.
Perform the following steps:
Step 1: Answer the following questions:
a) How many class files do you see?
Note: Path for Class files: /<ProjectFolder>/bin/
b) How many source files (.java) do you see?
Note: Path for Java files: /<ProjectFolder>/src/
c) Try opening the .class file using TextPad/Notepad, What do you observe?
Step 2: Write the verification process for byte code
a) Open the .class file and make the modification (add a space after the last line) and
save it.
Note: The .class file can be opened in TextPad/Notepad, the content of .class file
is not in readable format
b) Without compiling execute the same program. What do you observe?
c) Compile and execute the program what is difference you could observe?
Note: Following steps can be used as an alternate way of compiling the code in
Eclipse:
o Go to ProjectMenu and click on Clean option.
o Select the current Project from the Dialog box displayed and click on OK.
19 | P a g e
Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Run the program again.

Estimated time: 15 minutes


Summary of this assignment:
In this assignment, you have learnt
x Java architecture
At the end of the assignment you would have the following files:
Student.java
CourseManagement.java

2.5: Implementation of class


Assignment 2.5.1: Class creation
Objective: Creation of a Student Class and instantiation of objects
Problem Description: The Student class with the attributes and methods is to be
implemented in Java as per the class diagram given below:

Step 1: Define the class Student as per the class diagram specified
Step 2: Define all the setter and getter methods of Student Class
Step 3: Create a class Demo with the main method

20 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

a. Create a reference variable of Student class with the name student and instantiate
the same
b. Invoke the corresponding setter methods to set the values for the instance
variables as follows:
studentId
qualifyingExamMarks

1001
95.0f

residentialStatus
yearOfEngg

D
2

c. Using the corresponding getter method, display the details as follows:


Student Id
Qualifying Marks
Residential Status
Current Year of Engineering

:___________________
:___________________
:___________________
:___________________

Step 4: List out the actual parameters, Formal Parameters, called function and
Caller function.
Estimated time: 25 minutes
Summary of this assignment: In this assignment, you have learnt
x To create a class , instantiate objects , invoke methods using an object
x The parameters in the methods are invoked using pass by value technique
x To compile and execute a Java program
At the end of the assignment you would have the following files:
Student.java
Demo.java

2.6: References and objects


Assignment 2.6.1: Pass By Value and reference
Objective: Understand passing of primitive and abstract data types.
Problem Description: To write a code to understand pass by value and passing reference
objects.
21 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Step 1: Consider the program given below:


public class PassByVal {
public static void main (String args[]){
int sId = 25;
PassByVal val = new PassByVal();
System.out.println(sId);
val.passTheValueMethod(sId);
System.out.println("The sId are" + sId);
}
public void passTheValueMethod(int sId){
sId = 10;
System.out.println("The sId are" + sId);
}
}
Step 2: Write the necessary code in above given program and compile it.
Step 3: After successful compilation of the program, execute it. Supply the necessary values
and observe the output.
Note: There is no change in the student Id of the student. Why?
Step 5: Enhance this code by passing the object of Student class (created in earlier
Assignment 2.5.1) to the method passTheValueMethod().Change the value of Student Id and
display the Student Id of the student.
Note: There is a change in the Student Id. Why?
Estimated time: 20 minutes
Summary of this assignment:
In this assignment, you have learnt
x Pass by value and Pass by reference
At the end of the assignment you would have the following files:
Student.java
PassByVal.java

Assignment 2.6.2: Object Passing by reference


Objective: Understand the concept and passing of references to methods.
22 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Problem Description: At an airport, a traveller is allowed entry into the flight only if he
clears the following checks
i.
Baggage Check
ii.
Immigration Check
iii.
Security Check
The design for the scenario is provided below:

Traveller
-travellerId:int
-baggageAmount:int
-expiryYear:int
-nocStatus:boolean
+setTravellerId(int):void
+setBaggageAmount(int):void
+setExpiryYear(int): void
+setnocStatus(boolean):void
+getTravellerId():int
+getBaggageAmount():int
+getExpiryYear():int
+getNocStatus():boolean

Demo
+main(String args[]):void static

Checks
+checkBaggage(Traveller):boolean
+checkImmigration(Traveller):boolean
+checkSecurity(Traveller):boolean

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

Check if baggageAmount is greater than or equal to 0 and less than or equal to 40.
If baggageAmount is VALID
return TRUE
else
return FALSE

23 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

checkImmigration(Traveller):boolean
x

Check if expiryYear is greater than or equal to 2001 and less than or equal to 2025.
If expiryYear is VALID
return TRUE
else
return FALSE

checkSecurity(Traveller):boolean
If nocStatus is TRUE
return TRUE
else
return FALSE
main(String args[]):void static
In main method, create the object of class Traveller and initialize the values according to the
following table:
Variable
travellerId
baggageAmount
expiryDate
nocStatus

Value
1001
35
2019
true

The created object with the values initialized as above will be passed as an argument to the
checkBaggage(), checkImmigration() and checkSecurity() menthods in the 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
x Passing objects from one method to another
x Use of references
x Pass by reference
24 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

At the end of the assignment you would have the following files:
Traveller.java
Checks.java
Demo.java

2.7: Selectional Control Structure


Assignment 2.7.1: Selectional Control Structures

Objective: Write programs to understand Control statements, Operators and Boolean data
type
Problem Description: The validation of the examination marks is to be done. The range of
exam marks is between 65 and 100 (both inclusive). This is to be done by including a validate
method in Student class.
Modify the code written in Student Class to implement selection statements using if-else and
logical operators
Modified Student class diagram:

Step 1: Modify the Student class created (Student.java) in Assignment 2.5.1 to include
the
method whose prototype is given above
Step 2: The implementation of the method is as follows:
a. validateExamMarks()
i. If the qualifyingExamMarks is greater than or equal to 65 and less than or
equal to 100, return true
ii. If not, return false
Step 3: Add the following statements to the existing main method written in Demo class
(Demo.java)
a. Invoke the validateExamMarks() method
b. If the qualifyingExamMarks are valid,
a. Display Valid Marks
25 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

b. If not valid, display Invalid marks, the range of the qualifying exam marks
is between 65 and 100
Step 4: Compile the program, fix the errors if any
Step 5: Execute the program and verify the output
Estimated time: 15 minutes
Summary of this assignment:
In this assignment, you have learnt
x Control Statements, operators and Boolean data type
At the end of the assignment you would have the following files:
Student.java
Demo.java

Assignment 2.7.2: Selectional Control Structures


Objective: Creation of a Registration Class and instantiation of objects
Problem Description: Every student has to register and pay appropriate fees at the start of
every academic year of engineering. The fees to be paid are calculated based on branch
selected and discount based on qualification marks.
Implement the following class diagram using Java.

Step 1: Create a file called Registration.java using Eclipse


Step 2: Define the class Registration as per the class diagram specified
Step 3: Define all the getter and setter methods of Registration Class

26 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Step 4: The implementation of calculateFees() method is done based on the marks which is
passed as an argument to the method. The details are given in Table 1:
Table 1:

Range of marks
85-100
75-84
65-74

Discount in %
12
7
0

i. Declare a local variable with the name discount of type integer to store the
discount identified as per the Table 1
ii. Calculate the fees(instance variable of Registration class) after giving the
discount as follows:
fees = fees - (fees * (discount/100))
Step 4: Write a class called DemoReg in a file DemoReg.java with the main method
Step 5: Create a reference variable of Registration class with the name reg and instantiate
the same
a. Invoke the corresponding setter method to set the value for the instance variable as
follows:
RegistrationId
2001
b. The fees is based on the Branch Id. Create a local variable called branchId in the main
method and initialize to 1002. The logic for calculation of fees as per Branch Id is
given in Table 2
Table 2:

branchId
1001
1002
1003
1004
1005

Fees
25575.0
15500.0
33750.0
8350.0
20500.0

Write the logic for identifying the fees based on Branch Id using a switch case.Using
the appropriate setter method, set the fees.
c. Invoke the calculateFees() with 79 as an argument for marks
d. Using the corresponding getter methods, and display the details as follows:

27 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Registration Id
Fees

:___________________
:___________________

Step 5: Compile the program and execute the program


Step 6: Notice that the value of the discount calculated is not proper. Why?
Estimated time: 30 minutes
Summary of this assignment: In this assignment, you have learnt
x To use operators and control structures to perform business logic
At the end of the assignment you would have the following files:
Registration.java
DemoReg.java

Assignment 2.7.3: Switch case statement


Objective: Understand the concept of conditional case statements using switch cases.
Problem Description: A java program needs to be written to display the range of marks based
on the grade. The table for calculation of grade is as follows:

Grade
A
B
C
D
E

Range of marks
80-100
73-79
65-72
55-64
<55

Step 1: Create a class called SwitchCase with the main method


Step 2: Create a character variable for storing the grade with a default value of B
Step 3: Write the java code to implement the calculation of grades as given in the table. If
any other grade is provided , the program must display a message Grade does not exist,for
valid grades it must display the range of marks as given in the table.
Step 4: Change the values of the grade variable and test the working of the program for all
the grades.
Estimated time: 20 minutes
Summary of this assignment:
In this assignment, you have learnt
x Switch case statements
28 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

At the end of the assignment you would have the following files:
SwitchCase.java

2.8: Iterational Control Structures


Assignment 2.8.1: Understanding loops
Objective: Understand loops
Problem Description: The code given below is written to display all the even numbers
between 50 and 80 (both inclusive). Debug the program to get the correct output.
Step 1: Type the below program in Eclipse, save the file as ForLoop.java, compile and
execute.
public class ForLoop{
public static void main(String args[]){
for(int i=50;i<80;i++){
if(i%2==0){
System.out.println(i);
}
else{
break;
}
}
}
}
Step 2: Correct the logical error in the code, save, compile and execute the code
Step 3: Implement the same logic using while loop in separate file WhileLoop.java
Estimated time: 20 minutes
Summary of this assignment:
In this assignment, you have learnt
x Usage of For loop, while loop and break statements

29 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

At the end of the assignment you would have the following files:
ForLoop.java
WhileLoop.java

30 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Assignment 2.8.2: Building logic using iterational control structures


Objective: Understand logic building through control structures.
Problem Description: A Tutorial center has opened up invitations for admissions of students
to various courses. The class diagram for the student class is given in Figure 7.
Figure 7: Class diagram for Student class
Student
-studentAge:int
-studentName:String
-optedCourse:String
-courseType:char
-payableFees:double
+getStudentAge():int
+getStudentName():String
+getOptedCourse():String
+getCourseType():char
+getPayableFees():double
+validateStudentDetails():boolean
+calculateFeesPayable():double

Implementation Details:
Modify the design to include the setter methods for each of the instance variables
validateStudentDetails()
x
x
x
x

Student age should meet the minimum age requirement of 16yrs


Student name should have minimum length of 3 and maximum of 20 characters
Courses should be either Maths, Physics, Chemistry or Computer Science
Course Type must be either L for Long Term or S for Short Term

calculateFeesPayable()
x
x

The fees for the student must be calculated using the following data in the Table 3.
If the input values are valid (invoke the validateStudentDetails),calculate the fees as
given in Table 3 and update the instance variable, payableFees
Table 3:
Course Name

31 | P a g e

Long Term

Short Term

Maths

20000

40000

Physics

15000

30000

Chemistry

16000

32000

Computer Science

22000

30000

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Create a starter called Demo. In the main method, create an object of Student class
and initialize the object with the values given in Table 4 (Use the appropriate setter
methods). Calculate the fees payable and display all the Student details by invoking
the appropriate methods.
Table 4:
Instance Variable

Value

studentAge

20

studentName

Jasmine

optedCourse

Maths

courseType

Estimated time: 30 minutes


Summary of this assignment:
In this assignment, you have learnt
o Control Structures If Else If Ladder
o Switch Case
o Do-While Loop
At the end of the assignment you would have the following files:
Student.java
Demo.java

2.9: Control statements


Assignment 2.9.1: break & continue
Objective: Understand control statements
Problem Description: To implement control flow statements break and continue
Step 1: Type the below programs in the Eclipse IDE, save, compile and execute
Program 1:
//Program to understand the loop and break
class Control{
public static void main(String args[]){
boolean bool = true;
32 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

for(int i= 0; i<5 ; i++){


for(int j = 0; j<10; j++){
System.out.print(j +"\t");
if(j > 5){
break;
}
}
System.out.println("Outer Loop");
}
System.out.println("End");
}
}

Program 2:
//Program to understand the loop and continue
class ControlContinue{
public static void main(String args[]){
boolean bool = true;
for(int i= 0; i<5 ; i++){
for(int j = 0; j<10; j++){
System.out.print(j +"\t");
if(j > 5){
System.out.println();
continue;
}
}
System.out.println("Outer Loop");
}
System.out.println("End");
}
}

33 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Note:
x You cant use a number or anything that does not evaluate to a
Boolean value as a condition in selection / iteration statement
x

You can use break inside a looping statement without including if


construct.

Estimated time: 15 mins


Summary of this assignment:
In this assignment, you have learnt
x To use break and continue with the looping statement.
At the end of the assignment you would have the following files:
Control.java
ControlContinue.java

2.10: this reference


Assignment 2.10.1: Usage of this keyword
Objective: To understand the usage of this keyword.
Problem Description: Implement the following class diagram using Java.
Student
-studentId : int
-studentType:char
+Student()
+setStudentId(studentId:int):void
+setStudentType(type:char):void
+getStudentId():int
+getStudentType():char

Step 1: Modify the method setStudentId(int studentId) as below


setStudentId(int studentId){
/* assigning studentId to the current objects instance variable
studentId*/
this.studentId = studentId;
}
34 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Step 2: Save and Compile the program, fix the errors if any
Step 3: Execute the program and verify the output
Estimated time: 15 mins
Summary of this assignment:
In this assignment, you have learnt
x To use this keyword
At the end of the assignment you would have the following files:
Student.java

Assignment 2.10.2: Usage of this keyword


Objective: Understand the usage of this keyword.
Problem Description:
Implement the class diagram Using Java
Student
-studentId : int
-studentType:char
-studentName:String
+Student()
+Student(char sType,String fname,String lname)
+displayDetails(Student):void

Step 1: Define a class Student ,


x Define two constructors
o Default constructor: Used to increment the value of studentId for each
objects of Student class. studentId should start from 550.
o Parameterized constructor:
Constructor with three arguments
StudentType(H/D),firstName and lastName
studentName=firstName+lastName
o displayDetails (Student obj):Should accept the object as an argument
and display the details like studentId, studentType, studentName of that
object
Step 2: Define a main method ,
x In the main method
35 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Create an object of Student(D,Bony,Thomas) and assign it to


reference variable studentOne;
o Call the displayDetails() method and display the details of studentOne
o Create an object of Student(H,Dinil,Bose) and assign it to
reference variable studentTwo;
o Call the displayDetails() method and display the details of studentTwo
Step 3: Compile the program, fix the errors if any
Step 4: Execute the program and verify the output
o

Estimated time: 20 mins


Summary of this assignment:
In this assignment, you have learnt
x To use this keyword, passing object to an argument and Overloaded
constructors
At the end of the assignment you would have the following files:
Student.java

Assignment 2.10.3: Debugging this reference


Objective: Understand usage of this reference to resolve instance variable hiding
Problem Description: Debug the below given code to get the output shown below after the
code.
class Registration{
private int registrationId;
public void setRegistrationId(int registrationId){
registrationId=registrationId;
}
public int getRegistrationId(){
return registrationId;
}
}
class Demo{
public static void main(String args[]){
Registration reg = new Registration();
36 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

reg.setRegistrationId(1001);
System.out.println("Registration Id:"+
reg.getRegistrationId());
}
}
Step 2: Correct the logical error in the code, save, compile and execute the code to get the
below output
Output Expected:
Registration Id: 1001

Estimated time: 10 minutes


Summary of this assignment:
In this assignment, you have learnt
x Usage of this reference for resolving the ambiguity between instance variables and
local variables (instance variable hiding)
At the end of the assignment you would have the following files:
Registration.java
Demo.java

2.11: Constructor
Assignment 2.11.1: Default Constructor
Objective: To understand the concept of Default Constructor.
Problem Description:
Enhance the Assignment 2.5.1 and do the necessary modification as mentioned below:

37 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Student
-studentId : int
-studentType:char
+Student()
+setStudentId(id:int):void
+setStudentType(type:char):void
+getStudentId():int
+getStudentType():char

Step 1: Define constructor in Student class


Student (): initialize the instance variables with 10 and F (indicating
Fresher) respectively
Step 3: Define a main method
a. In the main method, create a reference variable with the name
student.
b. Create an object of type Student and assign it to reference variable
named student.
c. Using getter methods, display the student details.
Step 4: Compile the program, fix the errors if any
Step 5: Execute the program and verify the output
Estimated time: 15 mins
Summary of this assignment:
In this assignment, you have learnt
x To implement default constructor
x To use the constructor for initializing the objects
At the end of the assignment you would have the following files:
Student.java

Assignment 2.11.2: Default and Parameterized Constructors


Objective: Understand the concept and working of default and parameterized constructor.
Problem Description: Create a class called UserType and create a default and a
parameterized constructor. Invoke these constructors through two different objects of the
UserType class.
public class UserType {
38 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

String name;
UserType(String parameterVal)
{
name = parameterVal;
}
UserType()
{
this("student");
}
public static void main(String args[]) {
UserType usertype1 = new UserType("Faculty");
UserType usertype2 = new UserType();
System.out.println(usertype1.name);
System.out.println(usertype2.name);
}
}
Estimated time: 15 minutes
Summary of this assignment:
In this assignment, you have learnt about
x Default and Parameterized constructors
At the end of the assignment you would have the following files:
UserType.java

Assignment 2.11.3: Default and Parameterized Constructors


Objective: Understand Constructors in Java
Problem Description: The new metro rail service is planning to automate the generation of
tickets .This would be done when the customer presses a specific key on an automated
machine available in the railway stations. The tickets are generated for a preset start point
and preset end point of travel location. The class diagram is given in Figure 3.
Figure 3: Class diagram for Ticket class

39 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Ticket
-startPoint:int
-endPoint:int
-ticketAmount:int
+Ticket()
+Ticket(int,int)
+getStartPoint():int
+getEndPoint():int
+getTicketAmount():int
+validateTravelPoints():boolean
+calculateTicketAmt():void

Implementation Details:
x

validateTravelPoints() is written to satisfy the following criteria:o endPoint and startPoint must be greater than 0
o endPoint must always be greater than startPoint

calculateTicketAmt ()
o The ticket amount is calculated by the following formula:
o (endpoint startPoint) * 20
o The value is stored in the variable ticketAmount

x
x

The preset endPoint and startPoint are 18 and 2 respectively.


Create a starter class called Demo in Demo.java file. In the main method create
the objects as given below:
o Ticket newTicket=new Ticket();
o Ticket newTicket=new Ticket(18,1);
o Ticket newTicket=new Ticket(2,18);
o If the travel points are valid, calculate the ticket amount by invoking
the appropriate methods.
o At the end of each calculation, display the amount of money to be paid
and observe the changes.

Estimated time: 30 minutes


Summary of this assignment:
In this assignment, you have learnt
x Implementation of a given class diagram
x Default Constructor
x Parameterized Constructor
x Constructor Overloading
x Condition constructs

40 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

At the end of the assignment you would have the following files:
Ticket.java
Demo.java

2.12: Static keyword


Assignment 2.12.1: Static variable, block and method
Objective: To understand the static variable, static block and static method
Problem Description:
Modify the Assignment 2.11.1 to get the total number of student objects
Static variable and static method:
Step 1: Add static data member studentCount to store the total number of
student objects of type Student
Step 2: Add static member method getStudentCount () to return the
studentCount.
Step 3: In default constructor Student(), Increment the studentCount by 1 and assign
studentId = studentCount;
Static block:
Step 4: Assign studentCount = 10 (as already 10 students have enrolled)
Step 5: Save and Compile the program, fix the errors if any
Step 6: Execute the program and verify the output
Estimated time: 20 mins
Summary of this assignment:
In this assignment, you have learnt
x To use static variable, method and block
At the end of the assignment you would have the following files:
Student.java

Assignment 2.12.2: Default Constructor and static keyword


Objective: Understand default constructor
41 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Problem Description: Constructors can be redefined by the programmer to perform


initialization of instance variables and static variables of a class. Implement the default
constructor for the Student class.
Modify the Student class created (Student.java) in Assignment 2.5.1 to add the following
mentioned in the class diagram:

Step 1: Modify the Student class created (Student.java) in Assignment 2.5.1 to include the
default constructor

Step 2: Include the static variable in the class


Step 3: Initialize the counter to 1000 (Hint: you may use a static block for this)
Step 4: Increment the value for counter by one and initialize the value of Student Id.
Step 5: Define a static method getStudentCount() which returns the number of students
enrolled.(Hint: Use the static variable)
Step 6: In the existing Demo class (Demo.java)
a. Invoke the corresponding setter methods to set the values for the instance
variables as follows(studentOne):
Table 6

42 | P a g e

studentName

Johan

qualifyingExamMarks
residentialStatus

95.0f
D

yearOfEngg
branchName

2
CSE
Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

b. Invoke the validateStudentName() and validateBranchName() for


studentOne object created. If the return types of both the methods are true,
i.
ii.
iii.

Invoke the validateExamMarks() method for the studentOne object.


If the qualifyingExamMarks are invalid, display Invalid marks, the
range of marks is between 65 and 100
If the qualifyingExamMarks are valid, using the corresponding getter
method in the class to display the details as follows for both the
objects:
Student Id
Student Name
Qualifying Marks
Residential Status
Current Year of Engineering
Branch Name

:___________________
:___________________
:___________________
:___________________
:____________________
:____________________

c. Invoke the corresponding setter methods to set the values for the instance
variables as follows(studentTwo):
studentName
qualifyingExamMarks
residentialStatus
yearOfEngg
branchName

James
73.0f
D
1
MECH

d. Repeat Step 5.c for studentTwo


Step 7: Display the total number of students enrolled
Total number of students
:____________________
Step 8: Compile the program, fix the errors if any
Step 9: Execute the program and verify the output. Did you notice that the studentId is
incremented by one for each of the objects created? Can the studentId be made static? If
yes, why? If not, Why?
Estimated time: 35 minutes
43 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Summary of this assignment:


In this assignment, you have learnt
x Default constructor
x Static block , static keyword and auto-generation
At the end of the assignment you would have the following files:
Student.java
Demo.java

Topic 3: Coding Standards & Industry Best Practices


3.1: Optimization of Code
Assignment 3.1.1: Optimization of Code
Objective: Understand simple code optimization techniques
Background: There are several code tuning techniques, which if used while coding can
improve the performance of the code.
Estimated time: 60 minutes
Problem: Modify the codes given using the specified code tuning technique
i.

Code tuning technique: Constant folding and propagation

Description: It replaces expressions consisting of constants (e.g., "3 + 5") with their final
values ("8") and thus saves time during execution

44 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

import java.util.Random;
class CFP {
public static void main(String[] args) {
final int Num1 = 30;
int Num2 = 9 - Num1 / 5;
int Num3;
Random random = new Random();
Num3 = Num2 * random.nextInt(100);
if (Num3 > 100) {
Num3 = Num3 - 100;
System.out.println("Number 3 Changed");
}
System.out.println("Number 1 :" + Num1);
System.out.println("Number 2 :" + Num2);
System.out.println("Number 3 :" + Num3);
}
}

Code tuning technique: Common Sub-expression elimination

ii.

Description: It searches for instances of identical expressions (i.e., they all evaluate to
the same value), and analyses whether it is worthwhile replacing them with a single
variable holding the computed value
import java.util.Random;
class CSE {
public static void main(String[] args) {
int Num1,Num2 ,Num3 ,Num4 = 0,Num5 = 0;
Random random = new Random();
Num1 = random.nextInt(100);
Num2 = random.nextInt(100);
Num3 = random.nextInt(100);
Num4 = Num1 * Num2 + Num3;
Num5 = Num1 * Num2 * Num4;
System.out.println("Number 1 :" + Num1);
System.out.println("Number 2 :" + Num2);
System.out.println("Number 3 :" + Num3);
System.out.println("Number 4 :" + Num4);
System.out.println("Number 5 :" + Num5);
}
}
45 | P a g e

Infosys Foundation Program

Infosys Limited

iii.

Object Oriented Concepts Using Java

Code tuning technique: Dead Store elimination

Description: It removes assignments to variables that are not subsequently read, either
because the lifetime of the variable ends or because of a subsequent assignment that will
overwrite the first value.
import java.util.Random;
class DCE {
public static void main(String[] args) {
int Num1;
int Num2 = 10;
Random random = new Random();
Num1 = random.nextInt(100);
Num1=Num1+1000;
Num1=Num1 + Num1/4;
System.out.println("Number 1 :" + Num1);
}
}

iv.

Code tuning technique: Induction variable analysis and strength reduction

Description if a variable in a loop is a simple function of the index variable, such as j


:= 4*i + 1, it can be updated appropriately to reduce strength of the expression
(multiplication can be replaced with addition)
class Induction_Variable {
public static void main(String[] args) {
int Num1;
for (Num1=0; Num1 < 10; ++Num1) {
int Num2 = 17 * Num1;
System.out.println("Number 2 is : " + Num2);
}
}
}

46 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Code tuning technique: Loop fission

v.

Description: Loop fission attempts to break a loop into multiple loops over the same
index range but each taking only a part of the loop's body. This can improve locality of
reference
class Loop_Fission {
public static void main(String[] args) {
int Count1, Num1[] = new int[100], Num2[] = new int[100];
for (Count1 = 0; Count1 < 100; Count1++){
Num1[Count1] = Count1;
Num2[Count1] = Num1[Count1];
}
System.out.println("Printing Array Num1 ");
for (Count1 = 0; Count1 < 100; Count1++){
System.out.print(Num1[Count1] + " ");
}
System.out.println();
System.out.println("Printing Array Num2 ");
for (Count1 = 0; Count1 < 100; Count1++){
System.out.print(Num2[Count1] + " ");
}
}
}

47 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

vi.

Code tuning technique: Loop fusion

Description: when two adjacent loops iterate the same number of times (whether or
not that number is known at compile time), their bodies can be combined as long as
they make no reference to each other's data.
class Loop_Fusion {
public static void main(String[] args) {
int Count1, Num1[] = new int[100];
for (Count1 = 0; Count1 < 100; Count1++)
{
Num1[Count1] = Count1;
}
for (Count1 = 0; Count1 < 100; Count1++)
{
System.out.println(Num1[Count1]);
}
}
}

vii.

Code tuning technique: Loop splitting / peeling

Description: Loop splitting attempts to simplify a loop or eliminate dependencies by


breaking it into multiple loops which have the same bodies but iterate over different
contiguous portions of the index range. A useful special case is loop peeling, which can
simplify a loop with a problematic first iteration by performing that iteration
separately before entering the loop.

48 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

class Loop_Splitting {
public static void main(String[] args) {
int index = 10;
int[] Num1 = {1,2,3,4,5,6,7,8,9,10,11};
int[] Num2 = new int[10];
for (int Count=0; Count<10; ++Count)
{
Num2[Count] = Num1[Count] + Num1[index];
index = Count;
System.out.println(Num2[Count]);
}
}
}
At the end of the assignment you would have the following files:
CFP.java
CSE.java
DCE.java
Induction_Variable.java
Loop_Fission.java
Loop_Fusion.java
Loop_Splitting.java

3.2: Coding Standards


Assignment 3.2.1: To Understand the importance of Coding Standards
Objective: To understand the importance of coding standards.
Background: Infosys follows coding standards for the programs written in order to improve
the maintainability aspect.
Problem Description:
a) A text file CodingStandards.java is provided to you in Supplied Source Code folder
within the Lab Guide folder. Identify the missing coding standards in the given source
code, correct them and execute the code. (The coding standards include
documentation, indentation, variable naming standards, proper comments, file
header, footer etc)
49 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

b) Write a program to add two numbers and display the sum as the output. Implement all
the coding standards applicable.
Estimated time: 20 minutes
Summary of this assignment:
In this assignment, you have learnt:
x To use the various coding standards to write well documented code.
At the end of the assignment you would have the following files:
CodingStandards.java

Topic 4: Arrays
4.1: Arrays
Assignment 4.1.1: Arrays
Objective: Understand the concept of Arrays
Problem Description: In Assignment 2.7.2, we had several Branch Ids related to the various
branches of engineering in the college. The fee to be paid is different for different branches.
The business logic needs to be implemented to calculate the fees based on branch by using a
data structure.
Create an array for the branch Ids and initialize them as follows:
Step 1: Open the file DemoReg.java with the main method written in Assignment 2.7.2. In
the main method, do the following:
a. Declare an integer array branchList and initialize it with the following values:
branchList 1001

1002

1003

1004

1005

b. Declare a double array fees and initialize it with the following values:
fees
50 | P a g e

25575

15500

33750

8350

20500

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Note: The branchList array and fees array are related as follows: the fees for
branchId in branchList[0] is fees[0], the fees for branchId in branchList[1] is
fees[1] and so on
c. Check whether the value of the local variable, branchId is present in the
branchList array
[Hint: make use of length property of the array]
i. If present, identify the fees for the specified branchId from the fees
array. Using the appropriate setter method, set the fees
a. Invoke the calculateFees() with 79 as an argument for marks
b. Using the corresponding getter methods,display the details as
follows:
Registration Id
Fees

:___________________
:___________________

ii. If not, display a message as Invalid branch Id


Step 2: Compile the programs Registration.java, DemoReg.java, fix the errors if any.
Step 3: Execute the program and verify the output
Estimated time: 20 minutes
Summary of this assignment:
In this assignment, you have learnt
x Declaration of an integer array, its initialization and accessing the array elements
At the end of the assignment you would have the following files:
Registration.java
DemoReg.java

4.2: Multidimensional array


Assignment 4.2.1: Multidimensional Array(Jagged Array)
Objective: Understand the concept of Jagged Array

51 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Problem Description: Write a program to implement an asymmetric two dimensional array of


Strings
Consider that the students joined a tutorial for various subjects as given below:
Table 7
Student Name
Tony
Thomas
Dinil

Tutorial1
JAVA
JAVA
Linux

Tutorial 2
C
UNIX
Oracle

Tutorial 3
C++

Delvin

RDBMS

C#

ORACLE

Step 1: Create a file JaggedArray.java with a class JaggedArray containing the main method
Step 2: Initialize the array based on the above table and display the tutorials attended by
Delvin.
Estimated time: 20
Summary of this assignment:
In this assignment, you have learnt
x Multidimensional and asymmetric two dimensional Array

Note:
x

In Java, array of strings is a single dimensional array consisting of


instances of String class

At the end of the assignment you would have the following files:
JaggedArray.java

Topic 5: Strings
5.1: String & Array of Strings
Assignment 5.1.1: Strings
52 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Objective: Write programs to understand the concept of Strings


Problem Description: The student name and the branch name details of a particular student
has to be captured and validated.
Add the following mentioned in the class diagram of the existing Student class:

Step 1: Modify the Student class created (Student.java) in Assignment 2.5.1 to include the
instance variables and the methods whose prototype is given above:
Step 2: The logic for the validateStudentName()is as follows:
a. Check if the length of the studentName is between 5 and 25(both inclusive). If
not, display a message The length of the name should be minimum 5 characters
and a maximum of 25 characters and return false. Otherwise, return true.
Step 3: The logic for the validateBranchName()is as follows:
a. Using the following table, check whether the branchName is valid. Do a case
insensitive comparison of Strings.
Table 3

branchName
CSE
ECE
EEE
MECH
Bio-Tech
If it is valid, return true, else set the value of branchName to CSE and display a
message Invalid Branch Name, set to CSE and return false.
53 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Step 4: Add the following statements to the existing main method written in Demo class
(Demo.java in Assignment 2.7.1)
Create a reference variable of Student class(or use the existing object created earlier) with
the name studentOne and instantiate the same
a. Invoke the corresponding setter methods to set the values for the instance
variables as follows:
Table 4
studentId
1001
studentName
qualifyingExamMarks

Jackson
95.0f

residentialStatus
yearOfEngg
branchName

D
2
CSE

b. Invoke the validateStudentName() and validateBranchName() methods. If the


return types of both the methods are true,
i.
ii.
iii.

Invoke the validateExamMarks() method


If the qualifyingExamMarks is invalid, display Invalid marks, the range of
marks is between 65 and 100
If the qualifyingExamMarks is valid,
Using the corresponding getter method, display the details as follows:
Student Id
Student Name
Qualifying Marks
Residential Status
Current Year of Engineering
Branch Name

:___________________
:___________________
:___________________
:___________________
:___________________
:___________________

Step 5: Compile the program, fix the errors if any


Step 6: Execute the program and verify the output
Step 7: Create reference variables of Student class with the name studentTwo and
instantiate the same

54 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

a. Invoke the corresponding setter methods to set the values for the instance
variables as follows:
Table 5
studentId
studentName

1002
Jen

qualifyingExamMarks
residentialStatus

68.0f
H

yearOfEngg
branchName

3
ABC

Repeat Step 4.b for studentTwo created in Step 7, compile and execute the program. Do you
find a difference in the output? Why?
Estimated time: 30 minutes
Summary of this assignment:
In this assignment, you have learnt
x Using String data type
At the end of the assignment you would have the following files:
Student.java
Demo.java

Assignment 5.1.2: Strings


Objective: Understand String data type
Problem Description: The permanent address and the residential address of the students
need to be captured. Implement the Address class as per the class diagram given below:

55 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Step 1: Create a file Address.java and create the Address class as shown in the class diagram
Step 2: Implement the getter and setter methods
Step 3: Create a file called DemoAddress.java and create a class called DemoAddress
containing the main method
Step 4: Create a reference variable of type Address and initialize the values of the instance
variables as given in table below using the appropriate setter methods:
Table 6

addressLine
city
zip
state

No.3,KT street
Mysore
570001
Karnataka

Step 5: Use the corresponding getter methods display the details in the following format:
Address Line
: ___________________
City
: ___________________
Zip code
: ____________________
State
: ____________________
Step 6: Compile the program, fix the errors if any
Estimated time: 20 minutes
Summary of this assignment:
In this assignment, you have learnt
x Using String data type
56 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

At the end of the assignment you would have the following files:
Address.java
DemoAddress.java

Assignment 5.1.3: Array of Strings


Objective: Understand an array of Strings
Problem Description: The Admin who is using the system has to be validated using a
username and password at the time of logging into the system. Create a login class for the
same.
Step 1: Create a class called Login in Login.java file as per the below mentioned class
diagram

Step 2: Initialize the usernames and passwords arrays with the values given below in a static
block:
Table 8
usernames admin
finance
student
passwords Admin
Finance
Student
Step 3: In the default constructor, initialize the instance variables as given:
Table 9

Instance Variable
username
password

Value to be initialized
student
Student

Step 4: Implement the validateLogin() method as below:


a. A case insensitive comparison should be made for the instance variable username
against the usernames present in the usernames array
b. A case sensitive comparison should be made for the instance variable password
against the passwords present in the passwords array and it should be the
password corresponding to the username
57 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

c. If the username and password are valid, return true


d. If not, return false
Step 6: Create a file DemoLogin.java containing a class DemoLogin which in turn has the main
method. In the main method
a. Create a reference variable of Login class with the name login
b. Invoke the validateLogin() method
i.
If the return value is true, display a message Login Successful
ii.
If not, display an error message Login Denied
Step 8: Compile and execute the code(compile the classes individually) .
Estimated time: 30 minutes
Summary of this assignment:
In this assignment, you have learnt
x To declare, initialize and use the Array of Strings
x To use equals() and equalsIgnoreCase() methods of String class
At the end of the assignment you would have the following files:
Login.java
DemoLogin.java

5.2: String Handling Functions


Assignment 5.2.1: Strings
Objective: Understand Strings and their manipulation
Problem Description: Planet one, a leading data management group has been given the task
of storing the records of their one lakh employees. The record contains an email id whose
datatype is String. The logic for validation of the email id needs to be written and hence
implement the following class EmailCheck

EmailCheck
-emailId:String
+getEmailId():String
+setEmailId(String):void
+main(String[] args):void static

58 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

The validation rules for the email id check are as follows (to be implemented in main()):
x
x
x
x

Overall Length of the email ID must be greater than 3 and less 20


The email ID must include @ followed by a minimum of 1 and maximum of 2 .
The substring before @must contain a combination of Upper case, Lower case and _
symbols.
The first letter of the Email ID must be in Upper Case

If all validations are valid,


Display Email Id is VALID!
Else,
Display <Appropriate Error Message>
x Invalid Length of email Id
x Invalid Position of Special Characters
x Invalid Combination for username
x Invalid Case of First Letter
Estimated time: 30 minutes
Note:
x

The code may be submitted as one java file.

Summary of this assignment:


In this assignment, you have learnt
x String Handling
x String Functions
At the end of the assignment you would have the following files:
EmailCheck.java

5.3: Command Line Arguments


Assignment 5.3.1: Command Line Arguments
Objective: Usage of command line arguments and integer conversion
Problem Description: The branch chosen by the student can be accepted by the program as
an argument. Implement the same using command line argument.
Use the DemoReg.java used in Assignment 2.7.2 to include command line arguments.
59 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Step 1: In the DemoReg class remove the initialization for the branchId local variable
Step 2: Accept the branch Id as a command line argument. Initialize the branch Id to the
value of the command line argument after appropriate conversion (Hint: Use
Integer.parseInt()).
Step 3: The rest of the program remains the same. Compile the programs Registration.java
and DemoReg.java and execute the code. Include the command line arguments.
Note: Follow the steps below to use the Command Line arguments to execute Java
Program in Eclipse
To pass command line arguments while, go to RunRun Configurations

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.

60 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Then select the arguments tab on the right side of the dialog box and enter the values to be
passed in the text area corresponding to the Program arguments option.

Use a space to separate the values in case more than one argument is being passed and click
on the run button to execute the code with the set of arguments passed.

61 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Estimated time: 20 minutes


Summary of this assignment: In this assignment, you have learnt
x Command line arguments and their usage

At the end of the assignment you would have the following files:
Registration.java
DemoReg.java

Topic 6: Relationships
6.1: Inheritance
Assignment 6.1.1: Relationships is a relationship
Objective: Understand the concept of is-a relationship
62 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Problem Description: Hostelite and DayScholar are two classes which inherit from the
Student class. They represent the two different kinds of Student. The class diagram is as
given below:

63 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Step 1: Create a new file Hostelite.java and define the Hostelite class which extends the
Student class as per the above class diagram
Step 2: Implement the constructor of Hostelite class and invoke the constructor of Student
class using the super keyword
Step 3: Compile the Student.java and Hostelite.java file and fix the errors if any
Step 4: Create a new file DayScholar.java and define the DayScholar class which extends the
Student class as per the above class diagram
Step 5: Implement the constructor of DayScholar class and invoke the constructor of Student
class using the super keyword
Step 6: Compile the DayScholar.java file and fix the errors if any
Step 7: Create a new file DemoInherit.java containing the DemoInherit class with the main
method
Step 8: In the main method:
a. Create a reference variable of Hostelite class and instantiate the same with the
following values using the parameterized constructor as given below
Table 12

Instance Variable
hostelName
roomNumber
roomType
studentName
qualifyingExamMarks
residentialStatus
branchName
yearOfEngg
addressLine
city
state
zip

Value to be initialized
Aaradhya
105
double
Tommy
75.6f
H
CSE
4
L-51,SriLabdhi Colony
Chennai
TamilNadu
600004

(Hint: Create reference variables of Address class whenever an address needs to be stored)

64 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

b. Invoke the validateStudentName() method. If the name is valid, invoke the


validateBranchName() and validateExamMarks() method. If both are valid,
invoke the corresponding getter methods and display the following details :
Student Id
Student Name
Qualifying Marks
Residential Status
Current Year of Engineering
Branch Name
Permanent Address
Hostel Name
Room Number
Room Type

:___________________
:___________________
:___________________
:___________________
:____________________
:____________________
:____________________
:____________________
:____________________
:____________________

c. Create a reference variable of DayScholar class and instantiate the same with the
following values:
Table 13

Instance Variable
Value to be initialized
For Residential Address
addressLine
No.3, Choultry circle
City
Mysore
state
Karnataka
Zip
570017
distance
10
studentName
Timmy
qualifyingExamMarks 80.0f
residentialStatus
D
branchName
CSE
yearOfEngg
4
For Permanent Address
addressLine
No.L-82, West Fort
City
Trivandrum
state
Kerala
Zip
560015

(Hint: Create reference variables of Address class whenever an address needs to be stored)
65 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

a. Invoke the validateStudentName() method. If the name is valid, invoke the


validateBranchName() and validateExamMarks() method. If both are valid,
invoke the corresponding getter methods and display the following details :
Student Id
Student Name
Qualifying Marks
Residential Status
Current Year of Engineering
Branch Name
Residential Address
Distance
Permanent Address

:___________________
:___________________
:___________________
:___________________
:____________________
:____________________
:____________________
:____________________
:____________________

Step 11: Compile, execute the program and verify the output
Estimated time: 50 minutes
Summary of this assignment:
In this assignment, you have learnt
x Inheritance
At the end of the assignment you would have the following files:
Student.java
Hostelite.java
DayScholar.java
Address.java
DemoInherit.java

Assignment 6.1.2: Default & Advanced Parameterized Constructor


Objective: Understand Constructors in Java
Problem Description: The firmware in the ticketing device used by the conductors in a public
transport system works on inputs from the conductor. The conductor,
x When hits a specific hotkey generates tickets from a preset start point and end
point
x When enters a start point and end point generates tickets from the corresponding
travel points

66 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Ticket
-startPoint:int
-endPoint:int
-ticketAmount:int
+Ticket()
+Ticket(int,int)
+getStartPoint():int
+getEndPoint():int
+getTicketAmount():int
+validateTravelPoints():void
+calcTicketAmt():int

The ticket amount is calculated by calcTicketAmt() and stored in ticketAmount by the


formula: (endpoint startPoint) * 10
The preset endPoint and startPoint are 9 and 3 respectively.
Create a starter class called Demo in Demo.java file. In the main method create the objects
as given below:
x Ticket newTicket=new Ticket();
x Ticket newTicket=new Ticket(10,1);
x Ticket newTicket=new Ticket(1,10);
At the end of each calculation, display the amount of money to be paid and observe the
changes.
Going ahead, ensure a validation with validateTravelPoints() with the following criteria:x endPoint and startPoint must be greater than 0
x endPoint must always be greater than startPoint
Estimated time: 40 minutes
Summary of this assignment:
In this assignment, you have learnt
x Default Constructor
x Parameterized Constructor
x Constructor Overloading
At the end of the assignment you would have the following files:
Ticket.java
Demo.java

6.2: Aggregation

67 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Assignment 6.2.1: Relationships has-a relationship


Objective: Understand has-a relationship
Problem Description: The relationship between the Student and the Address class is that of
has-a relationship. Using a java program, the relationship between the two classes can be
established by holding a reference of the Address class inside Student class as every student
has an address.

Step 1: Use the Student.java file created in Assignment 2.5.1. Modify the class by adding an
instance variable of type Address. (Use the Address class created in Assignment 5.1.2)
Step 2: Modify the parameterized constructor to add the Address reference as a parameter
and initialize the permanentAddress with the reference passed
Step 3: The definition of setPermanentAddress() and getPermanentAddress() is as given
below:
class Student{

private Address permanentAddress;


..
public void setPermanentAddress(Address address){
permanentAddress= address;
}
public Address getPermanentAddress(){
return permanentAddress;
}
..
}
Step 4: Create a file DemoConstructor.java file with the main method
class DemoConstructor{
public static void main(String args[]){
68 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Address address = new Address();


address.setAddressLine("No.333,ABC street");
address.setCity("Mysore");
address.setState("Karnataka");
address.setZip("570001");
Student studentSix = new Student();
studentSix.setPermanentAddress (address);
//Write the code for invocation of the setter methods, validate
//methods and printing the other details in the Student class as
//as per the previous assignments
address =studentSix.getPermanentAddress();
System.out.println(Address:);
System.out.println(address.getAddressLine()+,);
System.out.println(address.getCity()+,);
System.out.println(address.getState()+,);
System.out.println(address.getZip());
}
}
Step 5: Copy the Address.java file into the present working folder, compile the code.
Compile the Student.java and also compile the DemoConstructor.java program and fix errors
if any
Step 6: Execute the program and verify the output
Note:
x The reference of the Address class is placed as a member of the
Student class representing aggregation

Estimated time: 25 minutes


Summary of this assignment:
In this assignment, you have learnt
x Aggregation relationship
At the end of the assignment you would have the following files:
Student.java
Address.java
DemoConstructor.java

69 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

6.3: Association
Assignment 6.3.1: Relationships Uses a relationship
Objective: Understand the concept of Uses-A relationship
Problem Description: The relationship between Registration class and the PrintDetails class
is that of association. The calculateFees() method uses PrintDetails class for printing the
header of the bill. Implement this relationship using a Java program.
Step 1: Use the file Registration.java created in Assignment 2.7.2 and make the changes to
the calculateFees() before the calculation of fees is done
a. Create a reference variable of PrintDetails class
b. Invoke the printHeader() method of the PrintDetails class by passing a
character * to it
c. Invoke the printHeader() method of the PrintDetails class by passing a String "
Ricto Engineering College" to it
d. Invoke the printHeader() method of the PrintDetails class by passing a
character * to it
e. Display the registrationId as shown below:
Registration Id: _________________________
Step 2: The rest of the implementation of the calculateFees() method remains the same
.Compile the file Registration.java
Step 3: Use the class DemoReg created in the file DemoReg.java with the main method used
in Assignment 2.7.2. Remove the code written to display registrationId since it is now
displayed in calculateFees() of Registration class.
Step 4: Compile DemoReg.java and execute the code. Do you observe the printing of the
header? What is the relationship between the Registration and the PrintDetails class? How is it
different from aggregation?
Estimated time: 25 minutes
Summary of this assignment:
In this assignment, you have learnt
x The concept of Uses A relationship
70 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

At the end of the assignment you would have the following files:
Registration.java
PrintDetails.java
DemoReg.java

Topic 7: Polymorphism
7.1: Method overloading
Assignment 7.1.1: Method Overloading
Objective: Understand method overloading
Problem Description: The Admin wants to print the header of the bill in multiple ways
depending on the need. This can be printing a single character n, number of times or printing
of String or printing a character specified number of times.
Create a class called PrintDetails with overloaded methods as shown in the class diagram:

Step 1: Create a file called PrintDetails.java which contains the PrintDetails class designed
as per the class diagram given above.
Step 2: Implement the printHeader() methods as described below:
a. printHeader(char c)
x This method would print the character passed to it as an argument 80 times
in the same line
[Hint: make use of System.out.print() method to retain the cursor on the same line]
b. printHeader(char c, int no)
x This method would print the character passed to it as an argument the
specified number of times, which is passed as a second argument, in the
same line
c. printHeader(String s)
x This method would print the string passed to it as an argument once

71 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Step 3: Create a file DemoPrint.java containing the DemoPrint class with the main method.
Step 4: Create an object of PrintDetails class and instantiate the same. Invoke the
printHeader methods with the following values for the arguments
Table 11
Variables
c
no
s

values
*
20
Ricto Engineering College

Step 7: Compile , execute the program and verify the output


Note:
x Methods can be overloaded based on the number, sequence and type
of arguments

Estimated time: 25 minutes


Summary of this assignment:
In this assignment, you have learnt
x Method Overloading
At the end of the assignment you would have the following files:
PrintDetails.java
DemoPrint.java

7.2: Introduction to polymorphism and types


Assignment 7.2.1: Parameterized constructor and Constructor
Overloading
Objective: Understand parameterized constructor
Problem Description: Parameterized constructors can be used to initialize the instance
variables of the class. This can be done by passing arguments at the time of object creation.
72 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Modify the Student class created earlier (Student.java) to add the following mentioned in the
class diagram:

Step 1: Modify the Student class created earlier (Student.java) to include the definition for
the parameterized constructor as shown in above class diagram.
Step 2: Initialize the values of the instance variables appropriately using the values passed to
the parameterized constructor.
(Note: Ensure that the Student Id gets generated every time the default or the
parameterized constructor is called)
Step 3: Add the following statements to the existing main method written in Demo class
(Demo.java)
a. Create a reference variable of Student class with the name studentFive by
invoking the parameterized constructor of the student class by passing the
following values:
Table 10
studentName

Jimmy

qualifyingExamMarks
residentialStatus
yearOfEngg
branchName

688.0f
H
2
ECE

b. Invoke the validateStudentName() and validateBranchName() for the object


created. If the return types of both the methods are true,
i.
ii.
iii.

73 | P a g e

Invoke the validateExamMarks() method using the object created.


If the qualifyingExamMarks are invalid, display Invalid marks, the
range of marks is between 65 and 100
Else, using the corresponding getter methods in the class to display the
details as follows for the object created:

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Student Id
Student Name
Qualifying Marks
Residential Status
Current Year of Engineering
Branch Name

:___________________
:___________________
:___________________
:___________________
:____________________
:____________________

Step 6: Display the total number of students enrolled


Total number of students
:____________________
Step 7: Compile and Execute the program and verify the output. Did you notice that the
studentId is incremented by one for each of the object created? Did you also notice that
there are two versions of the constructor?
Note:
x The setter methods may be used for modification of instance variable
values
x The setter may also be used for setting the values of the instance
variables in the absence of a parameterized constructor
x Constructors can be overloaded

Estimated time: 20 minutes


Summary of this assignment:
In this assignment, you have learnt
x Parameterized Constructor
At the end of the assignment you would have the following files:
Student.java
Demo.java

Assignment7.2.2: Default & Parameterized Constructor Advanced


Objective: Understand Constructors in Java
Problem Description: The firmware in the ticketing device used by the conductors in a public
transport system works on inputs from the conductor. The conductor,
x When hits a specific hotkey generates tickets from a preset start point and end
point
74 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

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():void
+calcTicketAmt():int

The ticket amount is calculated by calcTicketAmt() and stored in ticketAmount by the


formula: (endpoint startPoint) * 10
The preset endPoint and startPoint are 9 and 3 respectively.
Create a starter class called Demo in Demo.java file. In the main method create the objects
as given below:
x Ticket newTicket=new Ticket();
x Ticket newTicket=new Ticket(10,1);
x Ticket newTicket=new Ticket(1,10);
At the end of each calculation, display the amount of money to be paid and observe the
changes.
Going ahead, ensure a validation with validateTravelPoints() with the following criteria:x endPoint and startPoint must be greater than 0
x endPoint must always be greater than startPoint
Estimated time: 40 minutes
Summary of this assignment:
In this assignment, you have learnt
x Default Constructor
x Parameterized Constructor
x Constructor Overloading
At the end of the assignment you would have the following files:
Ticket.java
Demo.java

75 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

7.3: Method Overriding


Assignment 7.3.1: Method Overriding
Objective: Understand method overriding
Problem Description: Method overriding happens when a method defined in the parent class
is redefined in the derived classes. displayStudentInformation() has to be defined in the
Student class to display student information and overridden in the derived classes (Hostelite
and DayScholar) to display the respective class details.
Step 1: Use the file Student.java, Address.java, Hostelite.java and DayScholar.java files
created earlier
Step 2: In the Student class, add a new method called displayStudentInformation() as
shown in the class diagram below:

In the displayStudentInformation(),write the logic using the getter methods of the class and
display the details as follows:

Notice how within the method, there is no need for


an object reference as the this reference is
implicitly available

public void displayStudentInformation(){


System.out.println("Student Id
: "+getStudentId());
System.out.println("StudentName
: "+getStudentName());
System.out.println("Qualifying Marks : "+getQualifyingMarks());
System.out.println("Residential status :"+getResidentialStatus());
System.out.println("Current Year Of Engg
: "+getYearOfEngg());
System.out.println("Branch Name
: "+getBranchName());
System.out.println("Address:"+getPermanentAddress().getAddressLin
e()+getPermanentAddress().getCity()+getPermanentAddress().getState()+
getPermanentAddress().getZip());
}
Notice how the getPermanentAddress() method returns a
reference of Address class, which in turn is used to invoke
a method of the Address class

76 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Step 2: Use the file Hostelite.java file created earlier, add a new method called
displayStudentInformation() as shown in the class diagram below:

In the displayStudentInformation(),invoke the displayStudentInformation() of the Student


class .Write the logic using the getter methods of the Hostelite class and display the details
as follows:
public void displayStudentInformation(){
super.displayStudentInformation();
System.out.println("Hostel Name
: "+getHostelName());
System.out.println("Room Number
: "+getRoomNumber());
System.out.println("Room Type
: "+getRoomType());
}
Step 3: Use the file DayScholar.java file created earlier, add a new method called
displayStudentInformation() as shown in the class diagram below:

In the displayStudentInformation(),invoke the displayStudentInformation() of the Student


class .Write the logic using the getter methods of the DayScholar class and display the details
as follows:
public void displayStudentInformation(){
super.displayStudentInformation();
System.out.println("Distance
: "+getDistance());
System.out.println("Residential Address
:
"+getResidentialAddress().getAddressLine()+getResidentialAddress().get
City()+getResidentialAddress().getState()+getResidentialAddress().getZ
ip());
}

77 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Step 4: Create a file DemoOverriding.java containing the DemoOverriding class with the
main method.
Step 5: Create an object each of the Hostelite and DayScholar class and instantiate them.
(Pass values for each of the instance variables through the parameterized constructor). Invoke
the displayStudentInformation() using the objects individually.
Step
6:
Compile
the
Student.java,
Hostelite.java,
DemoOverriding.java and execute the code. Verify the output.

DayScholar.java

and

Estimated time: 20 minutes


Summary of this assignment:
In this assignment, you have learnt
x Overriding of methods
At the end of the assignment you would have the following files:
Student.java
Hostelite.java
DayScholar.java
Address.java
DemoOverriding.java

7.4: Dynamic Polymorphism


Assignment 7.4.1: Dynamic Polymorphism
Objective: Understand dynamic polymorphism, implementation and applications
Problem Description: The calculation of the fees paid by a student is based on the following:
x Qualifying marks
x Hostelite or DayScholar
x Year of Engineering
x Additional fees to be paid
The calculateFees() of Registration class has to be modified based on whether the student is
a hostelite or a day scholar.
Modify the Assignment 2.7.2 to implement the above.
78 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Step 1: Use the Student.java, Hostelite.java, DayScholar.java and Address.java created


earlier
Step 2: Use the Registration.java created earlier and add the following to the Registration
class:
x A static counter variable
x Constructor of the Registration class
x Change the prototype of the calculateFees() to pass a Student reference to it
Step 2: Implementation of methods is given below:
a. In the constructor of Registration class, write the logic so that the registration
ids are autogenerated from 5001 onwards.
b. In calculateFees() method, using the Student reference passed, do the following
validations:
i.
Invoke the validateStudentName() method. If the name is valid, invoke
the validateBranchName() and validateExamMarks() method. If both
are valid, go to the next step (Step 2.c). Otherwise display appropriate
error messages and return 0
A skeleton code is given for your reference:
public void calculateFees(Student stu){
int discount=0;
if(stu.validateStudentName() ==true){
if(stu.validateBranchName() ==true){
if(stu.validateExamMarks() ==true){
if(stu.getQualifyingMarks()>=85
&& stu.getQualifyingMarks()<=100){
discount=12;
}
..
}
c. Identify the fees based on the branch name of the student using the student
reference as per the below table:
Table 14

branchName
79 | P a g e

branchFees
Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

CSE
ECE
EEE
MECH
Bio-Tech

25575
15500
33750
8350
20500

d. Identify the qualifying marks of the student (using the student reference and
getter method) and calculate the discount by declaring a local variable discount.
(In Day 2, recall that the marks was passed as an argument to the calculateFees()
). The table for your reference is as follows:
Table 15

qualifyingMarks
85-100
75-84
65-74

Discount in %
12
7
0

e. Calculate the fees(instance variable of Registration class) after giving the


discount as follows:
fees = fees - (fees * (discount/100))
f. Invoke the displayStudentInformation() method using the reference of student.
Step 3: Create a new file DemoDynamic.java with the class DemoDynamic which contains
the main method.
Step 4: In the main method:
a. Create a reference variable of Student class called studentDynamicOne and
instantiate the same to an object of Hostelite class with the following values (Use
the parameterized constructor of respective class):
Table 16

Instance Variable
hostelName
roomNumber
roomType
studentName
qualifyingExamMarks
residentialStatus
branchName
yearOfEngg
80 | P a g e

Value to be initialized
Aaradhya
105
double
Tommy
75.6f
H
CSE
4

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

addressLine
city
state
zip

L-51,SriLabdhi Colony
Chennai
TamilNadu
600004

(Hint: Create reference variables of Address class whenever an address needs to be stored)
Do you notice here that a reference variable of a parent class is instantiated with an
object of derived class. Thus a parent reference may point to an object of itself or its
child classes which is one aspect of dynamic polymorphism
b. Create a reference variable of Registration class called registrationOne . Using
this object invoke the calculateFees() by passing the studentDynamicOne as an
argument.
c. Invoke the corresponding getter method to display the fees as shown below:
Fees to be paid by the Hostelite:_________________________________
A sample skeleton of code is shown for your reference:
Notice parent reference
pointing to child class

Student studentDynamicOne=new
Hostelite("Aradhya",105,"double","Tommy",75.6f,'H',"CSE",add,4);
,"double"
Registration registrationOne=new Registration();
registrationOne.calculateFees(studentDynamicOne);
)
System.out.println("Fees for Hostelite:"+registrationOne.getFees());

d. Create another reference variable of Student class called studentDynamicTwo


and instantiate the same to an object of DayScholar class with the following
values(Use the parameterized constructor of respective class) :
Table 17

Instance Variable
Value to be initialized
For Residential Address
addressLine
No.3, Choultry circle
City
Mysore
state
Karnataka
81 | P a g e

Infosys Foundation Program

Notice
passing of
Student
reference
to calculate
-Fees()

Infosys Limited

Object Oriented Concepts Using Java

Zip
570017
distance
10
studentName
Timmy
qualifyingExamMarks 80.0f
residentialStatus
D
branchName
MECH
yearOfEngg
4
For Permanent Address
addressLine
No.L-82, West Fort
City
Trivandrum
state
Kerala
Zip
560015

(Hint: Create reference variables of Address class whenever an address needs to be stored)
e. Using this object invoke the calculateFees() by passing the studentDynamicTwo
as an argument.
f. Invoke the corresponding getter method to display the fees as shown below:
Fees to be paid by the Day Scholar:_________________________________
Step 5: Compile Registration.java and DemoDynamic.java files, execute the program and
verify the output
Estimated time: 50 minutes
Summary of this assignment:
In this assignment, you have learnt
x Dynamic polymorphism
At the end of the assignment you would have the following files:
Student.java
Hostelite.java
DayScholar.java
Registration.java
Address.java
DemoDynamic.java

82 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Topic 8: Abstract keyword and interfaces


8.1: abstract keyword
Assignment 8.1.1: abstract class and method
Objective: Understand abstract keyword for usage with class and method
Problem Description: When at least one method in a class is not complete (ie. abstract)
then, the class holding that method also needs to be declared abstract. The
displayStudentInformation() is a good candidate for abstract method, as the same
information can be accessed and displayed in the overridden method. The Student class,
therefore has to be declared abstract.
Step 1: Use the file Student.java, Address.java, Hostelite.java and DayScholar.java files
created earlier.
Step 2: Make the Student class and the displayStudentInformation() present in the class
abstract. This is needed because the Hostelite and the DayScholar classes override this
method. There is no definition to this method as shown below:
Notice the abstract method with no body
abstract class Student{
..
abstract
ract public void displayStudentInformation();
}

Step 3: Use the file Hostelite.java file created earlier. In the displayStudentInformation(),
invoke the getter methods of the Student class explicitly (remove the invocation of the
displayStudentInformation() using super ) to display the values of the instance variables of
the Student. This is followed by the display of details of the Hostelite class members as
shown below:

class Hostelite{
.
public void displayStudentInformation(){
System.out.println("Student Id

: "+getStudentId());

System.out.println("StudentName

: "+getStudentName());

System.out.println("Qualifying Marks

: "+getQualifyingMarks());

83 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

System.out.println("Residential status

:"+getResidentialStatus());

System.out.println("Current Year Of Engg

: "+getYearOfEngg());

System.out.println("Branch Name

: "+getBranchName());

System.out.println("Address:"+getPermanentAddress().getAddressLine()+ge
tPermanentAddress().getCity()+getPermanentAddress().getState()+getPerma
nentAddress().getZip());
System.out.println("Hostel Name

: "+getHostelName());

System.out.println("Room Number

: "+getRoomNumber());

System.out.println("Room Type : "+getRoomType());

}
}
Step
4:
Use
the
file
DayScholar.java
file
created
earlier.
In
the
displayStudentInformation(), invoke the getter methods of the Student class to display the
values of the instance variables of the Student. This is followed by the display of details of
the DayScholar class members
Step
6:
Compile
the
Student.java,
Hostelite.java,
DayScholar.java
and
DemoOverriding.java (created earlier) and execute the code. Verify the output. Which kind
of polymorphism is discussed here? What is the use of the displayStudentInformation() in the
Student class ?
Estimated time: 25 minutes
Summary of this assignment:
In this assignment, you have learnt
x Abstract keyword and Overriding of methods
At the end of the assignment you would have the following files:
Student.java
Hostelite.java
DayScholar.java
Address.java
DemoOverriding.java

8.2: Interfaces
Assignment 8.2.1: Interfaces
84 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Objective: Understand interfaces


Problem Description: Interfaces represent a special form of classes containing only abstract
methods. They are deployed when some generic behavior is required across many classes
(both related and unrelated). The student has to pay infrastructure and library fees along
with yearly fees. Library and Infrastructure fees are constant values. Implement the same
using an interface.
Create an interface called AdditionalFees as shown below:

Step 1: Create a file called AdditionalFees.java and create an interface AdditionalFees as


shown. Initialize the infrastructure fees to 20000.0 and library fees to 6000.0.
Step 2: Compile the file. Do you notice an AdditionalFees.class getting created?
Step 3: Use the Registration.java created in Assignment 2.7.2. Use the implements keyword
so that the Registration class implements the AdditionalFees interface and overrides the
computeAddtionalFees() as shown below:
class Registration implements AdditionalFees{
.
public double computeAdditionalFees(){
return infrastructureFees+libraryFees;
}
}

Step 3: Compile Registration.java


Step 4: Can you instantiate an object of an interface. If not, Why?
Estimated time: 25 minutes
Summary of this assignment:
In this assignment, you have learnt
85 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Interfaces

At the end of the assignment you would have the following files:
AdditionalFees.java
Registration.java

Topic 9: Packages
Assignment 9.1.1: Packages
Objective: Understand the usage of package
Problem Description: Create, compile and execute the program contained in a package and
access the data members with different access specifiers in different packages
Note: To create a new package follows the instructions below:
To create a new package, right click on the src folder in your project and select
NewPackage

Enter the package name in the dialog box and click on finish.

86 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

This would create a new package in the project explorer as shown below.

87 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

To create a new class in this package, right Click on this newly created package and create
new class SamplePackageClass following the normal process to create a class.

This would add the class in the new package as shown below.
88 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Step 1: Write the following program in Eclipse IDE


package pack1;
public class Base{
private int privateNum;
int defaultNum;
protected int protectedNum;
public int publicNum;
public Base(){
privateNum=90;
defaultNum=900;
protectedNum=9000;
publicNum=90000;
}
}

Step 2: Save the program as Base.java


Step 3: Write the following program in Eclipse

Private and default data members


package pack2;
cannot be accessed outside the
import pack1.Base;
package
class Derived extends Base{
public void disp(){
// System.out.println(privateNum);
//System.out.println(defaultNum);
System.out.println(protectedNum);
System.out.println(publicNum);
}
Note how the protected and
public data members are
}
accessed in the derived class
class Demo{
specified in another package
public static void main(String args[]){
Derived obj=new Derived();
obj.disp();
}
}
89 | P a g e
Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Step 4: Save the program as Demo.java


Estimated time: 20 minutes
Summary of this assignment:
In this assignment, you have learnt
x How to create packages, import classes from one package into another
At the end of the assignment you would have the following files:
SamplePackageClass.java
Base.java
Derived.java
Demo.java

Assignment 9.1.2: Packages for Course Registration System


Objective: Create packages for proper organization of classes
Problem Description: Organize the classes created for the case study into a package.
Step 1: Open the files Student.java, Address.java, Hostelite.java, DayScholar.java,
Registration.java, PrintDetails.java, AdditionalFees.java and add the following
statement as the first line in the file and make all the interfaces and classes as public
:
package courseRegistration;

Step 2: Open the DemoCourseRegistration.java file, add the following statement as


the first line in the file:
package Main;
import courseRegistration.*;

Step 3: Compile the DemoCourseRegistration.java and execute the program and


verify the output.
Estimated time: 25 minutes
Summary of this assignment:
90 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

In this assignment, you have learnt


x Packages
At the end of the assignment you would have the following files:
Student.java
Hostelite.java
DayScholar.java
Registration.java
Address.java
PrintDetails.java
AdditionalFees.java
DemoCourseRegistration.java

Topic 10: Analysis of algorithms


Assignment 10.1.1: Answer the questions
Objective: To recall about the algorithms and its properties.
Background: Knowledge of fundamentals of algorithms.
Problem Description: Answer the questions.
Estimated time: 30 Minutes
1.
2.
3.
4.
5.
6.

Define Algorithm. What are the Properties of algorithm?


What are the resources need to be considered during algorithm analysis?
List the importance of analysis of algorithm.
Identify the factors, why posteriori analysis of algorithms is not a better approach?
Define Order of Magnitude of an algorithm.
What is Time Complexity?

Assignment 10.1.2: Step Count


Objective: To learn how to determine the step count of a given algorithm.
Background: To determine the number of operations involved in the algorithm
Problem Description: Find the step count for the following code
91 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Estimated time: 25 Minutes


x

Find the step count of the following code segments:


a. Sum(a,n)
{
S= 0;
for (i=1;i<=n;i=i+1)
S=S+a[i]
return S
}

b. SequentialSearch(a,x,n)
{
i=n;
a [0]=x;
while(a [i]!= x) do
i = i-1
return i
}
c. Smallest(a,n)
{
small=a[1];
for(i=1;i<=n;i=i+1)
{
if(a[i] < small)
{
small=a[i];
}
}
return small;
}
Summary of this assignment:
In this assignment, you have learnt
x Determining the step count for an algorithm

Assignment 10.1.3: Time Complexity


Objective: To learn how to determine the amount of time a given algorithm would consume.
Background: To determine the time Complexity
Problem Description: Find the order of time complexity for the following code snippets and
represent it in Big O notation.
92 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Estimated time: 50 Minutes


x

Find the time complexity for the following code segments:


d.
for(iCount=0;iCount<n; iCount =iCount+1){

}
e. for(iCount=0;iCount<iNum; iCount=iCount+2){

}
f. for(iCount=1;iCount<iNum; iCount=iCount*2){

}
g. for(iCount=iNum; iCount>iNum; iCount =iCount-1){

}
h. for(iCount1=0;iCount1<iNum;iCount1= iCount1+1){
for(iCount2=0;iCount2<iNum;iCount2= iCount2+1)
{
..
}
}
i. for(iCount1=0;iCount1<iNum;iCount1= iCount1+1)
{
for(iCount2=1;iCount2<=iCount1;iCount2= iCount2+1)
{

}
}

j. for(iCount1=0;iCount1<iNum;iCount1= iCount1+1)
{
for(iCount2=0; iCount2<iNum; iCount2= iCount2+2)
{

}
}
k. for(iCount1=0;iCount1<iNum;iCount1= iCount1+1)
93 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

{
for(iCount2=1;iCount2<n;iCount2=iCount2*2)
{

}
}
l. for(iCount1=0;iCount1<iNum;iCount1= iCount1+1)
{
for(iCount2=iNum; iCount2>0; iCount2= iCount2/2)
{

}
}
m. if(An array A of size n is sorted)
{
for(iCount=0;iCount<iNum; iCount =iCount+1)
{

}
}
else {
for(iCount=0;iCount<iNum/2;iCount= iCount+1)
{

}
}
n. if(iSum < iTotalAmount)
{
for(iCount=0;iCount<iNum;iCount= iCount+1)
{

}
}
else {
for(iCount=0;iCount<iNum/2;iCount= iCount+1)
{

}
}
Summary of this assignment:
In this assignment, you have learnt
x Determining time complexity using Step count
94 | P a g e
Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Assignment 10.1.4: Identifying time complexity of well-known


algorithms
Objective: To understand how to calculate the worst case time complexity of well-known
algorithms.
Background: This assignment helps you to understand how to identify the time complexity for
search and sort techniques.
Problem Description:
1. Linear search is a well-known search algorithm to search key element in a given list of
elements. The linear search is applied on the set of items that are not arranged in any
particular order. In linear search, the searching process starts from the first item. The
searching is continued till either the item is found or the end of the list is reached
indicating the item is not found. The items in the list are assumed to be unique. The
algorithm can be expressed as below.(Consider n as the total number of elements in the
list)
Begin
for (i = 1,i<=n; i=i+1)
If (target = a[i]) then
End with output as i
End For
End with output as none
Identify the worst case time complexity for above search algorithm and express in the form of
Big Oh notation.
2. Bubble Sort is a well-known algorithm for sorting the elements in a specific order. The
algorithm can be expressed as below. (Consider aiNum as an integer array and num as the
total number of elements in the array need to be sorted
for iNum1 = 1 to num-1
sorted = true
for iNum2 = 0 to num-1-iNum1
if aiNum [iNum2] > aiNum [iNum2+1]
temp = aiNum [iNum2]
aiNum [iNum2] = aiNum [iNum2+1]
aiNum [iNum2+1] = temp
sorted = false
end for
if sorted
break from iNum1 loop
end for
95 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Estimated Time: 10 2 = 20 Minutes


Summary of this assignment: In this assignment, we learn how to get the worst case time
complexity of well-known algorithms.

Topic 11: Code tuning techniques


Assignment 11.1.1: Usage of Code Tuning Techniques (1)
Objective: To understand the usage of code tuning techniques.
Problem Description:
Analyze the following code snippet and tune the code snippet wherever necessary.
Note: For all the assignments on code tuning techniques, the tuned code can be submitted in
a .txt file.
iNum=1;
while(iNum<= iX/2)
{
afSal[iNum] = 1.5* afSal[iNum];
iNum=iNum+1;
}
Estimated time: 15 minutes
Summary of this assignment:
In this assignment, you have learnt:
Usage of code tuning techniques - Minimize work performed inside Loops

Assignment 11.1.2: Usage of Code Tuning Techniques (2)


Objective: To understand the usage of code tuning techniques.
Problem Description:
Analyze the following code snippet and tune the code snippet wherever necessary.
Note: For all the assignments on code tuning techniques, the tuned code can be submitted in
a .txt file.
for(iNum=1; iNum <=iTotal; iNum++) {
afCommission[iNum] = iNum* fRevenue* fBaseCommission * fDiscount;
}
96 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

Estimated time: 15 minutes


Summary of this assignment:
In this assignment, you have learnt:
Usage of code tuning techniques - Minimize work performed inside Loops

Assignment 11.1.3: Usage of Code Tuning Techniques (3)


Objective: To understand the usage of code tuning techniques.
Problem Description:
Analyze the following code snippet and tune the code snippet wherever necessary.
Note: For all the assignments on code tuning techniques, the tuned code can be submitted in
a .txt file.
for( iNum=2;iNum<10;iNum++){
aiArr[1]=10;
aiArr[iNum]=iNum*aiArr[iNum-1];
}
Estimated time: 15 minutes
Summary of this assignment:
In this assignment, you have learnt:
Usage of code tuning techniques - Minimize array references

Assignment 11.1.4: Usage of Code Tuning Techniques (4)


Objective: To understand the usage of code tuning techniques.
Problem Description:
Analyze the following code snippet and tune the code snippet wherever necessary.
Note: For all the assignments on code tuning techniques, the tuned code can be submitted in
a .txt file.
iNum = 10;
for(iIndex=0;iIndex<10;iIndex++){
if(iNum>20)
System.out.println(iNum + is greater than 20);
else
System.out.println(iNum +%d is less than or equal to 20);
--------------------97 | P a g e

Infosys Foundation Program

Infosys Limited

Object Oriented Concepts Using Java

--------------------}
Estimated time: 15 minutes
Summary of this assignment:
In this assignment, you have learnt:
Usage of code tuning techniques - Unswitching of loops

98 | P a g e

Infosys Foundation Program

You might also like