lab guide object oriented programming using java_la1026_ver1.2

71
CONFIDENTIAL Lab Guide for Object Oriented Programming Using Java Author(s) S.Meenakshi Lesitha Mary James Authorized by Mr. Srikantan Moorthy Creation/Revision Date Mar-2009/Aug-2009 Version 1.2

Upload: shashank-telidevara

Post on 22-Nov-2014

1.069 views

Category:

Documents


2 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Lab guide  object oriented programming using java_la1026_ver1.2

CONFIDENTIAL

Lab Guide for Object Oriented Programming Using Java

Author(s) S.Meenakshi

Lesitha Mary James

Authorized by Mr. Srikantan Moorthy

Creation/Revision Date Mar-2009/Aug-2009

Version 1.2

Page 2: Lab guide  object oriented programming using java_la1026_ver1.2

CONFIDENTIAL

COPYRIGHT NOTICE

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

Education and Research Department

Infosys Technologies Limited

Electronic City

Hosur Road

Bangalore - 561 229, India.

Tel: 91 80 852 0261-270

Fax: 91 80 852 0362

www.infosys.com

mailto:E&[email protected]

Page 3: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Document Revision History

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No: 1.2

i

Document Revision History

Version Date Author(s) Reviewer(s) Comments

1.0 Mar-2009 Vani Vasudevan

Lesitha Mary James

Meenakshi S

Nishit Goel

Restructure 2009

1.1 Jun-2009 S.Meenakshi

Lesitha Mary James

Nishit Goel Changes made as per

feedback from pilot batch

rollout

1.2 Aug-2009 S.Meenakshi

Lesitha Mary James

Nishit Goel Modified assignments

based on case study

Page 4: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 1 of 68

Contents

COPYRIGHT NOTICE ...................................................................................................... II

DOCUMENT REVISION HISTORY ......................................................................................... I

CONTENTS ..................................................................................................................1

CONTEXT ....................................................................................................................3

DAY 1 ASSIGNMENTS .....................................................................................................3

ASSIGNMENT 1: CASE STUDY .................................................................................................. 3

ASSIGNMENT 2: OOP FEATURES ............................................................................................... 4

ASSIGNMENT 3: CLASSES AND OBJECTS ........................................................................................ 5

ASSIGNMENT 4: FIRST JAVA PROGRAM ........................................................................................ 6

ASSIGNMENT 5: LOCAL VARIABLES ............................................................................................. 8

ASSIGNMENT 6: OPERATORS ................................................................................................... 9

ASSIGNMENT 7: BOOLEAN DATA TYPE ....................................................................................... 10

ASSIGNMENT 8: BYTE DATA TYPE ........................................................................................... 11

DAY 2 ASSIGNMENTS ................................................................................................... 12

ASSIGNMENT 1: TYPECASTING ............................................................................................... 12

ASSIGNMENT 2: CONTROL STATEMENT ...................................................................................... 13

ASSIGNMENT 3: SWITCH CASE STATEMENT ................................................................................... 14

ASSIGNMENT 4: CLASSES AND OBJECTS ...................................................................................... 15

ASSIGNMENT 5: DEFAULT CONSTRUCTOR .................................................................................... 16

ASSIGNMENT 6: DEFAULT AND PARAMETERIZED CONSTRUCTORS .............................................................. 17

ASSIGNMENT 7: PASS BY VALUE AND REFERENCE ............................................................................. 18

ASSIGNMENT 8: CODING STANDARDS ......................................................................................... 19

ASSIGNMENT 9: USAGE OF “THIS” KEYWORD ................................................................................ 20

SELF REVIEW ................................................................................................................ 21

DAY 3 ASSIGNMENTS ................................................................................................... 23

ASSIGNMENT 1:STATIC VARIABLE, BLOCK AND METHOD ....................................................................... 23

ASSIGNMENT 2: 2D ARRAYS .................................................................................................. 24

ASSIGNMENT 3: MULTIDIMENSIONAL ARRAY(JAGGED ARRAY) ................................................................ 25

ASSIGNMENT 4:STRINGS ..................................................................................................... 25

ASSIGNMENT 5: JAVA DOC EXPLORATORY ASSIGNMENT ...................................................................... 27

ASSIGNMENT 6: USER INPUT(COMMAND LINE ARGUMENT) ................................................................... 27

ASSIGNMENT 7:COMMAND LINE ARGUMENT .................................................................................. 28

ASSIGNMENT 8:OVERLOADED METHODS ...................................................................................... 29

SELF REVIEW ................................................................................................................ 30

DAY 4 ASSIGNMENTS ................................................................................................... 33

ASSIGNMENT 1: INHERITANCE ................................................................................................ 33

Page 5: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 2 of 68

ASSIGNMENT 2: ‘PROTECTED’ ACCESS SPECIFIER ............................................................................ 34

ASSIGNMENT 3: METHOD OVERRIDING ,SUPER KEYWORD AND DYNAMIC BINDING ............................................. 36

ASSIGNMENT 4: SUPER KEYWORD ............................................................................................ 38

ASSIGNMENT 5: CONSTRUCTOR INVOCATION ................................................................................. 42

ASSIGNMENT 6 : DYNAMIC POLYMORPHISM ................................................................................... 44

ASSIGNMENT 7:FINAL KEYWORD .............................................................................................. 45

ASSIGNMENT 8:ABSTRACT CLASS ............................................................................................ 47

REVIEW ...................................................................................................................... 48

DAY 5 ASSIGNMENTS ................................................................................................... 52

ASSIGNMENT 1: PACKAGE (CREATE, COMPILE & EXECUTE ) ................................................................. 52

ASSIGNMENT 2 : ACCESS SPECIFIER.......................................................................................... 57

ASSIGNMENT 3:INTERFACES .................................................................................................. 59

ASSIGNMENT 4: UML – USE CASE DIAGRAM ................................................................................. 60

ASSIGNMENT 5: UML – CLASS DIAGRAM ..................................................................................... 61

ASSIGNMENT 6: CASE STUDY OF D-RAIL INC. ................................................................................ 62

SELF REVIEW ................................................................................................................. 63

CASE STUDY BASED ASSIGNMENTS .................................................................................. 65

CASE STUDY 1 – BANKING SYSTEM ........................................................................................... 65

DAY 2 ASSIGNMENT 1: IF-ELSE CONDITION ................................................................................... 65

CASE STUDY 2 – TRAVEL MANAGEMENT SYSTEM .............................................................................. 65

DAY 2 ASSIGNMENT 1: IF-ELSE CONDITION ................................................................................... 65

DAY 3 ASSIGNMENT 2: STRINGS .............................................................................................. 66

DAY 4 ASSIGNMENT 3: INHERITANCE ......................................................................................... 67

Page 6: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 3 of 68

Context This document contains assignments to be completed as part of the hands on for the subject

Introduction to Object Oriented Programming using Java.

Note: In order to complete the course, assignments in this document must be completed in

the sequence mentioned.

Day 1 Assignments

Assignment 1: Case Study

Objective: Analysis of the case study and identify the complex system attributes and using

OO features to overcome the same.

Problem Description: Course Management System

A Course Management System needs to be developed for an engineering college. The college wants an automated system to replace its manual system for purpose of allocation of students to courses and lecturers to courses. There are 10000 students and 500 faculty members in the college. The engineering college provides graduation and post graduation in the various branches of engineering.

In any branch, the entire duration is divided into semesters. Each semester includes various courses. Students admitted into the college can apply for various courses. The courses are elective in nature. The student needs to select two electives. The electives are offered from 5th semester onwards for graduate students and from 3rd semester onwards for the post graduate students. The graduate students need to undergo a final year project in the fourth year of engineering whereas the post graduate student undergoes a thesis submission in the second year. The complete list of courses, lecturers and students is maintained in the college. The list is constant and cannot be updated by the system. The automated system uses this list for allocation of courses.

The lecturers can be categorized into full time lecturers and visiting members. The full time lecturers have target days and are paid salary every month. The visiting members get paid per lecture basis and do not have any target days.

