OOCUsingJava Lab Guide V3
OOCUsingJava Lab Guide V3
CONFIDENTIAL
Infosys Limited
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.
1|Page
Infosys Limited
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 Limited
3|Page
Infosys Limited
4|Page
Infosys Limited
5|Page
......................................................... 96
......................................................... 96
......................................................... 97
......................................................... 97
Infosys Limited
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
Infosys Limited
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
7|Page
Infosys Limited
Infosys Limited
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
Dispatcher: The person who dispatches shipments in a postal organization or courier company.
9|Page
Infosys Limited
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
Infosys Limited
Infosys Limited
7.
2
7
3
5
4
12 | P a g e
Infosys Limited
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.
Infosys Limited
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
14 | P a g e
Infosys Limited
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
Infosys Limited
12.
13.
14.
15.
16.
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
16 | P a g e
Infosys Limited
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
17 | P a g e
Infosys Limited
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)
18 | P a g e
Infosys Limited
Infosys Limited
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 Limited
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
:___________________
:___________________
:___________________
:___________________
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
Infosys Limited
Infosys Limited
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 Limited
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!
Infosys Limited
At the end of the assignment you would have the following files:
Traveller.java
Checks.java
Demo.java
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 Limited
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
26 | P a g e
Infosys Limited
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 Limited
Registration Id
Fees
:___________________
:___________________
Grade
A
B
C
D
E
Range of marks
80-100
73-79
65-72
55-64
<55
Infosys Limited
At the end of the assignment you would have the following files:
SwitchCase.java
29 | P a g e
Infosys Limited
At the end of the assignment you would have the following files:
ForLoop.java
WhileLoop.java
30 | P a g e
Infosys Limited
Implementation Details:
Modify the design to include the setter methods for each of the instance variables
validateStudentDetails()
x
x
x
x
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 Limited
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
Infosys Limited
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 Limited
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
Infosys Limited
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
Infosys Limited
Infosys Limited
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
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 Limited
Student
-studentId : int
-studentType:char
+Student()
+setStudentId(id:int):void
+setStudentType(type:char):void
+getStudentId():int
+getStudentType():char
Infosys Limited
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
39 | P a g e
Infosys Limited
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
40 | P a g e
Infosys Limited
At the end of the assignment you would have the following files:
Ticket.java
Demo.java
Infosys Limited
Step 1: Modify the Student class created (Student.java) in Assignment 2.5.1 to include the
default constructor
42 | P a g e
studentName
Johan
qualifyingExamMarks
residentialStatus
95.0f
D
yearOfEngg
branchName
2
CSE
Infosys Foundation Program
Infosys Limited
:___________________
:___________________
:___________________
:___________________
:____________________
:____________________
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
Infosys Limited
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 Limited
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);
}
}
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 Limited
iii.
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.
46 | P a g e
Infosys Limited
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 Limited
vi.
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.
48 | P a g e
Infosys Limited
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
Infosys Limited
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 Limited
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
:___________________
:___________________
51 | P a g e
Infosys Limited
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
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 Limited
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 Limited
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
:___________________
:___________________
:___________________
:___________________
:___________________
:___________________
54 | P a g e
Infosys Limited
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
55 | P a g e
Infosys Limited
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 Limited
At the end of the assignment you would have the following files:
Address.java
DemoAddress.java
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
Infosys Limited
EmailCheck
-emailId:String
+getEmailId():String
+setEmailId(String):void
+main(String[] args):void static
58 | P a g e
Infosys Limited
The validation rules for the email id check are as follows (to be implemented in main()):
x
x
x
x
Infosys Limited
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 Limited
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 Limited
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 Limited
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 Limited
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 Limited
:___________________
:___________________
:___________________
:___________________
:____________________
:____________________
:____________________
:____________________
:____________________
:____________________
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 Limited
:___________________
:___________________
:___________________
:___________________
:____________________
:____________________
:____________________
:____________________
:____________________
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
66 | P a g e
Infosys Limited
Ticket
-startPoint:int
-endPoint:int
-ticketAmount:int
+Ticket()
+Ticket(int,int)
+getStartPoint():int
+getEndPoint():int
+getTicketAmount():int
+validateTravelPoints():void
+calcTicketAmt():int
6.2: Aggregation
67 | P a g e
Infosys Limited
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{
Infosys Limited
69 | P a g e
Infosys Limited
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 Limited
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 Limited
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
Infosys Limited
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
73 | P a g e
Infosys Limited
Student Id
Student Name
Qualifying Marks
Residential Status
Current Year of Engineering
Branch Name
:___________________
:___________________
:___________________
:___________________
:____________________
:____________________
Infosys Limited
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
75 | P a g e
Infosys Limited
In the displayStudentInformation(),write the logic using the getter methods of the class and
display the details as follows:
76 | P a g e
Infosys Limited
Step 2: Use the file Hostelite.java file created earlier, add a new method called
displayStudentInformation() as shown in the class diagram below:
77 | P a g e
Infosys Limited
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
Infosys Limited
branchName
79 | P a g e
branchFees
Infosys Foundation Program
Infosys Limited
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
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 Limited
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());
Instance Variable
Value to be initialized
For Residential Address
addressLine
No.3, Choultry circle
City
Mysore
state
Karnataka
81 | P a g e
Notice
passing of
Student
reference
to calculate
-Fees()
Infosys Limited
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 Limited
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 Limited
System.out.println("Residential status
:"+getResidentialStatus());
: "+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());
}
}
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 Limited
Infosys Limited
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 Limited
This would create a new package in the project explorer as shown below.
87 | P a g e
Infosys Limited
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 Limited
Infosys Limited
Infosys Limited
Infosys Limited
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
Infosys Limited
}
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 Limited
{
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
Infosys Limited
Infosys Limited
Infosys Limited
--------------------}
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