oocusingjava lab guide v3
TRANSCRIPT
-
8/9/2019 OOCUsingJava Lab Guide V3
1/99
CONFIDENTIAL
Object Oriented Concepts using Java Lab Guide
-
8/9/2019 OOCUsingJava Lab Guide V3
2/99
Infosys Limited Object Oriented Concepts Using Java
1 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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 personthey 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 DepartmentInfosys LimitedElectronic CityHosur RoadBangalore - 560 100, India.
Tel: 91 80 2852 0261Fax: 91 80 2852 0362www.infosys.com
mailto:E&[email protected]
-
8/9/2019 OOCUsingJava Lab Guide V3
3/99
Infosys Limited Object Oriented Concepts Using Java
2 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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 OOCONCEPTS ............................................................................. 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
-
8/9/2019 OOCUsingJava Lab Guide V3
4/99
Infosys Limited Object Oriented Concepts Using Java
3 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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 THISKEYWORD .......................................................................... 34
ASSIGNMENT 2.10.2:USAGE OF THISKEYWORD .......................................................................... 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
-
8/9/2019 OOCUsingJava Lab Guide V3
5/99
Infosys Limited Object Oriented Concepts Using Java
4 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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 ARELATIONSHIP .................................................................. 62
ASSIGNMENT 6.1.2:DEFAULT &ADVANCED PARAMETERIZED CONSTRUCTOR................................................ 66
6.2: AGGREGATION ..................................................................................................... 67
ASSIGNMENT 6.2.1:RELATIONSHIPS HAS-ARELATIONSHIP............................................................... 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 .............................................................................................. 86ASSIGNMENT 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
-
8/9/2019 OOCUsingJava Lab Guide V3
6/99
Infosys Limited Object Oriented Concepts Using Java
5 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
TOPIC 11: CODE TUNING TECHNIQUES ............................................................................. 96
ASSIGNMENT 11.1.1:USAGE OF CODE TUNING TECHNIQUES (1) ......................................................... 96
ASSIGNMENT 11.1.2:USAGE OF CODE TUNING TECHNIQUES (2) ......................................................... 96
ASSIGNMENT 11.1.3:USAGE OF CODE TUNING TECHNIQUES (3) ......................................................... 97
ASSIGNMENT 11.1.4:USAGE OF CODE TUNING TECHNIQUES (4) ......................................................... 97
-
8/9/2019 OOCUsingJava Lab Guide V3
7/99
Infosys Limited Object Oriented Concepts Using Java
6 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
ContextThis document contains Practice Questions to be completed as a part of the practice session
for module Introduction to Object Oriented Programming.
Guidelines 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 collegewants an automated system to replace its manual system for the purpose of registration ofstudents to branches and calculation of fees for each year. The engineering college providesgraduation 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 thestudents. The student has to register every year for the next academic year. The Admin takescare of the yearly registration of the students and the calculation of yearly fees. The systemneeds 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
-
8/9/2019 OOCUsingJava Lab Guide V3
8/99
-
8/9/2019 OOCUsingJava Lab Guide V3
9/99
Infosys Limited Object Oriented Concepts Using Java
8 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
Estimated time: 25 minutes
Summary of this assignment:
In this assignment, you have learnt
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 andpurchases the item.
Identify the system, actors, use cases and the relationship
Draw use case diagram
Note:
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
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 ofcollecting 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/9/2019 OOCUsingJava Lab Guide V3
10/99
Infosys Limited Object Oriented Concepts Using Java
9 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
Customers approach the Dispatchers1at 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 Recipientsaddress, 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:
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
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 .
1Dispatcher:The person who dispatches shipments in a postal organization or courier company.
-
8/9/2019 OOCUsingJava Lab Guide V3
11/99
Infosys Limited Object Oriented Concepts Using Java
10 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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
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 _____________
-
8/9/2019 OOCUsingJava Lab Guide V3
12/99
Infosys Limited Object Oriented Concepts Using Java
11 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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
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
-
8/9/2019 OOCUsingJava Lab Guide V3
13/99
Infosys Limited Object Oriented Concepts Using Java
12 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
7. The attributes and activities of an employee can be bundled into a
__________
Estimated time: 10 minutes
Summary of this assignment:
In this assignment, you have learnt
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,charetc).
Note:A java file VariablesDemo.javais provided to you in Supplied Source Code folder within
the Lab Guide folder.
6
1
2
7
3
5
4
-
8/9/2019 OOCUsingJava Lab Guide V3
14/99
Infosys Limited Object Oriented Concepts Using Java
13 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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.Nowcopy
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 intto store the
Employee id. Similarly declare the variable for storing gender, basic salary and allowances.
Variable Name Datatype
Gender char
Allowances float
basicSalary 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 Nfor 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:
Variable declarations
Datatypes
At the end of the assignment you would have the following files:
Assignment 2.1.2: Understanding Constants
Objective: To define constant variable and print the same.
VariablesDemo.java
-
8/9/2019 OOCUsingJava Lab Guide V3
15/99
Infosys Limited Object Oriented Concepts Using Java
14 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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:
Constants
At the end of the assignment you would have the following files:
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.
VariablesDemo.java
-
8/9/2019 OOCUsingJava Lab Guide V3
16/99
Infosys Limited Object Oriented Concepts Using Java
15 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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:
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
Type Casting and Conversions
At the end of the assignment you would have the following files:
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. Jack is the name of a student- represents ________
9. 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 class-
VariablesDemo.java
-
8/9/2019 OOCUsingJava Lab Guide V3
17/99
Infosys Limited Object Oriented Concepts Using Java
16 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
represents _________________
12. There is a student in graduation class , whose id is1001 , name Jack and attending
Operating systems course represents an __________________
13. The student pays fees and the calculation is done by the admin represents _______
14. A day scholar is a type of student represents ___________
15. A student can only view marks, he cannot update itrepresents ________________16. I use calculateFees method , be it host-elite or day scholar represents
__________________________
Estimated time: 20 mins
Summary of this assignment:
In this assignment, you have learnt
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[]){
8
6
1
2
7
3
9
4
5
-
8/9/2019 OOCUsingJava Lab Guide V3
18/99
Infosys Limited Object Oriented Concepts Using Java
17 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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:
Note:
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
Debugging the common errors while creating objects
At the end of the assignment you would have the following files:
Assignment 2.3.3: Classes and ObjectsObjective:To understand the concept of Abstract Data Type used for achievingencapsulation and abstraction.
Problem Description:
Demo.java
Student Id:1002
Qualifying Marks:68.0Residential Status:H
Year Of Engineering:3
-
8/9/2019 OOCUsingJava Lab Guide V3
19/99
Infosys Limited Object Oriented Concepts Using Java
18 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
Implement the following class diagram using Java.
Note:
Using a class, you can create any number of objects 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
studentType instance variable can have F (fresher) or L (lateral)
Step 1: Define a class Student and save it in Student.javaStep 2:Define all the member methods of Student ClassStep 3: Define a class CourseManagement with main method and save it in
CourseManagement.javaa. 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 Studentand 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 studentdetails.
Step 4: Compile the program, fix the errors if anyStep 5: Execute the program and verify the output
Estimated time: 30 mins
Note:
Create a folder for storing every assignment
Student
-studentId :int-studentType:char
+setStudentId(id:int):void
+setStudentType(type:char):void
+getStudentId():int
+getStudentType():char
-
8/9/2019 OOCUsingJava Lab Guide V3
20/99
Infosys Limited Object Oriented Concepts Using Java
19 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
Summary of this assignment:In this assignment, you have learnt
To implement ADT in Java
To implement getter and setter methods
To create reference variables
To create object and pass messages
At the end of the assignment you would have the following files:
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: //bin/
b) How many source files (.java) do you see?
Note:Path for Java files: //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 formatb) 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.
Student.java
CourseManagement.java
-
8/9/2019 OOCUsingJava Lab Guide V3
21/99
Infosys Limited Object Oriented Concepts Using Java
20 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
o Run the program again.
Estimated time: 15 minutes
Summary of this assignment:
In this assignment, you have learnt
Java architecture
At the end of the assignment you would have the following files:
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 Studentas per the class diagram specified
Step 2:Define all the setter and getter methods of Student Class
Step 3: Create a class Demowith the main method
Student.java
CourseManagement.java
-
8/9/2019 OOCUsingJava Lab Guide V3
22/99
-
8/9/2019 OOCUsingJava Lab Guide V3
23/99
Infosys Limited Object Oriented Concepts Using Java
22 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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 anddisplay 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
Pass by value and Pass by reference
At the end of the assignment you would have the following files:
Assignment 2.6.2: Object Passing by referenceObjective:Understand the concept and passing of references to methods.
Student.java
PassByVal.java
-
8/9/2019 OOCUsingJava Lab Guide V3
24/99
Infosys Limited Object Oriented Concepts Using Java
23 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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
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
Check if baggageAmount is greater than or equal to 0 and less than or equal to 40.
If baggageAmountis VALID
return TRUE
else
return FALSE
Demo
+main(String args[]):void static
Checks
+checkBaggage(Traveller):boolean
+checkImmigration(Traveller):boolean+checkSecurity(Traveller):boolean
-
8/9/2019 OOCUsingJava Lab Guide V3
25/99
Infosys Limited Object Oriented Concepts Using Java
24 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
checkImmigration(Traveller):boolean
Check if expiryYear is greater than or equal to 2001 and less than or equal to 2025.
If expiryYearis VALIDreturn TRUE
else
return FALSE
checkSecurity(Traveller):boolean
If nocStatusis TRUE
return TRUE
else
return FALSE
main(String args[]):void static
In main method, create the object of classTraveller and initialize the values according to the
following table:
Variable Value
travellerId 1001
baggageAmount 35
expiryDate 2019
nocStatus true
The created object with the values initialized as above will be passed as an argument to thecheckBaggage(), 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
Passing objects from one method to another
Use of references
Pass by reference
-
8/9/2019 OOCUsingJava Lab Guide V3
26/99
Infosys Limited Object Oriented Concepts Using Java
25 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
At the end of the assignment you would have the following files:
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 validationof 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 Studentclass 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, returnfalseStep 3: Add the following statements to the existing main method written in Demo class
(Demo.java)
a. Invoke the validateExamMarks()method
b. If the qualifyingExamMarksare valid,
a. Display Valid Marks
Traveller.java
Checks.java
Demo.java
-
8/9/2019 OOCUsingJava Lab Guide V3
27/99
Infosys Limited Object Oriented Concepts Using Java
26 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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
Control Statements, operators and Boolean data type
At the end of the assignment you would have the following files:
Assignment 2.7.2: Selectional Control StructuresObjective: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 Registrationas per the class diagram specified
Step 3:Define all the getter and setter methods of Registration Class
Student.java
Demo.java
-
8/9/2019 OOCUsingJava Lab Guide V3
28/99
Infosys Limited Object Oriented Concepts Using Java
27 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
Step 4: The implementation of calculateFees()method is done based on the marks which is
passed as an argument to the method. The details are given in Table 1:
Table 1:
Range of marks Discount in %
85-100 12
75-84 7
65-74 0
i. Declare a local variable with the name discount of type integer to store the
discount identified as per the Table 1
ii. Calculate the fees(instance variable of Registration class) after giving the
discount as follows:
fees=fees - (fees* (discount/100))
Step 4: Write a class called DemoReg in a file DemoReg.javawith the main method
Step 5: Create a reference variable of Registrationclass with the name regand 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 branchIdin the mainmethod and initialize to 1002. The logic for calculation of fees as per Branch Id is
given in Table 2
Table 2:
branchId Fees
1001 25575.0
1002 15500.0
1003 33750.0
1004 8350.0
1005 20500.0
Write the logic for identifying the fees based on Branch Id using a switch case.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:
-
8/9/2019 OOCUsingJava Lab Guide V3
29/99
Infosys Limited Object Oriented Concepts Using Java
28 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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
To use operators and control structures to perform business logic
At the end of the assignment you would have the following files:
Assignment 2.7.3: Switch case statementObjective: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 Range of marks
A 80-100
B 73-79C 65-72
D 55-64
E
-
8/9/2019 OOCUsingJava Lab Guide V3
30/99
Infosys Limited Object Oriented Concepts Using Java
29 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
At the end of the assignment you would have the following files:
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
-
8/9/2019 OOCUsingJava Lab Guide V3
31/99
Infosys Limited Object Oriented Concepts Using Java
30 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
At the end of the assignment you would have the following files:
ForLoop.java
WhileLoop.java
-
8/9/2019 OOCUsingJava Lab Guide V3
32/99
Infosys Limited Object Oriented Concepts Using Java
31 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
Assignment 2.8.2: Building logic using iterational control structuresObjective: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()
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()
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 Long Term Short Term
Maths 20000 40000
Physics 15000 30000
Chemistry 16000 32000
Computer Science 22000 30000
-
8/9/2019 OOCUsingJava Lab Guide V3
33/99
Infosys Limited Object Oriented Concepts Using Java
32 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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 L
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:
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;
Student.java
Demo.java
-
8/9/2019 OOCUsingJava Lab Guide V3
34/99
Infosys Limited Object Oriented Concepts Using Java
33 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
for(int i= 0; i
-
8/9/2019 OOCUsingJava Lab Guide V3
35/99
-
8/9/2019 OOCUsingJava Lab Guide V3
36/99
Infosys Limited Object Oriented Concepts Using Java
35 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
Step 2: Save and Compile the program, fix the errors if anyStep 3: Execute the program and verify the output
Estimated time: 15 mins
Summary of this assignment:
In this assignment, you have learnt
To use this keyword
At the end of the assignment you would have the following files:
Assignment 2.10.2: Usage of this keyword
Objective:Understand the usage of this keyword.
Problem Description:
Implement the class diagram Using Java
Step 1: Define a class Student ,
Define two constructorso 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 lastNamestudentName=firstName+lastNameo displayDetails (Student obj):Should accept the object as an argumentand display the details like studentId, studentType, studentName of thatobject
Step 2:Define a main method ,
In the main method
Student.java
Student
-studentId : int
-studentType:char
-studentName:String+Student()
+Student(char sType,String fname,String lname)
+displayDetails(Student):void
-
8/9/2019 OOCUsingJava Lab Guide V3
37/99
Infosys Limited Object Oriented Concepts Using Java
36 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
o Create an object of Student(D,Bony,Thomas) and assign it toreference variable studentOne;
o Call the displayDetails() method and display the details of studentOneo 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 anyStep 4: Execute the program and verify the output
Estimated time: 20 mins
Summary of this assignment:
In this assignment, you have learnt
To use this keyword, passing object to an argument and Overloaded
constructors
At the end of the assignment you would have the following files:
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();
Student.java
-
8/9/2019 OOCUsingJava Lab Guide V3
38/99
Infosys Limited Object Oriented Concepts Using Java
37 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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:
Estimated time:10 minutes
Summary of this assignment:
In this assignment, you have learnt
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:
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:
Registration.java
Demo.java
Registration Id: 1001
-
8/9/2019 OOCUsingJava Lab Guide V3
39/99
Infosys Limited Object Oriented Concepts Using Java
38 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
Step 1: Define constructor in Student classStudent ():initialize the instance variables with 10 and F (indicatingFresher) respectively
Step 3: Define a main methoda. In the main method, create a reference variable with the name
student.b. Create an object of type Studentand assign it to reference variable
named student.c. Using getter methods, display the studentdetails.
Step 4: Compile the program, fix the errors if anyStep 5: Execute the program and verify the output
Estimated time: 15 mins
Summary of this assignment:
In this assignment, you have learnt
To implement default constructor
To use the constructor for initializing the objects
At the end of the assignment you would have the following files:
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 {
Student.java
Student
-studentId : int
-studentType:char
+Student()
+setStudentId(id:int):void
+setStudentType(type:char):void
+getStudentId():int
+getStudentType():char
-
8/9/2019 OOCUsingJava Lab Guide V3
40/99
Infosys Limited Object Oriented Concepts Using Java
39 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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
Default and Parameterized constructors
At the end of the assignment you would have the following files:
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 automatedmachine 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
UserType.java
-
8/9/2019 OOCUsingJava Lab Guide V3
41/99
Infosys Limited Object Oriented Concepts Using Java
40 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
Ticket
-startPoint:int
-endPoint:int
-ticketAmount:int
+Ticket()
+Ticket(int,int)+getStartPoint():int
+getEndPoint():int
+getTicketAmount():int
+validateTravelPoints():boolean
+calculateTicketAmt():void
Implementation Details:
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
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
Implementation of a given class diagram Default Constructor
Parameterized Constructor
Constructor Overloading
Condition constructs
-
8/9/2019 OOCUsingJava Lab Guide V3
42/99
Infosys Limited Object Oriented Concepts Using Java
41 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
At the end of the assignment you would have the following files:
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 studentCountto store the total number ofstudentobjects of type Student
Step 2: Add static member method getStudentCount () to return thestudentCount.
Step 3:In default constructor Student(), Increment the studentCountby 1 and assignstudentId = 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 anyStep 6: Execute the program and verify the output
Estimated time: 20 mins
Summary of this assignment:
In this assignment, you have learnt
To use static variable, method and block
At the end of the assignment you would have the following files:
Assignment 2.12.2: Default Constructor and static keyword
Objective: Understand default constructor
Ticket.java
Demo.java
Student.java
-
8/9/2019 OOCUsingJava Lab Guide V3
43/99
-
8/9/2019 OOCUsingJava Lab Guide V3
44/99
Infosys Limited Object Oriented Concepts Using Java
43 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
b. Invoke the validateStudentName() and validateBranchName() for
studentOne objectcreated. If the return types of both the methods are true,
i. Invoke the validateExamMarks()method for thestudentOneobject.
ii. If the qualifyingExamMarks are invalid, display Invalid marks, the
range of marks is between 65 and 100
iii. 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 James
qualifyingExamMarks 73.0f
residentialStatus D
yearOfEngg 1
branchName MECH
d. Repeat Step 5.cfor 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
-
8/9/2019 OOCUsingJava Lab Guide V3
45/99
Infosys Limited Object Oriented Concepts Using Java
44 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
Summary of this assignment:
In this assignment, you have learnt
Default constructor
Static block , static keyword and auto-generation
At the end of the assignment you would have the following files:
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 canimprove 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
Student.java
Demo.java
-
8/9/2019 OOCUsingJava Lab Guide V3
46/99
Infosys Limited Object Oriented Concepts Using Java
45 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
ii. Code tuning technique: Common Sub-expression elimination
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 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);
}}
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);
}
}
-
8/9/2019 OOCUsingJava Lab Guide V3
47/99
Infosys Limited Object Oriented Concepts Using Java
46 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
iii. 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.
iv. Code tuning technique: Induction variable analysis and strength reduction
Descriptionif 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)
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);}
}
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);
}
}
}
-
8/9/2019 OOCUsingJava Lab Guide V3
48/99
Infosys Limited Object Oriented Concepts Using Java
47 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
v. Code tuning technique: Loop fission
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 ofreference
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] + " ");
}
}
}
-
8/9/2019 OOCUsingJava Lab Guide V3
49/99
Infosys Limited Object Oriented Concepts Using Java
48 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
vi. Code tuning technique: Loop fusion
Description:when two adjacent loops iterate the same number of times (whether ornot that number is known at compile time), their bodies can be combined as long as
they make no reference to each other's data.
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 differentcontiguous 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.
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]);
}
}
}
-
8/9/2019 OOCUsingJava Lab Guide V3
50/99
Infosys Limited Object Oriented Concepts Using Java
49 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
At the end of the assignment you would have the following files:
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 sourcecode, correct them and execute the code. (The coding standards includedocumentation, indentation, variable naming standards, proper comments, fileheader, footer etc)
CFP.java
CSE.java
DCE.java
Induction_Variable.java
Loop_Fission.java
Loop_Fusion.java
Loop_Splitting.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
-
8/9/2019 OOCUsingJava Lab Guide V3
51/99
Infosys Limited Object Oriented Concepts Using Java
50 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
b) Write a program to add two numbers and display the sum as the output. Implement allthe coding standards applicable.
Estimated time: 20 minutes
Summary of this assignment:
In this assignment, you have learnt:
To use the various coding standards to write well documented code.
At the end of the assignment you would have the following files:
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.javawith the main method written in Assignment 2.7.2. In
the main method, do the following:
a. Declare an integer array branchListand initialize it with the following values:
branchList 1001 1002 1003 1004 1005
b. Declare a double arrayfeesand initialize it with the following values:
fees 25575 15500 33750 8350 20500
CodingStandards.java
-
8/9/2019 OOCUsingJava Lab Guide V3
52/99
Infosys Limited Object Oriented Concepts Using Java
51 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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
branchListarray
[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
Declaration of an integer array, its initialization and accessing the array elements
At the end of the assignment you would have the following files:
4.2: Multidimensional array
Assignment 4.2.1: Multidimensional Array(Jagged Array)
Objective: Understand the concept of Jagged Array
Registration.java
DemoReg.java
-
8/9/2019 OOCUsingJava Lab Guide V3
53/99
Infosys Limited Object Oriented Concepts Using Java
52 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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 Tutorial1 Tutorial 2 Tutorial 3
Tony JAVA C C++
Thomas JAVA UNIX
Dinil Linux Oracle
Delvin RDBMS C# ORACLE
Step 1:Create a file JaggedArray.java with a classJaggedArraycontaining 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
Multidimensional and asymmetric two dimensional Array
Note:
In Java, array of strings is a single dimensional array consisting ofinstances of String class
At the end of the assignment you would have the following files:
Topic 5: Strings
5.1: String & Array of Strings
Assignment 5.1.1: Strings
JaggedArray.java
-
8/9/2019 OOCUsingJava Lab Guide V3
54/99
Infosys Limited Object Oriented Concepts Using Java
53 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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 Studentclass 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 thevalidateStudentName()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 charactersand a maximum of 25 characters and return false. Otherwise, return true.
Step 3: The logic for thevalidateBranchName()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
ECEEEE
MECH
Bio-Tech
If it is valid, return true, else set the value of branchNameto CSE and display a
message Invalid Branch Name, set to CSE and return false.
-
8/9/2019 OOCUsingJava Lab Guide V3
55/99
Infosys Limited Object Oriented Concepts Using Java
54 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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 studentOneand instantiate the same
a. Invoke the corresponding setter methods to set the values for the instance
variables as follows:
Table 4
studentId 1001
studentName Jackson
qualifyingExamMarks 95.0f
residentialStatus D
yearOfEngg 2
branchName CSE
b. Invoke the validateStudentName() and validateBranchName() methods. If the
return types of both the methods are true,
i. Invoke the validateExamMarks()method
ii. If the qualifyingExamMarksis invalid, display Invalid marks, the range of
marks is between 65 and 100
iii. If the qualifyingExamMarksis 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
-
8/9/2019 OOCUsingJava Lab Guide V3
56/99
Infosys Limited Object Oriented Concepts Using Java
55 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
a. Invoke the corresponding setter methods to set the values for the instance
variables as follows:
Table 5
studentId 1002
studentName Jen
qualifyingExamMarks 68.0f
residentialStatus H
yearOfEngg 3
branchName ABC
Repeat Step 4.bfor studentTwocreated 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
Using String data type
At the end of the assignment you would have the following files:
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:
Student.java
Demo.java
-
8/9/2019 OOCUsingJava Lab Guide V3
57/99
-
8/9/2019 OOCUsingJava Lab Guide V3
58/99
Infosys Limited Object Oriented Concepts Using Java
57 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
At the end of the assignment you would have the following files:
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 usernamesandpasswordsarrays with the values given below in a static
block:
Table 8
usernames admin finance studentpasswords Admin Finance Student
Step 3: In the default constructor, initialize the instance variables as given:
Table 9
Instance Variable Value to be initialized
username student
password 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 usernamesarray
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
Address.java
DemoAddress.java
-
8/9/2019 OOCUsingJava Lab Guide V3
59/99
-
8/9/2019 OOCUsingJava Lab Guide V3
60/99
-
8/9/2019 OOCUsingJava Lab Guide V3
61/99
-
8/9/2019 OOCUsingJava Lab Guide V3
62/99
Infosys Limited Object Oriented Concepts Using Java
61 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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.
-
8/9/2019 OOCUsingJava Lab Guide V3
63/99
-
8/9/2019 OOCUsingJava Lab Guide V3
64/99
Infosys Limited Object Oriented Concepts Using Java
63 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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:
-
8/9/2019 OOCUsingJava Lab Guide V3
65/99
Infosys Limited Object Oriented Concepts Using Java
64 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
Step 1:Create a new file Hostelite.java and define the Hostelite class which extends the
Studentclass as per the above class diagram
Step 2: Implement the constructor of Hosteliteclass and invoke the constructor of Student
class using the superkeyword
Step 3:Compile the Student.javaand Hostelite.javafile and fix the errors if any
Step 4:Create a new file DayScholar.javaand define the DayScholarclass which extends the
Studentclass as per the aboveclass diagram
Step 5: Implement the constructor of DayScholarclass and invoke the constructor of Student
class using the superkeyword
Step 6: Compile the DayScholar.javafile and fix the errors if any
Step 7:Create a new file DemoInherit.javacontaining the DemoInheritclass with the main
method
Step 8:In the main method:
a. Create a reference variable of Hosteliteclass and instantiate the same with the
following values using the parameterized constructor as given below
Table 12
Instance Variable Value to be initialized
hostelName AaradhyaroomNumber 105
roomType double
studentName Tommy
qualifyingExamMarks 75.6f
residentialStatus H
branchName CSE
yearOfEngg 4
addressLine L-51,SriLabdhi Colony
city Chennai
state TamilNadu
zip 600004
(Hint: Create reference variables of Address class whenever an address needs to be stored)
-
8/9/2019 OOCUsingJava Lab Guide V3
66/99
Infosys Limited Object Oriented Concepts Using Java
65 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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 DayScholarclass 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)
-
8/9/2019 OOCUsingJava Lab Guide V3
67/99
Infosys Limited Object Oriented Concepts Using Java
66 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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
Inheritance
At the end of the assignment you would have the following files:
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,
When hits a specific hotkey generates tickets from a preset start point and end
point
When enters a start point and end point generates tickets from the corresponding
travel points
Student.java
Hostelite.java
DayScholar.java
Address.java
DemoInherit.java
-
8/9/2019 OOCUsingJava Lab Guide V3
68/99
Infosys Limited Object Oriented Concepts Using Java
67 | P a g e I n f o s y s F o u n d a t i o n P r o g r a m
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 ticketAmountby 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 objectsas given below:
Ticket newTicket=new Ticket();
Ticket newTicket=new Ticket(10,1);
Ticket newTicket=new Ticket(1,10);
At