The system is used by the admin staff to register students admitted to college to the courses opted. The system needs to be authenticated with a login id and password. The system would be used by the student to view the marks and the attendance details also. The system is used by the HOD (Head of the department) to allocate courses to the lecturers. At the beginning of the semester, the HOD will do the allocation of lecturers to the classes for his department. The HOD may make changes in the allocation during the progress of the course. The system maintains a history of all the lecturers who have handled the courses throughout the semester .The lecturer will use the system to update the marks of the student (project, assignment,

Page 7: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 4 of 68

internal test marks and the semester end examination marks). The lecturer will also mark the attendance of the students through the system.

In addition to the above, the system also keeps track of the residential status of the student. The student may be a host-elite or a day scholar. If he is host-elite, the system will maintain his / her hostels name, room number and the fees pertaining to the same.

Answer the following:

a. Identify two cases of hierarchy in the given problem statement

b. Identify the common behavior among the day scholar, host-elite, graduate and post graduate students

c. Identify the different layers possible in this system in terms of the users of the systems

d. The admin staff wants to generate a report containing the scores of students in a batch in the following manner:

Student Id Student Name Marks scored Lecturer Name Course registered

What details should the admin staff accumulate to arrive at this detailed report?

Estimated time: 20 mins

Summary of this assignment:

In this assignment, you have learnt

• To understand a complex software system and identify the attributes

Assignment 2: OOP features

Objective: Analyze the OOP features Problem Description: Consider the case study provided in Assignment 1 for this assignment. a. Identify the attributes of the Student class. What are the details that can be exposed and

what details can be hidden?

b. Consider the calculation of grade for the Student. There are several student types. Let us assume that we need to write a method for the calculation. How many methods would be written? Will they have the same name and signature? Will the functionality /code in these functions remain same?

c. The fees have to be paid by the host-elite and by the day scholars. The host-elites need to pay hostel fees along with semester fees. The day scholars need to pay only semester fees. How many function/s would you code in the Student class and why?

d. For the options a,b and c identify the OOP features that would be implemented

Estimated time: 20 mins

Summary of this assignment:

Page 8: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 5 of 68

In this assignment, you have learnt

• Analyze a complex system and apply object oriented approach to solve the problem

Assignment 3: Classes and Objects

Objective: Understand the terms -class, objects, state, behavior and identity

Problem Description: Fill the crossword based on the clues given

1. Jack is the name of a student- represents ________

2. Graduates, post graduates , day scholars and host-elites share common behavior of this

________

3. Tom is a Post Graduate student and is a topper –represents _____________

4. The attribute and the activities related to a student are put as part of Student class-

represents _________________

5. There is a student in graduation class , whose id is1001 , name Jack and attending

Operating systems course – represents an __________________

6. The student pays fees and the calculation is done by the admin – represents _______

7. A day scholar is a type of student – represents ___________

8. A student can only view marks, he cannot update it—represents ________________

9. I use calculateFees method , be it host-elite or day scholar – represents

__________________________

8

6

1

2

7

3

9

4

5

Estimated time: 20 mins

Summary of this assignment:

In this assignment, you have learnt

Page 9: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 6 of 68

• Object Oriented terminologies

Assignment 4: First Java Program

Objective: Create, save, compile and execute a Java Program using text pad.

Problem Description: To display “Welcome message” using Java program

Step 1: Go to Start and Run

Step 2: Open textpad

Step 3: Text editor is opened as below

Page 10: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 7 of 68

Step 4: Go to File menu and select “Save As” menu option to save the file as Welcome.java in

the chosen folder (This would enable the java color setting for the code to be typed)

Step 5: Type the below program in the textpad and save

// First Java program class Welcome{ public static void main(String args[]){ // println method is used to print message on the s creen System.out.println("Welcome to Object Oriented Pro gramming:Day1

Session"); } } Step 6: Compile the program (press Ctrl + 1 or go to Tools menu and select “Compile Java”)

Page 11: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 8 of 68

Step 7: Execute the program (press Ctrl + 2 or go to Tools menu and select “Run Java

Application”

Output Window:

Estimated time: 15 mins

Summary of this assignment:

In this assignment, you have learnt

• How to create, save , compile and execute the Java program using textpad

Assignment 5: Local Variables

Objective: Understand the usage of local variables

Problem Description: To create different types of local variables and display them

Step 1: Type the below program in the textpad, save and compile the program

// Program to understand local variables and litera ls class Variable { public static void main (String args[]){ int intVal; float floatVal = 250.5f; double doubleVal = 2500.5; boolean boolVal = true;

Indicates that compilation is successful

Page 12: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 9 of 68

System.out.println("Integer\t:" + intVal + "\nFloa t\t:" + floatVal+"\nDouble\t:" + doubleVal + "\nBoole an\t:" + boolVal); } }

Step 2: Observe that there is a compilation error. Debug the code so that it compiles and

executes successfully.

Note: Accessing an uninitialized local variable will result in a compile-time error. If you cannot initialize your local variable where it is declared, make sure to assign a value before you attempt to use it.

Estimated time: 15 mins

Summary of this assignment:

In this assignment, you have learnt

• How to use local variables in Java

Assignment 6: Operators

Objective: Understand the various operators in Java

Problem Description: To implement and understand the usage of modulus operator, string

concatenation, equality operator and logical operators in Java.

Step 1: Type the below program in the textpad, save, compile and execute

// Program to understand different types of operato rs class Operator{ public static void main(String[] args){ int intVal=10; float floatVal=3.0f; boolean bool1 = true; boolean bool2 = false; boolean bool3 = true; // Arithmetic : Modulus operator System.out.println("Arithmetic"); System.out.println(intVal + " % " + floatVal + "= " +

Page 13: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 10 of 68

(intVal % floatVal)); System.out.println(); // String Concatenation : Observe the difference System.out.println("String Concatenation"); System.out.println("Day " + 2 + " Session"); System.out.println("\n" + 2 + 3 +"\n" +(2+3)); System.out.println(); // Relational: Equality operator System.out.println("Relational"); System.out.println(intVal + " == " + floatVal + " = " +(intVal==floatVal)) ; floatVal = 10.0f; System.out.println(intVal + " == " + floatVal + " = " +(intVal==floatVal)); System.out.println(); bool2 = false; if(bool1 || (bool1 && (bool2=false))){ System.out.println("Success"); } else{ System.out.println("Failure"); } System.out.println("bool2 value : " + bool2); } } Estimated time: 25 mins

Summary of this assignment:

In this assignment, you have learnt

• Usage of some operators available in Java

Assignment 7: Boolean Data Type

Objective: Understand the Boolean data type

Problem Description: To implement and understand the usage Boolean datatype in Java

Step 1: Type the below program in the textpad and save the file

Step 2: When executed, the output is :

Page 14: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 11 of 68

Failure bool2 value : true Press any key to continue . . .

Step 3: Make changes to the code so that the output reads :

Success bool2 value : true Press any key to continue . . .

Note: The logical operators and the Boolean operators may be changed to achieve this

result. Although the if control structure is used here, the focus is on the operators and

Boolean datatype

class Operator{ public static void main(String[] args){ boolean bool1 = false; boolean bool2 = true; boolean bool3 = true; if(bool1 && (bool1 && (bool2=false))){ System.out.println("Success"); } else{ System.out.println("Failure"); } System.out.println("bool2 value : " + bool2); } } Summary of this assignment:

In this assignment, you have learnt

• Boolean data type and operators

Estimated time: 15 minutes

Assignment 8: Byte Data Type

Objective: Understand the byte data type

Problem Description: Understand the range for datatypes and strong typechecking.

Step 1: Consider the program given below:

Page 15: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 12 of 68

public class Operator { public static void main(String args[]){ int intVal = 100; byte byteVal= (byte)intVal; byte max = 127; byte min = -128; byte sum= max + min; System.out.println("Sum= " + sum); } } Step 2: Type the program and compile it

Step 3: Analyze the compilation error

Note: The solution to this error will be dealt with in Day 2 of the course

Estimated time: 20 minutes

Summary of this assignment:

In this assignment, you have learnt

• Byte data type

Day 2 Assignments

Assignment 1: Typecasting

Objective: Understand Conversion and Typecasting

Problem Description: Modify Assignment No. 8 of Day 1 so that the addition of the numbers is

possible and can be stored and displayed.

Estimated time: 15 minutes

Summary of this assignment:

In this assignment, you have learnt

• Typecasting Data types

Page 16: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 13 of 68

Assignment 2: Control Statement

Objective: Understand control statements

Problem Description: To implement control flow statements break and continue

Step 1: Type the below programs in the textpad, save, compile and execute

Program 1: //Program to understand the loop and break class Control{ 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){ break; } } System.out.println("Outer Loop"); } System.out.println("End"); } }

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

Page 17: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 14 of 68

continue; } } System.out.println("Outer Loop"); } System.out.println("End"); } }

Note:

• You can’t use a number or anything that does not evaluate to a

Boolean value as a condition in selection / iteration statement

• You can use break inside a looping statement without including if

construct.

Estimated time: 15 mins

Summary of this assignment:

In this assignment, you have learnt

• How to use break and continue with the looping statement.

Assignment 3: Switch case statement

Objective: Understand the concept of conditional case statements using switch cases.

Problem Description: A java program needs to be written to display the range of marks based

on the grade. The table for calculation of grade is as follows:

Grade Range of marks

A 80-100

B 73-79

C 65-72

D 55-64

E <55

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

Step 2: Create a character variable for storing the grade with a default value of B

Step 3: Write the java code to implement the calculation of grades as given in the table. If

any other grade is provided , the program must display a message “Grade does not exist”,for

valid grades it must display the range of marks as given in the table.

Page 18: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 15 of 68

Step 4: Change the values of the grade variable and test the working of the program for all

the grades.

Estimated time: 20 minutes

Summary of this assignment:

In this assignment, you have learnt

• Switch case statements

Assignment 4: Classes and Objects

Objective: Understand and implement the concept of Abstract Data Type used for achieving

encapsulation and abstraction.

Problem Description:

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.java Step 2: Define all the member methods of Student Class Step 3: Define a class “CourseManagement” with main method and save it in CourseManagement.java

a. In the main method, assign the student details in the corresponding temporary variables.

b. Create a reference variable with the name student and instantiate the same

Student

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

Page 19: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 16 of 68

c. Invoke the corresponding setter methods to set the instance variable with the given values stored in temporary variables.

d. Using getter methods, display the student details. Step 4: Compile the program, fix the errors if any Step 5: Execute the program and verify the output

Estimated time: 30 mins

Note:

• Create a folder for storing every assignment

Summary of this assignment:

In this assignment, you have learnt

• How to implement ADT in Java

• How to implement getter and setter methods

• How to create reference variables

• How to create an object

Assignment 5: Default Constructor

Objective: Understand the concept of Default Constructor.

Problem Description:

Enhance the Assignment 4 and do the necessary modification as mentioned below:

Step 1: Define constructor in Student class

Student (): initialize the instance variables with 10 and ‘F’ (indicated fresher) respectively

Step 2: Define a main method a. In the main method, create a reference variable with the name student. b. Create an object of type Student and assign it to reference variable named

student.

Student

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

Page 20: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 17 of 68

c. Using getter methods, display the student details. Step 3: Compile the program, fix the errors if any Step 4: Execute the program and verify the output

Estimated time: 15 mins

Summary of this assignment:

In this assignment, you have learnt

• How to implement default constructor

• How to use the constructor for initializing the objects

Assignment 6: 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 { 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:

Page 21: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 18 of 68

In this assignment, you have learnt about

• Default and

• Parameterized constructors

Assignment 7: Pass By Value and reference

Objective: Understand passing of primitive and abstract data types .

Problem Description: To write code to understand pass by value and passing reference

objects.

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) to the method passTheValueMethod().Change the value of Student Id and display

the Student Id of the student.

Note: There is a change in the Student Id. Why?

Estimated time: 20 minutes

Page 22: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 19 of 68

Summary of this assignment:

In this assignment, you have learnt

• Pass by value and Pass by reference

Assignment 8: Coding Standards

Objective: Understand and implement coding standards

Problem Description: Consider the program given below. Correct the missing coding

standards, prevent instance variable hiding , compile and execute the program.

Note: i and j represent instance variables as well as parameters

public class class1 { int i=22; int j=14000; boolean k; boolean l; public static void main(String args[]){ i=22; j=14000; class1 class1= new class1(); k= class1.Method1(i); l= class1.Method2(j); if(k==true &&l==true ) { System.out.print(" Is a new employee"); } else { System.out.print(" Is not a new employee"); } } public boolean Method1(int i) { if (i>20 && i<30) { return true; } else { return false; }

Page 23: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 20 of 68

} public boolean Method2(int j) { if (j>=14000 && j<20000) { return true; } else { return false; } } }

Estimated time: 15 minutes

Summary of this assignment:

In this assignment, you have learnt

• Coding standards

Assignment 9: 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 constructors o Default constructor: Used to increment the value of studentId for each

objects of Student class. studentId should start from 550. o Parameterized constructor: Constructor with three arguments

StudentType(H/D),firstName and lastName

Student

-studentId : integer -studentType:char -studentName:String +Student() +Student(char sType,String fname,String lname) +displayDetails(Student):void

Page 24: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 21 of 68

studentName=firstName+lastName o displayDetails (Student obj):Should accept the object as an argument and display the details like studentId, studentType, studentName of that object

Step 2: Define a main method ,

• In the main method o Create an object of Student(‘D’,”Bony”,”Thomas”) and assign it to

reference variable studentOne; o Call the displayDetails() method and display the details of studentOne o Create an object of Student(‘H’,”Dinil”,”Bose”) and assign it to

reference variable studentTwo; o Call the displayDetails() method and display the details of studentTwo

Step 3: Compile the program, fix the errors if any Step 4: Execute the program and verify the output

Estimated time: 20 mins

Summary of this assignment:

In this assignment, you have learnt

• How to use this, passing object to an argument, Overloaded constructors

Self Review

Predict the output of the following programs and analysis your answer by executing the code:

1.

class TypeCasting{ public static void main(String args[]){ int intVal=10; double doubleVal= 20.0; // Explicit Casting is required intVal = doubleVal; System.out.println(intVal); } }

2.

class Demo{ public static void main(String args[]){ if(1){ System.out.println("True Block"); } else{ System.out.println("False Block"); } }

Page 25: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 22 of 68

} Note : You can only the Boolean type in the conditional st atement 0 won’t be interpreted as false and nonzero (>0) wo n’t be interpreted as true.

3.

class Example{ public static void main(String[] args){ int intValOne = 0; int intValTwo = 0; for(short index=0; index < 5; index++){ if((++intValOne > 2) || (++intValTwo > 2)){ intValOne++; } } System.out.println(intValOne + " " + intValTwo); } }

4.

class Example{ public static void main(String[] args){ int intValOne = 5,intValTwo = 7; System.out.println((( intValTwo * 2) % intValOne) ); System.out.println(intValTwo % intValOne); } }

5.

class Example{ public static void main(String[] args){ int val1 = 9; int val2 = 6;

for (int val3 = 0; val3 < 6; va13++,val2--){ if(val1 > 2){

val1--; } if(val1 > 5){ System.out.print(val1 + “ “); --val1;

Page 26: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 23 of 68

continue; } val1--; }

} }

7.

Find the output of the following program: public class switchCase { public static void main(String args[]) { String comment; int val = (int)(4 * 3); switch (val) { case 0: comment = "Case 0"; break; case 1: comment = "Case 1"; break; case 2: comment = "Case 2"; break; default: comment = "Oops -- something is wron g "; } System.out.print(comment); } }

Day 3 Assignments

Assignment 1:Static variable, block and method

Objective: Understand the static variable, static block and static method

Problem Description:

Modify the Assignment 10 of Day 2 to get the total number of student objects

Static variable and static method:

Page 27: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 24 of 68

Step 1: Add static data member studentCount to store the total number of objects of

type Student Step 2: Add static member method getStudentCount () to return the value studentCount. Step 3: In default constructor Student(), increment the studentCount by 1 and assign to studentId

Static block:

Step 4: Assign studentCount = 10 (as already 10 students have enrolled)

Step 5: Save and Compile the program, fix the errors if any Step 6: Execute the program and verify the output

Estimated time: 20 mins

Summary of this assignment:

In this assignment, you have learnt

• How to use static variable, method and block

Assignment 2: 2D arrays

Objective: Understand 2D arrays and its working

Problem Description: Create class DemoArray to add 2D arrays. Write the business logic to

display the sum of the matrices. Below mentioned are a few guidelines that can be followed

Initialize the 2D arrays as follows:

int firstArrayMatrix[][]={{1,1,1},{1,1,1}}; int secondArrayMatrix[][]={{2,2,2},{2,2,2}}; Display the two matrices on the console as follows: Matrix 1 1 1 1 1 1 1 Matrix 2 2 2 2 2 2 2 Display the sum of the matrices: Sum of the Matrices 3 3 3 3 3 3

Page 28: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 25 of 68

Estimated time: 20 minutes

Summary of this assignment:

In this assignment, you have learnt

• Implementation of 2d arrays

Assignment 3: Multidimensional Array(Jagged Array)

Objective: Understand the concept of Jagged Array

Problem Description:

The students joined a tutorial for the various subjects as given below:

Tony JAVA C C++

Thomas JAVA UNIX

Dinil Linux Oracle

Delvin RDBMS C# ORACLE

Initialize the array based on the above table and display the details of Delvin inside the main

method written in a class JaggedArray

Estimated time: 20 min

Summary of this assignment:

In this assignment, you have learnt

• Multidimensional Array

Assignment 4:Strings

Objective: To understand the concept of strings

Problem Description:

Enhance the Assignment 5 of Day 2 and do the necessary modification as mentioned below:

Student

-studentId : integer -studentType:char - studentName:String

+Student() +Student(id,type,firstName,lastName) +setStudentId(id:int):void +setStudentType(type:char):void +setStudentName(firstName:String,lastName:String) +getStudentId():int

Page 29: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 26 of 68

Step 1: Define constructors in Student class

Student (): Initialize the instance variables with 10 and ‘F’ (indicated fresher) respectively Student(id,type,firstName,lastName):Initialize the instance variables studentId and studentType with id and type respectively. Initialize the instance variable studentName with firstName + lastName. (+ denote concatenation)

Step 2: Define the setStudentName(firstName:String,lastName:String) as below:

setStudentName(String firstName,String lastName){ studentName = firstName+lastName;

}

Step 3: Define a main method a. In the main method, create a reference variable student of type Student. b. Create an object of type Student and assign it to reference variable named

student. i. Invoke the corresponding setter methods to set the instance variable

with the given values stored in temporary variables. ii. Using getter methods, display the student details.

c. Create an object of type Student (id, type, firstName, lastName) and assign it to reference variable named student.

i. Using getter methods, display the student details Step 4: Compile the program, fix the errors if any Step 5: Execute the program and verify the output

Estimated time: 25 mins

Note:

• You can refer javadoc to know various methods present in String class

Summary of this assignment:

In this assignment, you have learnt

• How to use strings

Page 30: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 27 of 68

Assignment 5: Java Doc Exploratory assignment

Objective: To explore and understand the Java Doc. Create a program with the help of java

doc. (hint use String)

Problem Description: Create classes called which does the following: 1. Takes User name as input 2. Display length of the string 3. Displays output as Hi <username> 4. Convert User name to lower case 5. Convert User name to upper case 6. Check whether the name is starting with ‘a’ 7. Replace the User name as INFOSYS

Estimated time: 35 minutes

Summary of this assignment:

In this assignment, you have learnt

• To use Java Doc to seek help on existing classes

Assignment 6: User Input(Command Line Argument)

Objective: Understand the command line arguments and Integer. parseInt method and its

working .

Problem Description: Create classes called UserInput. Create member variables which accept values entered by the user through command line. The variable ‘number’ will be the number for which the multiplication table is to be generated and ‘iterations’ will be the number till which the multiplication table will be generated. Generate the multiplication table by accepting input from user as mentioned in the description above.

public class UserInput { public static void main(String[] args) { int number, iterations; number = Integer.parseInt(args[0]); iterations = Integer.parseInt(args[1]); /*write code to generate a multiplication table*/ } } Estimated time: 20 minutes

Summary of this assignment:

Page 31: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 28 of 68

In this assignment, you have learnt

• Taking input from user as arguments

Assignment 7:Command Line Argument

Objective: Understand command line arguments

Problem Description:

Enhance the Assignment 4 of Day 3 and do the necessary modification as mentioned below:

Step 1: Through the command line argument get the value of studentId, studentName residentialStaus, Semester fees and Hostel fees(only if the residential status is “Hostelite”) Step 2: Set the value of the data members with the help of the setter method Step 3: In the main method, create a reference variable student of type Student.

a. Using getter methods, display the student details Step 4: Compile the program, fix the errors if any Step 5: Execute the program and verify the output

Estimated time: 20 mins

Summary of this assignment:

In this assignment, you have learnt

• How to implement command line argument and parseInt()method

Student

-studentId : integer -studentName:String - residentialStatus:String - feesPerMonth: long int +Student() +setStudentId(id:int):void +setStudentName(firstName:String,lastName:String) +setResidentialStatus(status:String) +getStudentId():int +getStudentName():String +getResidentialStatus():String +getFees():long int

Page 32: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 29 of 68

Assignment 8:Overloaded Methods

Objective: Understand method overloading

Problem Description:

Enhance the Assignment 7 and do the necessary modification as mentioned below:

Step 1: Define the calculateFees methods as below: calculateFees(double semesterFees){ feesPerMonth = semesterFees / 6.0;

} calculateFees(double semesterFees,double hosterlFees){

feesPerMonth = semesterFees / 6.0; feesPerMonth = feesPerMonth+ hostelFees;

}

Step 2: Define a main method

Student

-studentId : integer -studentType:char -studentName:String - residentialStatus:String - feesPerMonth: double +Student() +Student(id,type,firstName,lastName) +setStudentId(id:int):void +setStudentType(type:char):void +setStudentName(firstName:String,lastName:String) +setResidentialStatus(status:String) +getStudentId():int +getStudentType():char +getStudentName():String +getResidentialStatus():String +getFees():String +calculateFees(semesterFees:double):void +calculateFees(semesterFees:double,hostelFees:doubl e):void

Page 33: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 30 of 68

a. In the main method, create a reference variable student of type Student. b. Create an object of type Student (id, type, firstName, lastName) and assign

it to reference variable named student. c. Invoke setResidentialStatus method to set the residentialStatus as “Day

Scholar” or “Hostelite” d. Check for the residential status, if residential status is equals to “Day

Scholar”,invoke calculateFees(double semesterFees) method otherwise, invoke calculateFees(double semesterFees, double hosterlFees)

e. Using getter methods, display the student details

Step 3: Compile the program, fix the errors if any Step 4: Execute the program and verify the output

Note:

• Use boolean equalsIgnoreCase(String anotherString)

Method to check the content of the string objects for equality

Estimated time: 40 mins

Summary of this assignment:

In this assignment, you have learnt

• How to implement method overloading

Self Review

What would be the output of the following programs?

1.

class StringEqual{ public static void main(String arg[]){ String name1,name2; name1 = "God"; name2= name1; if(name1 == name2){ System.out.println("Equal"); } else{ System.out.println("Not Equal"); } } }

2.

Page 34: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 31 of 68

class StringEqual{ public static void main(String arg[]){ String name1,name2; name1 = new String("God"); name2= new String("God"); if(name1 == name2){ System.out.println("Equal"); } else{ System.out.println("Not Equal"); } } }

3.

class StringEqual{ public static void main(String arg[]){ String name1,name2; name1 = new String("God"); name2= new String("God"); if(name1.equals(name2)){ System.out.println("Equal"); } else{ System.out.println("Not Equal"); } } }

4.

class StaticDemo { static int count=10; StaticDemo(){ count++; } static void display(){ System.out.println(count); } static{ System.out.println("Static Block written Befo re Main");

Page 35: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 32 of 68

} public static void main(String args[]){ StaticDemo t1=new StaticDemo(); StaticDemo t2=new StaticDemo(); StaticDemo.display(); t2.display(); } static{ System.out.println("Static Block written Af ter Main"); } }

5.

class MultiDimArray { public static void main(String[] args) { String[][] names = {{"Mrs.","Ms." , "Mr."}, {"Vani","Lesitha","Nishit","Meenakshi"} }; System.out.println(names[0][0] + names[1][0 ]); System.out.println(names[0][2] + names[1][2 ]); } }

6.

class StaticDemo1{ private int num; static void display(){ System.out.println(num); } public static void main(String args[]){ StaticDemo.display(); } } 7.

What will be the output of the following: public class thisSample { public static void main(String[] args){ Square square =new Square(); square.display(5); int area = square.calculateArea();

Page 36: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 33 of 68

System.out.println("The area of the Square is : " + area); } } public class Square { int length; void display(int length){ this.length=length; } int calculateArea(){ return(length*length); } }

Day 4 Assignments

Assignment 1: Inheritance

Objective: Understand the concept of Inheritance

Problem Description:

To implement the following class diagram

Student

-studentId : integer -studentType:char -studentName:String -feesPerMonth: double +Student() +Student(id,type,firstName,lastName) +setStudentId(id:integer):void +setStudentType(type:char):void +setStudentName(firstName:String,lastName:String) +setFeesPerMonth(double) +getStudentId():integer +getStudentType():char +getStudentName():String +getStudentType():char +getStudentName():String +getFeesPerMonth():double

Page 37: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 34 of 68

Step 1: Create a class “Hostelite” by reusing “Student” class. Step 2: Implement all the methods specified in the “Hostelite” and store it in Hostelite.java Step 3: In main method,

a. Create an object of type Hostelite by invoking the parameterized constructor with the required parameters.

b. Display all the details of Hostelite (id, type, name, feesPerMonth, hostelName, roomNo) by invoking appropriate getter methods.

Step 4: Compile the program, fix the errors if any Step 5: Execute the program and verify the output

Estimated time: 25 mins

Summary of this assignment:

In this assignment, you have learnt

• How to implement simple inheritance.

Assignment 2: ‘protected’ Access Specifier

Objective: Understand the significance of protected access specifier in Inheritance.

Problem Description:

Modify the Assignment 1 of Day 4 with the following class diagram and steps

Hostelite -hostelName : String -roomNumber : integer +Hostelite() +Hostelite(integer,char,String,double,String,intege r) +getHostelName():String +getRoomNumber():integer

Page 38: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 35 of 68

Student

#studentId : integer #studentType:char #studentName:String #feesPerMonth: double +Student() +Student(id,type,firstName,lastName) +setStudentId(id:integer):void +setStudentType(type:char):void +setStudentName(firstName:String,lastName:String) +setFeesPerMonth(double) +getStudentId():integer +getStudentType():char +getStudentName():String +getStudentType():char +getStudentName():String +getFeesPerMonth():double

Hostelite -hostelName : String -roomNumber : integer +Hostelite() +Hostelite(integer,char,String,double,String,intege r) +getHostelName():String +getRoomNumber():integer

Page 39: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 36 of 68

Steps mentioned in Assignment 1 of Day4 have to be repeated with the following

modification. Step 1: Modify the data members of the Student class from private to protected Step 2: Hostelite class is derived from Student class Step 3: In Hostelite () parameterized constructor, all the member variables (including Student class members) have to be initialized with the corresponding parameters passed. Step 4: Display the details. Step 5: Compile the program, fix the errors if any Step 6: Execute the program and verify the output

Estimated time: 15 mins

Summary of this assignment:

In this assignment, you have learnt

• How to use the protected access specifier

Assignment 3: Method Overriding ,super keyword and Dynamic Binding

Objective: Understand the significance of super keyword and method overriding in

Inheritance.

Problem Description:

Modify the Assignment 2 of Day 4 with the following class diagram and steps

Page 40: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 37 of 68

Student

#studentId : integer #studentType:char #studentName:String #feesPerMonth: double +Student() +Student(id,type,firstName,lastName) +setStudentId(id:integer):void +setStudentType(type:char):void +setStudentName(firstName:String,lastName:String) +setFeesPerMonth(double) +getStudentId():integer +getStudentType():char +getStudentName():String +getFeesPerMonth():double +displayStudentDetails():void

Hostelite -hostelName : String -roomNumber : integer +Hostelite() +Hostelite(integer,char,String,double

,String,integer)

+getHostelName():String +getRoomNumber():integer +displayStudentDetails():void

DayScholar -residentialAddress : String +DayScholar() +DayScholar(integer,char,String ,double,String) +getResidentialAddress():String +displayStudentDetails():void

Page 41: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 38 of 68

Steps mentioned in Assignment 2 of Day4 have to be repeated with the following

modification.

Step 1: displayStudentDetails() method needs to be defined in Student class. This method

should display the student details.

Step 2: The method displayStudentDetails() needs to be overridden in Hotelite and

DayScholar classes which will display additional student information(hostelName and

roomNumber or residentialAddress).

Note:

• Use super keyword to invoke the super class displayStudentDetails()

Step 3: In main method,

a. Create reference variable of type Student

b. Read the residential status of the student(from the command line argument

using String as described in earlier assignments- Hostelite or Dayscholar), if

(s)he is a hostelite then create object of type hostelite by invoking the

parameterized constructor and assign it to reference variable named

student otherwise, create object of type dayscholar by invoking the

corresponding parameterized constructor and assign it to reference

c. Invoke the corresponding displayDetails method and display the complete

student details

Step 4: Compile the program, fix the errors if any Step 5: Execute the program and verify the output

Estimated time: 35mins

Assignment 4: super keyword

Objective: Understand the significance of super keyword

Problem Description:

Analyze the problem and Debug the code

Problem 1:

Page 42: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 39 of 68

class Student{ protected int studentId; protected char studentType; protected String studentName; protected int semesterFees; protected int feesPerMonth; Student(int studentId){ this.studentId=studentId; } Student(int studentId,char studentType,String stu dName,int semFees){ super(); studentType=studentType; studentName=studName; semesterFees=semFees; } void displayDetails(){ } } class DayScholar extends Student{ private String residentialAddress; DayScholar(int studentId,char studentType ,String studName,int semFees,String res identialAddress){ this.residentialAddress=residentialAddress; super(int studentId,char studentType,String studName,int semFees); } void displayDetails(){ } } class CourseReg{ public static void main(String args[]){ DayScholar dayscholar = new DayScho lar (1001,'D',"Eugene",12000,"No 32 /68 Vijayanagar"); dayscholar.displayDetails(); } } After fixing the errors, perform the following:

Step 1: In main method,

Page 43: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 40 of 68

a. Create object of type Dayscholar by invoking the corresponding

constructor and assign it to reference variable dayscholar

b. Both the constructor of the Student class need to be invoked c. Fill the displayDetails() of the both the class

d. dayscholar.displayDetails() should invoke both derived and base class displayDetails()

Step 2: Compile the program, fix the errors if any Step 3: Execute the program and verify the output Estimated time: 40mins

Problem 2: class CourseRegistration{ static protected int regId; protected String courseName; CourseRegistration(){ regId++; } CourseRegistration (String cName){ courseName=cName; this(); } public void displayDetails(){ System.out.println("Registration ID :"+regId); System.out.println("CourseName :"+courseName); } } class Student extends CourseRegistration{ protected int studentId; protected char studentType; protected String studentName; private int semesterFees; private int feesPerMonth; Student(int studentId, String cName){ super(cName); this.studentId=studentId; } Student(int studentId,char studentType,String stu dName,int semFees,String cName){ super(cName); studentType=studentType;

Page 44: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 41 of 68

studentName=studName; semesterFees=semFees; } } class DayScholar extends Student{ private String residentialAddress; DayScholar(int studentId,char studentType, String studName, int semFees, String residentialAddress , String cName){ super(studentId,studentType,studName, semFees, cName); this.residentialAddress=residentialAddress ; } void displayDetails(){ //need to display the Details of the Stude nt and //DayScholar } } class CourseReg{ public static void main(String args[]){ DayScholar dayscholar = new DayScholar (1001,'D',"Eugene",12000,"No32/68 V ijayanagar","OOP"); dayscholar.displayDetails(); } } Debug the above code. Once done , follow the below steps-

Step 1: In main method,

a. Create object of type Dayscholar by invoking the corresponding

constructor and assign it to reference variable dayscholar

b. Both the constructor of the Student class and CourseRegistration class need to be invoked

c. Fill the displayDetails() of DayScholar class

d. dayscholar.displayDetails() should invoke DayScholar and

CourseRegistration displayDetails()

Step 2: Compile the program, fix the errors if any Step 3: Execute the program and verify the output

Summary of this assignment:

In this assignment, you have learnt

• Uses of super keyword

Estimated time: 25 mins

Page 45: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 42 of 68

Assignment 5: Constructor Invocation

Objective: Understand the order of constructor invocation

Problem Description:

Implement the following class diagram using Java.

Step 1:In the Student class

Student

#studentId : int #studentType :char #studentName :String +Student() +Student(int,char,String)

PostGradStudent #postCourseId : int #postCourseName :String #postCoursefees :int +PostGradStudent(int,String,int,int,char,String) +getpostCourseId():int +getpostCourseName:String

DayScholar -residentialAddress : String +DayScholar(int,String,int,char,String,String) +calculateFees():void +getFees():int

Page 46: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 43 of 68

• Define constructor o Student(): Used to increment the value of studentId each and every time

object is created. Hint : Use a static variable

o Student(sid,sType,sName ): Used to initialize the instance variables studentId,studentType,studentName and to invoke the constructor Student()

Step 2:In the PostGradStudent class

• Define constructor

o PostGradStudent(pCourseId,pCourseName,pCourseFees,

sid,sType,sName ): Used to initialize the instance variables studentId , studentType studentName to invoke the constructor

Student(sid,sType,sName )

• getter method o Using getter methods, display the PostGraduation Student details.

Step 2:In the DayScholar class

• Define constructor

DayScholar(pCourseId,pCourseName,pCourseFees, sid,sType,sName ,rAddress): Used initialize the instance variable residentialAddress and to invoke the constructor PostGradStudent

(pCourseId,pCourseName,pCourseFees, sid,sType,sName )

• calculateFees() o calculate the fees as below.

calulateFees(){

fees= postCoursefees /6; }

• getter method o Using getter methods, display the fees details.

Step 3:In the main method

• Create an object of type DayScholar with the values(5,”OOP”,16000,1001,’D’,”Manu”,”N0 32/3 Vijayanagar”)and assign it to reference variable named dayScholar

• Call the corresponding methods Step 4: Compile the program, fix the errors if any Step 5: Execute the program and verify the output

Note:

• super() can be used to invoke the base class constructor

Estimated time: 25 mins

Page 47: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 44 of 68

Summary of this assignment:

In this assignment, you have learnt

• How to implement constructors

• Constructor invocation

Assignment 6 : Dynamic Polymorphism

Objective: To understand the concept of Dynamic Polymorphism

Problem Description:

Analyze the problem and Debug the code and display the Result in the following

format

Student ID :1001

Student Type :D

Student Name:Thomas

Residential Address:No 32/3 Vijayanagar

class Student { protected int studentId; protected char studentType; protected String studentName; public void setStudentId(int sId){ this.studentId=sId; } public void setStudentType(char sType){ this.studentType=sType; } public void setStudentName(String sName){ this.studentName=sName; } public void getDetails(){ System.out.println("Student ID :"+studentId); System.out.println("Student Type :"+studentType) ; } } class DayScholar extends Student{ private String residentialAddress; public void setResAddress(String resAddress){ this.residentialAddress=resAddress; } public void getDetails(){

Page 48: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 45 of 68

super.getDetails(); System.out.println("Student Name "+studentName); System.out.println("Residential Address"+residentialAddress); } } class DynamicEx{ public static void main(String args[]){ Student dayScholar=new DayScholar(); dayScholar.setStudentId(1001); dayScholar.setStudentType('D'); dayScholar.setStudentName("Thomas"); dayScholar.setResAddress(); dayScholar.getDetails(); } }

Note:

A new method defined in the sub class cannot be called using the

super class reference

Estimated time: 15 mins

Summary of this assignment:

In this assignment, you have learnt

Dynamic polymorphism

Assignment 7:final keyword

Objective: Understand the significance of final keyword

Problem Description:

Reuse Assignment 6 of Day 4 to achieve the following:

Page 49: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 46 of 68

Step 1: Make the Student class as specified in the class diagram

Step 2: Data member semesterFees should be fixed as 12000

Step 3:displayDetail() should not be used in any of its derived classes to display the details

Step 4:calculateFees() method should be given as below : void calculateFees(){

Student

#studentId : integer #studentType:char #studentName:String # semesterFees: int #feesPerMonth:int +Student() +setStudentId(id:integer):void +setStudentType(type:char):void +setStudentName(firstName:String,lastName:String) +calculateFees():void +displayDetail():void

DayScholar -residentialAddress : String +DayScholar() +DayScholar(integer,char,String,double,String) +displayDaySDetails():void

Page 50: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 47 of 68

feesPerMonth = semesterFees / 6.0;

}

Step5:Make the class DayScholar in such a way that no other class should derive from

DayScholar

Step 6: Code the displayDaySDetails() to display the details of DayScholar

Step 7: In main method,

a. Create object of type DayScholar by invoking the corresponding constructor

and assign it to reference variable dayscholar

b. Set the value of all the data members with the help of setter method

c. Invoke the calculateFees method

d. Invoke the corresponding method to display the details of DayScholar and

Student

Step 6: Compile the program, fix the errors if any Step 7: Execute the program and verify the output

Estimated time: 25 mins

Summary of this assignment:

In this assignment, you have learnt

• Uses of final keyword

Assignment 8:Abstract Class

Objective: Understand the significance of super keyword and method overriding in

Inheritance.

Problem Description:

Modify the Assignment 3 of Day 4 with the following steps

Step 1: Make the Student class as abstract class

Step 2: Include an abstract method calculateFees(double)

Step 3: Define the method calculateFees(double) as follows in Dayscholar

class void calculateFees(double semesterFees){

feesPerMonth = semesterFees / 6.0;

}

Step 4: Define the method calculateFees(double) as follows in Hostelite class void calculateFees(double semesterFee){

feesPerMonth = semesterFees / 6.0; // Add hostel fees Rs.1200 feesPerMonth = feesPerMonth+ 1200;

}

Page 51: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 48 of 68

Step 5: In main method,

a. Create reference variable of type Student

b. Read the residential status of the student(from the command line argument

using String as described in earlier assignments- Hostelite or Dayscholar), if

(s)he is a hostelite then create object of type hostelite by invoking the

parameterized constructor and assign it to reference variable named

student otherwise, create object of type dayscholar by invoking the

corresponding parameterized constructor and assign it to reference

c. Also, Invoke the corresponding calculateFees method and display the

complete student details

Step 6: Compile the program, fix the errors if any Step 7: Execute the program and verify the output

Estimated time: 20 mins

Summary of this assignment:

In this assignment, you have learnt

• abstract class and abstract method

Review

What would be output for the following programs? If there is an error in the program, analyze

it, fix it and execute it

1.

class Parent{ private int num; public void setNum(int val){ num = val; } public int getNum(){ return num; } public void display(){ System.out.println("Number :"+num); } } class Child extends Parent{ private int val;

Page 52: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 49 of 68

public void setVal(int num){ val = num; } public int getVal(){ return val; } public void display(){ System.out.println("Number :"+num); System.out.println("Value :"+val); } } class CourseMgmt{ public static void main(String args[]){ Child child; child = new Child(); child.setNum(100); child.setVal(200); child.display(); } } 2.

class Parent{ private int num; public void setNum(int val){ num = val; } public int getNum(){ return num; } public void display(){ System.out.println("Number :"+num); } } class Child extends Parent{

Page 53: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 50 of 68

private int val; public void setVal(int num){ val = num; } public int getVal(){ return val; } public void display(){ super.display(); System.out.println("Value :"+val); } } class CourseMgmt{ public static void main(String args[]){ Child child; child = new Child(); child.setNum(100); child.setVal(200); child.display(); } }

3.

class Animal { public static void testClassMethod() { System.out.println("The class method in Ani mal."); } public void testInstanceMethod() { System.out.println("The instance method in Animal."); } } class Cat extends Animal { public static void testClassMethod() { System.out.println("The class method in Cat ."); } public void testInstanceMethod() {

Page 54: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 51 of 68

System.out.println("The instance method in Cat."); } public static void main(String[] args) { Cat myCat = new Cat(); Animal myAnimal = myCat; Animal.testClassMethod(); myAnimal.testInstanceMethod(); } } 4.

class Parent{ private int num; Parent(int num){ this.num = num; } public int getNum(){ return num; } } class Child extends Parent{ private int val; Child(int num,int val){ // To invoke super class constructor super(num); this.val = val; } public int getVal(){ return val; } } class CourseMgmt{ public static void main(String args[]){ Child child;

Page 55: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 52 of 68

child = new Child(100,200); System.out.println("Parent: Num:" + child.getNum( )); System.out.println("Child: Val:" + child.getVal() ); } }

5.

public class ClassA { public void methodOne(int i) { } public void methodTwo(int i) { } public static void methodThree(int i) { } public static void methodFour(int i) { } } public class ClassB extends ClassA { public static void methodOne(int i) { } public void methodTwo(int i) { } public void methodThree(int i) { } public static void methodFour(int i) { } }

Day 5 Assignments

Assignment 1: Package (Create, Compile & Execute )

Objective: Create and use Packages

Problem Description: To display student details using package program

Step1: Write the following program in a textpad

package courseregistration;

Page 56: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 53 of 68

class Student { protected int studentId; protected char studentType; protected String studentName; public void setStudentId(int sId){ this.studentId=sId; } public void setStudentType(char sType){ this.studentType=sType; } public void setStudentName(String sName){ this.studentName=sName; } public void getDetails(){ System.out.println("Student ID :"+studentId); System.out.println("Student Type :"+studentType) ; System.out.println("Student Name :"+studentName) ; } } class PackageEx{ public static void main(String args[]){ Student student=new Student(); student.setStudentId(1001); student.setStudentType('D'); student.setStudentName("Thomas"); student.getDetails(); } }

Step 2:Save the program using PackageEx.java

Page 57: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 54 of 68

Step 3: If the command prompt does not appear during the compilation or an execution do

the (Step4 & Step 5)

Step 4: Go to configure tab and select the Preferences-Tools-Compile Java and select Prompt for parameters

Page 58: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 55 of 68

Step 5: In Tools-Run Java Application and select Prompt for parameters

Step 6: Give ctrl+1 for the compilation and give as below in the prompt

–d . PackageEx.java

It will create a package in the current working directory

Page 59: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 56 of 68

Step 7:Give ctrl+2 for run the program and give as below in the prompt

courseregistration/PackageEx

Page 60: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 57 of 68

Estimated time: 25 mins

Summary of this assignment:

In this assignment, you have learnt

• How to create, save , compile and execute the Package program using textpad

Assignment 2 : Access Specifier

Objective: Understand the use of various Access specifier

Problem Description:

Analyze the problem, Debug the code and display the result in the following format

Student Id:1001

Student Type:D

Student Name:Dinil

Page 61: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 58 of 68

package studentpack; public class Student { int studentId; private char studentType; protected String studentName; public void setStudentId(int sId){ this.studentId=sId; } public void setStudentType(char sType){ this.studentType=sType; } public void setStudentName(String sName){ this.studentName=sName; } } package registrationpack; class DayScholar extends Student{ private String residentialAddress; public void setResAddress(String resAddress){ this.residentialAddress=resAddress; } public void getDetails(){ System.out.println("Student Id:"+studentId); System.out.println("Student Type:"+studentTy pe); System.out.println("Student Name:"+studentNa me); } } class Registration{ public static void main(String args[]){ DayScholar dayScholar=new DayScholar(); dayScholar.setStudentId(1001); dayScholar.setStudentType('D'); dayScholar.setStudentName("Dinil"); dayScholar.getDetails(); } }

Note: Compile the class Student separately in a package called courseregistration. There

is no error in this code. Compile the DayScholar and Registration classes separately in the

package registrationpack. There are some access related errors, analyse them, debug and

execute to get the output.

Page 62: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 59 of 68

Estimated time: 20 mins

Summary of this assignment:

In this assignment, you have learnt

• Access specifier

• package and import statement

Assignment 3:Interfaces

Objective: Understand the significance of interface

Problem Description:

Type the following code, debug the code and execute the same.

interface InterOne{ int varOne; int varTwo=100; void methodOne(); void methodTwo(); } class Example implements InterOne{ void methodOne(){ varTwo=varTwo+10; System.out.println("Value of varTwo:"+var Two); System.out.println("Good Morning"); } public void methodTwo(){ System.out.println("Good Afternoon"); } } class DemoInterface{ public static void main(String args[]){ Example obj=new Example(); obj.methodOne(); obj.methodTwo(); } }

Page 63: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 60 of 68

Estimated time: 15 mins

Summary of this assignment:

In this assignment, you have learnt

Interfaces

Assignment 4: UML – Use Case Diagram

Objective: Analysis of the case study and design the Use Case Diagram.

Problem Description: Course Management System

A Course Management System needs to be developed for an engineering college. The college wants an automated system to replace its manual system for purpose of allocation of students to courses and lecturers to courses. There are around 10000 students and 500 faculty members in the college. The engineering college provides graduation and post graduation in the various branches of engineering.

In any branch, the entire duration is divided into semesters. Each semester includes various courses. Students admitted into the college can apply for various courses. The courses are elective in nature. The student needs to select two electives. The electives are offered from 5th semester onwards for graduate students and from 3rd semester onwards for the post graduate students. The graduate students need to undergo a final year project in the fourth year of engineering whereas the post graduate student undergoes a thesis submission in the second year. The complete list of courses, lecturers and students is maintained in the college. The list is constant and cannot be updated by the system. The automated system uses this list for allocation of courses.

The lecturers can be categorized into full time lecturers and visiting members. The full time lecturers have target days of course delivery and are paid salary every month. The visiting members get paid per lecture basis and do not have any target days.

The system is used by the admin staff to register students admitted to college to the courses they opted. The system needs to be authenticated with a login id and password. The system would be used by the students to view the marks and the attendance details also. The system is used by the HOD (Head of the department) to allocate courses to the lecturers. At the beginning of the semester, the HOD will do the allocation of lecturers to the classes for his department. The HOD may make changes in the allocation during the progress of the course. The system maintains a history of all the lecturers who have handled the courses throughout the semester .The lecturer will use the system to update the marks of the student (project, assignment, internal test marks and the semester end examination marks). The lecturer will also mark the attendance of the students through the system.

In addition to the above, the system also keeps track of the residential status of the student. The student may be a host-elite or a day scholar. If (s)he is host-elite, the system will maintain his / her hostels name, room number and the fees pertaining to the same.

Page 64: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 61 of 68

Note: This is the same case study provided in Day 1 assignment.

Step 1: Identify all the ‘nouns’ i.e. the actors in the problem statement.

Step 2: Identify the activities i.e. the use cases. Connect the actors to the use cases.

Step 3: Identify the relationships.(Generalization, specialization, Includes)

Estimated time: 30 mins

Summary of this assignment:

In this assignment, you have learnt

• How to analyze and design the Use case diagram for a given problem statement.

Assignment 5: UML – Class Diagram

Objective: Analysis of the case study and design the class diagram.

Problem Description: Course Management System

Step 1: Identify all the ‘nouns’ (type of objects or classes) in the case study given in previous

case study.

Step 2: Identify the commonalities between classes (Generalization) if it is obvious.

Step 3: Identify all the member variables and methods the class should have.

Step 4: Identify the member variables and methods (getter and setter methods for each and

every attribute) for the rest of the classes.

Step 5: Ensure that the class is fully independent of other classes and contains all the

attributes and methods necessary.

Step 6: Keep all data members private (-) or protected (#).

Step 7: The methods in class should completely abstract the functionality using

encapsulation. The methods in the class should not be a force fit of procedural code into a

class.

Step 8: Inherit and extend classes from the base class ONLY IF situation has scope for it. Shift

the commonalities among classes to the base class

Step 9: Define the “Has-A” and “Uses-A” relationship among classes

(Is-A has been defined already in previous step)

Page 65: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 62 of 68

Step 10: Keep the number of classes in your application under check (Do not create any

unnecessary classes)

Step 11: Review your design

Estimated time: 30 mins

Summary of this assignment:

In this assignment, you have learnt

• How to analyze design a class diagram for the given problem statement.

Assignment 6: Case study of D-Rail Inc.

D-Rail Inc. is a metropolitan railway corporation operating in a large city and its suburbs. D-

Rail has an ambitious plan to computerize its ticketing system. The IT department of D-Rail

has come up with an OO design for their ticketing system. Now, they require the design to be

validated for correctness.

The ticketing system addresses the needs of the metro rail service of D-Rail between the city

and its suburbs.

Requirements of the Ticketing System:

A Ticketing Clerk at one of the D-Rail counters can issue the following kinds of tickets to

commuters:

One Time ticket: Used for one way travel. It has to be used the same day it is issued.

Return ticket: Used for two way travel. Onward journey has to be done on the date of

issue. However, the return journey can be done any time within a week from the date of

issue.

Multi-use ticket: Used for traveling many times between an origin and destination

stations (onward or return). Multi-use tickets are available 10, 15 and 20 trips

denominations, which are also specified in the ticket. However the ticket has an expiry

date which is two months from the date of issue. Every time the ticket is used, one trip is

deducted.

All tickets have information on the origin and destination stations.

All the tickets issued are magnetic tickets which store the entire ticket information. This

information will be verified by the ticket reading machine at the entry points.

Step 1: Design the Class diagram

Page 66: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 63 of 68

Step 2: Implement the Class diagram using Java

Estimated time: 30 mins

Summary of this assignment:

In this assignment, you have learnt

• To understand a complex software system and design the Use Case and Class diagrams

Self review

What would be the output of the following programs?

1.

abstract class Animal { abstract static void testClassMethod(); public void testInstanceMethod() { System.out.println("The instance method in Animal."); } } class Cat extends Animal { public static void testClassMethod() { System.out.println("The class method in Cat ."); } public void testInstanceMethod() { System.out.println("The instance method in Cat."); } public static void main(String[] args) { Cat myCat = new Cat(); Animal myAnimal = myCat; Animal.testClassMethod(); myAnimal.testInstanceMethod(); } } 2.

interface Count { short counter=0; void countUp(); } public class TestCount implements Count{ public static void main(String args[]){ TestCount test=new TestCount(); test.countUp();

Page 67: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 64 of 68

} public void countUp(){ for (int x=6;x>counter;x--,++counter){ System.out.println(" "+counter); } } } 3.

interface ParentOne{ int pOne=1; void printParentOne(); } interface ParentTwo{ int pTwo=2; void printParentTwo(); } interface Child extends ParentOne, ParentTwo{ int child=3; void printChild(); } class InheritClass implements Child{ public void printParentOne(){ System.out.println(pOne); } public void printParentTwo(){ System.out.println(pTwo); } public void printChild(){ System.out.println(child); } } class TestInterface{ public static void main(String args[]){ InheritClass inclass=new InheritClass(); inclass.printParentOne(); inclass.printParentTwo(); inclass.printChild(); } }

Page 68: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 65 of 68

Case Study based Assignments

Case Study 1 – Banking System

Day 2 Assignment 1: If-else condition

Objective: Understand control structures Problem Description: To validate the account balance with reference to the Intermediate Level Case study provided. Step 1: Create a class called MinAccountBalValidation with the main method Step 2: Create a class called Account with the following Class diagram Step 3: Create an object of Account in the main method Step 4: Set the amount to 5000 using the setter method Step 5: Write the logic in the main method to check if the amount remaining is less than 500. If so display a message “The balance is below minimum value”. Otherwise display the existing balance.

Estimated time: 20 minutes Summary of this assignment: In this assignment, you have learnt

• If else conditional statements

Case Study 2 – Travel Management System

Day 2 Assignment 1: If-else condition

Account -accAmount: int -accNo:int -custName: String

+getAccNo(): int +getAmount(): int +getCustName(): String +setAccNo(): void +setAmount(): void +setCustName(): void

Page 69: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 66 of 68

Objective: Understand control structures Problem Description: To validate the mode of travel with reference to the Intermediate Level Case study provided. Step 1: Create a class called Demo with the main method Step 2: Create a class called Travel with the following Class diagram Step 3: Create an object of Travel in the main method Step 4: Set the mode of travel to F using the appropriate setter method Step 5:Set the number of tickets to 3 using the appropriate setter method Step 6: Write the logic in the main method to check the mode of travel. Set the amount to paid as service charges as per the following table:

SE NO MODE OF TRAVEL SERVICE CHARGE PERTICKET

1 F(FOR FLIGHT) 500

2 T(FOR TRAIN) 100

3 B(FOR BUS) 50

The calculation of service charge is as follows:

Total Service charge =Service Charge perTicket * No. of Tickets Estimated time: 20 minutes Summary of this assignment: In this assignment, you have learnt

• If else conditional statements

Day 3 Assignment 2: Strings

Objective: To understand Strings

Travel -modeOfTravel: char -noOfTickets:int -amount:double

+getModeOfTravel (): char +getNoOfTickets():int +getAmount():double +setAmount(double):void +setModeOfTravel (char): void +setNoOfTickets (int): void

Page 70: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 67 of 68

Problem Description: To write the autogeneration of the ticket number based on some criterion. Step 1: Create a class called AutoGenerate with the main() method Step 2: Write the logic to autogenerate the booking confirmation number as follows:

Format of Booking confirmation number:

Y Y Y X N N N Z Z Z Z

Here,

o YYY denotes travel company code 115 o X denotes mode of travel F-Flight, T-Train, B-Bus o NNN denotes Flight/Train/Bus Code such as 101-105 for

flight,201-205 for Train and 301-305 for Bus o ZZZZ denotes a unique code, which starts from 0001 in

a branch and increments sequentially by 1 for each booking request

Step 3: Test the code by providing the following inputs to the fields as follows:

SE NO. VALUES FOR X

VALUES FOR NNN

VALUES TO BE GENERATED FOR ZZZZ

CASE 1 F 102 0001

CASE 2 T 202 0002

CASE 3 B 304 0003

Note: The values for the different fields may be provided through the program itself statically. Estimated time: 20 minutes Summary of this assignment: In this assignment, you have learnt

• If else conditional statements and Strings

Day 4 Assignment 3: Inheritance

Page 71: Lab guide  object oriented programming using java_la1026_ver1.2

Infosys Technologies Limited Object Oriented Programming using Java

ER/CORP/CRS/ LA1026 CONFIDENTIAL Version No. 1.2 68 of 68

Objective: To understand the application of Inheritance concept Problem Description: To identify situations where Inheritance is to be applied with respect to Intermediate Case study provided. Scenario 1: A user needs to provide details of the travel. The travel details include mode of travel, source, and destination, date and time, ticket details and travel class type. The type can be

� Flight-Economy( less expensive) or Business (upper or

executive class) � Train-II Class (less expensive) or I Class(upper or executive

class) � Bus – Non-AC (ordinary) or AC (Air Conditioned)

The difference in the travel type amount to the difference in the fares only. What will be the structure of the class and would Inheritance concept be applicable to the mentioned scenario? Scenario 2: The taxi can be booked for difference kinds of tours. The tours are as follows:

o One way travel o One day travel o Package tour (more than one day travel)

The One way travel has a destination, the charges are calculated based on the number of kilometers multiplied by two. The one day travel consists of starting time, bus number, sight seeing locations and the charge is a lumpsum amount per person. The package tour is a part of the stay in the hotel and contains the locations to be visited, the travel schedule and the number of persons to travel. What will be the class structure and would inheritance concept be applicable to this scenario?

Estimated time: 20 minutes Summary of this assignment: In this assignment, you have learnt

• Inheritance concept and its application