0% found this document useful (0 votes)
120 views

LM OOP Java (Azhar Jamil)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
120 views

LM OOP Java (Azhar Jamil)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 134

BIIT Series

Lab Manual
Object Oriented
Programming
A simplified practical work book of Object Oriented programming course
for Computer Science, Information Technology and Software
Engineering students

Student Name:______________________________________
Registration No:___________________________________
Section / Semester: _________________________________
Submission Date: _____________________________________
Student Signature: __________________________________

Marks Obtained: _______________________________________


Maximum Marks: _____________________________________
Examiner Name/Sig: ___________________________________

Azhar Jamil
Lab Manual Object Oriented Programming: First Edition
(Publisher:???)
Author(s): Azhar Jamil
ISBN: ????
Publication Date: ????
A publication of BIIT Series
Copyrights © Reserved By Authors

Learning Objectives: By the end of the lab work, students should have following skills;

Sr. Learning Objective LAB No.

10

11

12

13

14

15

16
Table of Contents
LAB # 1________________________________________________________________________5
Theory: Familarity with Java Environment_____________________________________________5
1.1: Installing JDK________________________________________________________________7
Task 1.1:_Executing Basic Java Commands___________________________________________15
Comments/Signature (Student & Teacher):____________________________________________15
LAB # 2________________________________________________________________________16
Theory: Primitive Data Types, Expressions and Branches__________________________________7
Task 2.1: Exercise - 1 (Basics)______________________________________________________19
Task 2.2: Bike Race _____________________________________________________________20
Comments/Signature (Student & Teacher):____________________________________________21
LAB # 3_______________________________________________________________________22
Theory: Use of Operators, Expressions, control Flow____________________________________22
Task 3.1: Implementation of Binary search mechanism___________________________________21
Comments/Signature (Student & Teacher):____________________________________________21
LAB # 4_______________________________________________________________________27
Theory: Introduction to classes______________________________________________________27
Task 4.1: Use of Classes __________________________________________________________27
Task 4.2: Array of Objects________________ ________________________________________ 28
Comments/Signature (Student & Teacher):____________________________________________30
LAB # 5_______________________________________________________________________31
Theory: An Overview of Objects and Classes (cont..)____________________________________31
Task 5.1: Demonstration of Classes and Objects________________________________________31
Task 5.2: Access Specifiers_______________________________________________________ 32
Comments/Signature (Student & Teacher):____________________________________________32
LAB # 6 ______________________________________________________________________33
Theory: Theory: Constructors and Destructors_________________________________________33
Task 6.1: Counting number of objects created__________________________________________33
Comments/Signature (Student & Teacher):____________________________________________35
LAB # 7_______________________________________________________________________36
Theory: Constructor overloading____________________________________________________38
Task 7.1: Auto Generation of Student Arid No_________________________________________38
Comments/Signature (Student & Teacher):____________________________________________40
LAB # 8_______________________________________________________________________41
Theory: Friend Functions and Friend Classes__________________________________________ 41
Task 8.1: Exercise________________________________________________________________42
Comments/Signature (Student & Teacher):____________________________________________44
LAB # 9_______________________________________________________________________45
Theory: Inheritance_______________________________________________________________45
Task 9.1: Exercise________________________________________________________________46
Comments/Signature (Student & Teacher):____________________________________________48
LAB # 10______________________________________________________________________49
Theory: inheritance (cont…)_______________________________________________________49
Task 10.1: Exercises______________________________________________________________50
Comments/Signature (Student & Teacher):____________________________________________51
LAB # 11______________________________________________________________________52
Theory: Inheritance and Method Overriding___________________________________________52
Task 11.1: Exercises______________________________________________________________53
Comments/Signature (Student & Teacher):____________________________________________57
LAB # 12______________________________________________________________________58
Theory: File Handling_____________________________________________________________58
Task 12.1:Files Input Output_______________________________________________________58
Task 12.2: Reading an Lines fromDisk_______________________________________________ 61
Comments/Signature (Student & Teacher)_____________________________________________62
LAB # 13______________________________________________________________________63
Theory:Character I/O_____________________________________________________________63
Task 13.1: Writing characters_______________________________________________________63
Task 13.2: Reading characters______________________________________________________64
Comments/Signature (Student & Teacher):____________________________________________66
LAB # 14______________________________________________________________________67
Theory: Object Read Write_________________________________________________________67
Task 14.1: Writing Objects_________________________________________________________67
Comments/Signature (Student & Teacher):____________________________________________73
LAB # 15______________________________________________________________________74
Theory: Object Read Write (cont..)__________________________________________________74
Task 15.1: Writing an object to Disk_________________________________________________74
Task 15.2: Reading an object from Disk _____________________________________________76
Task 15.3: Random Access_________________________________________________________78
Comments/Signature (Student & Teacher):____________________________________________79
LAB # 16______________________________________________________________________80
Theory: String___________________________________________________________________80
Task 16.1: String functions_________________________________________________________80
Comments/Signature (Student & Teacher):____________________________________________86
-5-

LAB # 1

Familiarity with Java Environment


This section elaborates the environment of software tool to be used in LAB. Note that you may use an
updated version of the software tool which has been described here.
Steps:
Task 1.1: Installing JDK

1. Open any search engine and type “download JDK”

1.2. Installing Eclipse


Lab Manual BIIT Series

5
-6-

2. Open first link and the following oracle.com will open.

1.2. Installing Eclipse


Lab Manual BIIT Series

6
-7-

3. Click on dowload.

1.2. Installing Eclipse


4. Agree licence aggrement and select required download (Linux, Mac, Windows) accordingly.
5. After download, install the JDK.

1.2. Installing Eclipse Lab Manual BIIT Series

1. Download eclips using following the steps

7
-8-

2. Click download eclipse for required OS

1.2. Installing Eclipse


Lab Manual BIIT Series

3. Install Eclipse by following steps.


4. Now run eclipse

Figure 1

8
-9-

1.2. Installing Eclipse


Figure 2

Lab Manual BIIT Series

Figure 3

9
- 10 -

1.2. Installing Eclipse


Figure 4

Lab Manual BIIT Series

Figure 5

10
- 11 -

1.2. Installing Eclipse


Figure 6

Lab Manual BIIT Series

Figure 7

11
- 12 -

1.2. Installing Eclipse


Figure 8

Lab Manual BIIT Series

Figure 9

12
- 13 -

1.2. Installing Eclipse


Figure 10

Lab Manual BIIT Series

Figure 11

13
- 14 -

1.2. Installing Eclipse


Figure 12

Lab Manual BIIT Series

Figure 13

14
AJ/Lab Manual -15- Object Oriented Programming

Task 1.1: Executing Basic Java Commands

Execute the following commands (in the given sequence) and write the answers below each expression.
1. System.out.println(“Hello Class!”);

2. System.out.print(“This is print statement in java”);

3. System.out.println(“This is First”+”Lab task”);

4. System.out.print(4);

Comments/Signature (Student & Teacher):


5. System.out.print(5+34);

6. System.out.println(true);

7. System.out.println(“Sum of “+4+” and “+5+” is =”+(4+5));


Lab Manual BIIT Series

8. System.out.println(“Sum of “+4+” and “+5+” is =”+4+5);

9. System.out.println(“Sum of “+4+” and “+5+” is =”+(40.5/5));

10. System.out.println(“Sum of “+4+” and “+5+” is =”+(43+5.3));

Comments/Signature (Student & Teacher):

15
AJ/Lab Manual -16- Object Oriented Programming

LAB # 2
Primitive Data Types, Expressions and Branches

Analyze and do as directed.

1. What is the result of each of these statements?


int i;
i = 4 + 3 * 2;
i = 4 + (3 * 2);

Comments/Signature (Student & Teacher):


i = (4 + 3) * 2;
2. After executing this code, will showSize contain both values or just the last value?
double showSize = 9.5;
showSize = 10;
3. Will these compiles? If not, why not?
int mySize = 8.5; Lab Manual BIIT Series

int fraction = 4/8;


4. Is the result 0.0 or 0.5 for each of these? Why?
double fraction = 4 / 8;
fraction = 4.0 / 8;
fraction = 4 / 8.0;
fraction = (int) 4 / 8.0;
fraction = (double) (4 / 8);
5. What does the % operator do? What is the value of num after each line?
int num = 10 % 2;
int num = 10 % 3;
int num = 5 % 3;
int num = 120 % 5;
int num = 1397836563 % 2;
6. What is the result? In other words, is assignment left-to-right or right-to-left associative?
int a = 1;
int b = 2;
int c = 3;
int d = 4;

16
AJ/Lab Manual -17- Object Oriented Programming

a = b = c = d;

7. What is print out? Key is determining when the value of a variable is changed.
int a = 1;
System.out.print("a=");
System.out.print( (a = 2) + a);
int b = 1; System.out.print(", b=");
System.out.print( b + (b = 2));
8. boolean completed = false;
if (completed || !completed) {

Comments/Signature (Student & Teacher):


System.out.println("hmmm");
} else {
System.out.println("HMMM");
}
Is there any value of completed that will result in output of "HMMM"?
9. What is printed out?
Lab Manual BIIT Series

char ch = 'b';
String str = "|";
switch (ch) {
case 'a': str += ch;
case 'b': str = ch + str;
case 'c': str += 'c';
break;
case 'd': str += 'd';
default:
str += ch;
break;
}
System.out.print(str);

10. boolean happy = false; //Will both of the following if statements result in the same output?
if (happy) System.out.println("happy");
else System.out.println("not happy");
System.out.println("done");
17
AJ/Lab Manual -18- Object Oriented Programming

if (happy) {
System.out.println("happy");
} else {
System.out.println("not happy");
}
System.out.println("done");

11. Write the code to write the category name for a character in a char variable named ch. Ignore case.
You may try using both switch and if statements to see which is easier for someone else to read.

Characters Category

Comments/Signature (Student & Teacher):


1 3 5 7 9 Odd Number
24680 Even Number
aeiou Vowel
Letters other than vowels Consonant
.,;'?! Punctuation

12. Write a program to prompt the user for their age. Based on their age print out which generation they
Lab Manual BIIT Series

are, when they think youth ends, when old age begins and what age is considered the prime of life.

What is your age: 45


You are Generation X.
Youth ends at 31, old age begins at 65.
The prime of life is age

Generation Youth ends at old age begins at prime of life age is

millennials Between 21 and 36 40 59 36


X Between 37 and 52 31 65 47
boomers Between 52 and 72 31 73 50
Silent 73 and older 35 73 52

Task 2.1: Exercise - 1 (Basics)

a) Displaying default value of all primitive data types


18
AJ/Lab Manual -19- Object Oriented Programming

Aim: To write a JAVA program to display default value of all primitive data type of JAVA

class defaultdemo {
static byte b;
static short s;
static int i;
static long l;
static float f;
static double d;
static char c;

Comments/Signature (Student & Teacher):


static boolean bl;
public static void main(String[] args)
{
System.out.println("The default values of primitive data types are:");
System.out.println("Byte :"+b);
System.out.println("Short :"+s);
Lab Manual BIIT Series

System.out.println("Int :"+i);
System.out.println("Long :"+l);
System.out.println("Float :"+f);
System.out.println("Double :"+d);
System.out.println("Char :"+c);
System.out.println("Boolean :"+bl);
}
}
Write Output here:
|
|
|
|
|
|

Task 2.2: Bike Race

19
AJ/Lab Manual -20- Object Oriented Programming

Aim: Five Bikers Compete in a race such that they drive at a constant speed which may or may not
be the same as the other. To qualify the race, the speed of a racer must be more than the average
speed of all 5 racers. Take as input the speed of each racer and print back the speed of qualifying
racers.
Program: import java.util.*;
class racedemo {
public static void main(String[] args)
{
float s1,s2,s3,s4,s5,average;
Scanner s = new Scanner(System.in);
System.out.println("Enter speed of first racer:");

Comments/Signature (Student & Teacher):


s1 = s.nextFloat();
System.out.println("Enter speed of second racer:");
s2 = s.nextFloat();
System.out.println("Enter speed of third racer:");
s3 = s.nextFloat();
System.out.println("Enter speed of fourth racer:");
Lab Manual BIIT Series

s4 = s.nextFloat();
System.out.println("Enter speed of fifth racer:");
s5 = s.nextFloat();
average=(s1+s2+s3+s4+s5)/5;
if(s1>average)
System.out.println("First racer is qualify racer:");
else if(s2>average)
System.out.println("Second racer is qualify racer:");
else if(s3>average)
System.out.println("Third racer is qualify racer:");
else if(s4>average)
System.out.println("Fourth racer is qualify racer:");
else if(s5>average)
System.out.println("Fifth racer is qualify racer:");
}}

Write Output here:


| Write code here.
20
AJ/Lab Manual -21- Object Oriented Programming

|
|
|
|
|
|
|
|
|
|
|

Comments/Signature (Student & Teacher):


Lab Manual BIIT Series

Comments/Signature (Student & Teacher):

21
AJ/Lab Manual -22- Object Oriented Programming

LAB # 3
Use of Operators, Expressions, control Flow

1. What is the difference between these statements?


int x = 34;
int y = ++x;

int x = 34;
int y = x++;

Comments/Signature (Student & Teacher):


2. Does k contain 6 at the end? Why or why not?
int k = 5;
k = k++;
//k++ has a value for the expression as well as changes k,
//which is different with post increment and post decrement operators.
Lab Manual BIIT Series

//Also, this is overwriting any changes to k with the result of


//the value of the expression.

3. int x = 20;
int j = 4;
int y = x++ + --j;

4. int m = 14;
int n = --m + m--;
5. int m = 4;
int n = m -- - -- m;
6. int i=10;
while(i>1){
System.out.println(++i);
}
7. int i = 4;
while ( i != 1 ) {
System.out.println( i); i -= 2; }
22
AJ/Lab Manual -23- Object Oriented Programming

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


if ( i == 0)
break;
}
9. for ( int i = 0; i < 5; ++i) {
if ( i < 4) {
continue;
}
System.out.println("in body of for loop");
}
10. for ( int i = 0; i < 10; i++ ) {

Comments/Signature (Student & Teacher):


if ( i % 2 == 0 ) {
continue;
}
System.out.println( i + " must be odd");
}
Lab Manual BIIT Series

11. When will this code finish executing?


Scanner input = new Scanner(System.in);
boolean done = false; while ( !done) {
System.out.print("Enter an integer: ");
if ( input.nextInt() < 0) {
done = true;
}
}
12. When will this code finish executing?
int i=10; while(i>1){
System.out.println(i + 1);
}
13. When will this code finish executing?
for ( int i = 0; i < 10; ++i) {
for ( int j = i; j < 10; j+= 2) {
System.out.print("* ");
} System.out.println();
}
23
AJ/Lab Manual -24- Object Oriented Programming

14. When will this code finish executing?


boolean done = false; int counter = 0; do {
System.out.print("*");
if ( counter++ > 5) {
done = true;
} } while ( !done );

15. What value will be returned by this method.


public static int mystery(int n) {
int s = 0;

Comments/Signature (Student & Teacher):


int d = -1;
while ( n > 0) {
d = n % 10;
s += d % 2;
n /= 10;
}
Lab Manual BIIT Series

return s;
}
16. What is the sum after this executes?
int sum = 0; for (int i = 5; i >= 0; --i) {
for (int j = 1; j < 4; ++j) {
if (j % 2 == 1)
continue;
sum++; }
if (i > 0)
break; }
System.out.println("sum=" + sum);

Task 3.1: Implementation of Binary search mechanism

24
AJ/Lab Manual -25- Object Oriented Programming

Aim: To write a JAVA program to search for an element in a given list of elements using binary search
mechanism.
Program:
import java.util.Scanner;
class binarysearchdemo
{
public static void main(String args[])
{
int n, i, num,first, last, middle;
int a[ ]=new int[20];
Scanner s = new Scanner(System.in);

Comments/Signature (Student & Teacher):


System.out.println("Enter total number of elements:");
n = s.nextInt();
System.out.println("Enter elements in sorted order:");
for (i = 0; i < n; i++)
a[i] = s.nextInt();
System.out.println("Enter the search value:");
Lab Manual BIIT Series

num = s.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( a[middle] < num )
first = middle + 1;
else if ( a[middle] == num )
{
System.out.println("number found");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
25
AJ/Lab Manual -26- Object Oriented Programming

}
if ( first > last )
System.out.println( " Number is not found");
}}

Write output of example code here:

|
|
|

Comments/Signature (Student & Teacher):


|
|
|

Lab Manual BIIT Series

Comments/Signature (Student & Teacher):

26
AJ/Lab Manual -27- Object Oriented Programming

Lab 04
Introduction to classes
A class is an extension to the structure data type. Data member should be grouped in private access
specifier and member functions are normally clustered together in public section. Attempting to access
private members from outside the class will cause syntax error.

Task 4.1: Use of classes

Q#1: Write a class named Person with attributes name of the person, his/her age, contact number,
address and gender. Also write following functions to input and display his data.

Comments/Signature (Student & Teacher):


1) getPersonData()
2) showPersonData()
In main() program create 5 objects of type person and take input for them. After getting the input from
user find and display the youngest person among five persons and display his name and age.
| Write code here.
|
Lab Manual BIIT Series

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27
AJ/Lab Manual -28- Object Oriented Programming

|
|
|
|
|
|
|
|
|
|
|

Comments/Signature (Student & Teacher):


|

Task 4.2: Array of Objects

Q #2: Modify the above class person so that user can get data for more than 50 students. Note: Use the
Lab Manual BIIT Series

concept of array of objects.


In main() program declare an array of person of size 60 and take fill that array by calling function
input(person arr[]). After taking the input from the user,display all those students who belongs to
Rawalpindi (using dot operator).
| Write code here.
|
|
|
|
|
|
|
|
|
|
|

28
AJ/Lab Manual -29- Object Oriented Programming

|
|
|
|
|
|
|
|
|

Comments/Signature (Student & Teacher):


|
|
|
|
|
Lab Manual BIIT Series

|
|
|
|
|
|

Q #3: Create a class called employee with the following details as variables within it.
1. Name of the employee
2. Age
3. Designation
4. Salary
Write a JAVA program to create array of objects for the class to access these and print the name, age,
designation and salary.
| Write code here.
|
|
|
29
AJ/Lab Manual -30- Object Oriented Programming

|
|
|
|
|
|
|
|
|
|
|
|

Comments/Signature (Student & Teacher):


|
|
|
|
|
| Lab Manual BIIT Series

|
|
|
|
|
|
|
|
|
|
|
|
|
|

Comments/Signature (Student & Teacher):

30
AJ/Lab Manual -31- Object Oriented Programming

LAB # 05
An Overview of Objects and Classes (cont..)

In object-oriented programming language java the data and functions


(procedures to manipulate the data) are bundled together as a self-
contained unit called an object. A class is an extended concept similar
to that of structure in C programming language, this class describes
the data properties alone. In java programming language, class
describes both the properties (data) and behaviors (functions) of
objects. Classes are not objects, but they are used to instantiate
objects. Lab Manual BIIT Series

A typical java program would contain four sections as shown in the


below Fig. These sections may be placed in separate code files and
then complied independently.

Include Header Files

Class Declaration

Member Function Definition

Main Function Program


AJ/Lab Manual -32- Object Oriented Programming

Features of Class:

Classes contain data known as members and member functions. As a unit, the
collection of members and member functions is an object. Therefore, these
units of objects make up a class.

Task 5.1: Demonstration of Classes and Objects

Q.1: Write a program which demonstrates Classes and objects.

Objective: At the end of this exercise, students should be able to understand


following points:
Lab Manual BIIT Series

1. Class and object.


2. Crating class and object.
3. Defining function in different ways.
4. Concept of Access specifier like private, public etc.
AJ/Lab Manual -33- Object Oriented Programming

Task 2.2: Access Specifiers


Q.2: Create a class called student with the following details as variables within it.

1. Name of the student

2. Age

3. Year of study

4. Semester

5. 5 different subject marks in array

Write a JAVA program to create object for the class to access these and print the Name, age, year,
semester and grade according to their percentage of marks scored.
Lab Manual BIIT Series

90 % and above – A+ grade

80% to 89% -- A grade

70% to 79% -- B grade

60% to 69% -- C grade

50% to 59% -- D grade

<50% -- F grade

Note: data members should not be accessed from main() program.

Comments/Signature (Student & Teacher):


AJ/Lab Manual -34- Object Oriented Programming

LAB # 06
Theory: Constructors and Destructors

Constructors and Destructors are special member functions of a class


for initializing and disposing of objects belonging to that class.

Java provides a well-defined mechanism, for initializing an object


when it is created, by means of a constructors; same way when an
object is no more needed, java defines a way to scrap it off, by means
of a destructors.

Lab Manual BIIT Series

Task 6.1: Counting number of objects created

Q #1: Create a class for counting the number of objects created and
destroyed within various block using constructor and destructors.

Implement the code and write here.

|
AJ/Lab Manual -35- Object Oriented Programming

| Lab Manual BIIT Series

|
AJ/Lab Manual -36- Object Oriented Programming

Q#2. Write a program to demonstrate the use of constructor and


destructor in the class template. The program is used to find the
bigger of two entered numbers.
Lab Manual BIIT Series

Implement the code and write here.

|
AJ/Lab Manual -37- Object Oriented Programming

| Lab Manual BIIT Series

|
AJ/Lab Manual -38- Object Oriented Programming

Lab Manual BIIT Series

Comments/Signature (Student & Teacher):


AJ/Lab Manual -39- Object Oriented Programming

Lab 07
Constructor overloading
Lab Manual BIIT Series

Q#3. Write a program to perform addition of two complex numbers


using constructor overloading. The first constructor which takes no
argument is used to create objects which are not initialized, second
which takes one argument is used to initialize real and imaginary
parts to equal values and third which takes two argument is used to
initialized real and imaginary to two different values.

Write code here after implementation.

|
|
|
|
AJ/Lab Manual -40- Object Oriented Programming

|
|
|
|
|
|
|
|
|
|
|
Lab Manual BIIT Series

|
|
|
|
|
|
|
|
|
|
|
|
|
AJ/Lab Manual -41- Object Oriented Programming

|
|
|
|
|
|
|
|
|
|
|
Lab Manual BIIT Series

|
|
|
|
|
|
|
|
|
|
|
|
|
AJ/Lab Manual -42- Object Oriented Programming

|
|
|

Lab Manual BIIT Series


AJ/Lab Manual -43- Object Oriented Programming

|
|
|

Lab Manual BIIT Series


AJ/Lab Manual -44- Object Oriented Programming

|
|
|
|
|
|
|
|
|
|
|
Lab Manual BIIT Series

|
|
|
|
|
|
|
|
|
|
|
|
|
AJ/Lab Manual -45- Object Oriented Programming

|
|
|

Lab Manual BIIT Series


AJ/Lab Manual -46- Object Oriented Programming

|
|
|
|
|
|
|
|
|
|
|
Lab Manual BIIT Series

|
|
|
|
|
|
|
|
|
|
|
|
|
AJ/Lab Manual -47- Object Oriented Programming

|
|
|
|
|
|
|
|

Theory: Static data members

Lab Manual BIIT Series

We can define class members static using static keyword. When we


declare a member of a class as static it means no matter how many
objects of the class are created, there is only one copy of the static
member.A static member is shared by all objects of the class. All
static data is initialized to zero when the first object is created, if no
other initialization is present. We can't put it in the class definition
but it can be initialized outside the class as done in the following
example by redeclaring the static variable, using the scope resolution
operator :: to identify which class it belongs to.

Task 7.1: Auto Generation of Student Arid No


AJ/Lab Manual -48- Object Oriented Programming

Q#1. Write a class named student to save name, age, gender, section
and city. Also write following member functions to get and display the
data.
1. input() : to get data from the user
2. display () : to print the details of student

Lab Manual BIIT Series


AJ/Lab Manual -49- Object Oriented Programming

Use the concept of static data member and constructor to set the arid
no of each student automatically, starting from 2018-arid-0001.

|
Lab Manual BIIT Series

|
AJ/Lab Manual -50- Object Oriented Programming

| Lab Manual BIIT Series

|
AJ/Lab Manual -51- Object Oriented Programming

| Lab Manual BIIT Series

|
AJ/Lab Manual -52- Object Oriented Programming

Comments/Signature (Student & Teacher):


Lab Manual BIIT Series
AJ/Lab Manual -53- Object Oriented Programming

LAB # 08
Friend Functions and Friend Classes

Q#1. Write a program to accept five different numbers by creating a


class called friendfunc1 and friendfunc2 by taking 2 and 3 arguments
respectively and calculate the average of these numbers by passing
object of the class to friend function.

| Write code here.

|
Lab Manual BIIT Series

|
AJ/Lab Manual -54- Object Oriented Programming

Lab Manual BIIT Series


AJ/Lab Manual -55- Object Oriented Programming

|
Lab Manual BIIT Series

|
AJ/Lab Manual -56- Object Oriented Programming

|
Lab Manual BIIT Series

Q#2. Write a program to accept the student detail such as name and 3
different marks by get_data() method and display the name and
average of marks using display() method. Define a friend class for
calculating the average of marks using the method marrk_avg().

| Write code here.

|
AJ/Lab Manual -57- Object Oriented Programming

|
Lab Manual BIIT Series

|
AJ/Lab Manual -58- Object Oriented Programming

|
Lab Manual BIIT Series

|
AJ/Lab Manual -59- Object Oriented Programming

Lab Manual BIIT Series

Comments/Signature (Student & Teacher):


AJ/Lab Manual -60- Object Oriented Programming

LAB # 9
Theory: Inheritance

Inheritance is one of the key features of Object-oriented


programming in java. It allows user to create a new class (derived
Lab Manual BIIT Series

class) from an existing class(base class).

The derived class inherits all the features from the base class and can
have additional features of its own.

Exercise

Q.1 Write a class called Person that has the attributes name, address,
date of birth and cell phone number. This class should also include
the following methods:
1. A constructor to initialize all the members a default values
2. input () to get data for attributes
3. display () function to print attributes in the following format:
Name: the name of the person
Address: the address of the person
AJ/Lab Manual -61- Object Oriented Programming

Date of Birth: in the format mm/dd/yyyy


Cell Phone Number: the cell phone number of the person

Lab Manual BIIT Series


AJ/Lab Manual -62- Object Oriented Programming

Now, write a class called Employee that inherits from the Person
class. This class should have the additional attributes Department
and DateHired. Be sure to include input() and display() methods.

Write two more classes, Commission and Hourly, that both inherit
from Employee.

The Commission class has two attributes, baseSalary and


commissionRate. Be sure to include appropriate methods. Also
include a method to calculate the total salary. Total salary is the base
salary plus the commission earned (commissionRate times an input
total sales amount).

The Hourly class should have 2 attributes, rateOfPay and


Lab Manual BIIT Series

hoursWorked. Be sure to include appropriate methods. Also include a


method to calculate total salary.

Now write a main () program that gets employee data from user, like
Name, Address, Date of Birth, Cell Phone Number, Department Date
Hired, Base Salary (if commission) or Rate of Pay (if hourly)
Commission Rate (if commission) or hoursWorked (if hourly). The
program should print a report with the following information:

Name, Address, Date of Birth, Cell Phone Number, Department Date


Hired, Pay for this pay period. Be sure to use input() methods in each
class so that you can print the object and get the correct output
format.

| Write code here.


AJ/Lab Manual -63- Object Oriented Programming

| Lab Manual BIIT Series

|
AJ/Lab Manual -64- Object Oriented Programming

| Lab Manual BIIT Series

|
AJ/Lab Manual -65- Object Oriented Programming

| Lab Manual BIIT Series

|
AJ/Lab Manual -66- Object Oriented Programming

| Lab Manual BIIT Series

|
AJ/Lab Manual -67- Object Oriented Programming

| Lab Manual BIIT Series


AJ/Lab Manual -68- Object Oriented Programming

Comments/Signature (Student & Teacher):

Lab Manual BIIT Series


AJ/Lab Manual -69- Object Oriented Programming

LAB # 10
Inheritance (cont..)
Exercise

Lab Manual BIIT Series


AJ/Lab Manual -70- Object Oriented Programming

Q.1 Create an application that contains a base class that accepts


registration number and name of students. Write a program that will
accept registration number, name, and Branch as input. Implement
two branch called CSE and ECE using Inheritance. If the student
enters CSE, then get the marks of computer Network, Data Structure
and Testing. If the student enters ECE, get the marks for Electronic
Circuits, Circuit Analysis and Analog Communication. Then calculate
the average of the three subjects. The output should display the
registration number, name, and the details of subject wise marks and
the average marks. Hint: Student is the base class; Science Student
and Commerce Student are inherited from it

| Lab Manual BIIT Series

|
AJ/Lab Manual -71- Object Oriented Programming

| Lab Manual BIIT Series

|
AJ/Lab Manual -72- Object Oriented Programming

Q.2Create an application that has a base class called figure which


contains x, y, and name as member variable. x and y are double data
type. Then create four derived classes named rectangle, triangle,
square and cube which inherit from base class figure. Then create a
method named area in base class figure which should be overridden
in all derived class to calculate the area for each derived classes. Use
constructors for all classes to initialize data members. Data should be
taken from user as input.

| Lab Manual BIIT Series

|
AJ/Lab Manual -73- Object Oriented Programming

| Lab Manual BIIT Series

Q.3 Create an application that contains an Interface named


“IShape”which contains method called area. Create two classes cube
and circle that implements theinterface. Calculate the area of cube
and circle and print.

|
AJ/Lab Manual -74- Object Oriented Programming

|
Lab Manual BIIT Series

Comments/Signature (Student & Teacher):


AJ/Lab Manual -75- Object Oriented Programming

LAB # 11

Inheritance and Method Overriding


Exercise

Q.1 Implement given class Diagram.

Lab Manual BIIT Series

| Write code here

|
AJ/Lab Manual -76- Object Oriented Programming

|
Lab Manual BIIT Series

|
AJ/Lab Manual -77- Object Oriented Programming

|
Lab Manual BIIT Series

|
AJ/Lab Manual -78- Object Oriented Programming

|
Lab Manual BIIT Series

|
AJ/Lab Manual -79- Object Oriented Programming

Lab Manual BIIT Series


AJ/Lab Manual -80- Object Oriented Programming

Q.2 Implement given class Diagram.

Lab Manual BIIT Series

| Write code here

|
AJ/Lab Manual -81- Object Oriented Programming

|
Lab Manual BIIT Series

|
AJ/Lab Manual -82- Object Oriented Programming

|
Lab Manual BIIT Series

|
AJ/Lab Manual -83- Object Oriented Programming

|
Lab Manual BIIT Series

|
AJ/Lab Manual -84- Object Oriented Programming

|
Lab Manual BIIT Series

Comments/Signature (Student & Teacher):


AJ/Lab Manual -85- Object Oriented Programming

LAB # 12
Theory: File Handling

File Handling concept in JAVA language is used for store a data


permanently in computer. Using file handling we can store our data
in Secondary memory (Hard disk).

Sometime, it is important to store the information entered by the


user into the file for further use. After storing the information into
the file, later you can retrieve that information from that file. File
helps in storing the information permanently.
Lab Manual BIIT Series

Task 12.1: Files Input Output

Q.1 Write a program to input 5 cities from user and store them in a
file cities.txt.

Example Execution

Enter the name of city: Islamabad


Enter the name of city: Rawalpindi
Enter the name of city: Lahore
Enter the name of city: Karachi
Enter the name of city: Multan
AJ/Lab Manual -86- Object Oriented Programming

Successfully saved in file…………

|write code here……..


|
|
|
|
|
|

Lab Manual BIIT Series


AJ/Lab Manual -87- Object Oriented Programming

|
|
|
|
|
|
|
|
|
|
|
Lab Manual BIIT Series

|
|

|
|
|
|
|
|
|
|
|
|
AJ/Lab Manual -88- Object Oriented Programming

|
|
|
|
|
|
|
|

|
|
Lab Manual BIIT Series

|
|
|
|
|
|
|
|
|
|
|
|
|
AJ/Lab Manual -89- Object Oriented Programming

|
|
|

Q.2 Write a program that display all records from filecities.txt


prepared in the previous example.

Example Output

1- Islamabad
2- Rawalpindi Lab Manual BIIT Series

3- Lahore
4- Karachi
5- Multan
AJ/Lab Manual -90- Object Oriented Programming

|write code here……..

| Lab Manual BIIT Series

|
AJ/Lab Manual -91- Object Oriented Programming

| Lab Manual BIIT Series

|
AJ/Lab Manual -92- Object Oriented Programming

Task 12.2: Reading Lines from Files

Q.3 Write a program that inputs the addresses of five students from
user and save them in a file students.txt. After writing the data, the
program should read the data from file as a whole line. Finally the
program should print all addresses.

Example output: Lab Manual BIIT Series

Enter your Address: H # 9, Jinah Street, Rawalpindi

Enter your Address: H # 19, Khan Street, Karachi

Enter your Address: H # 4, Khayaban e Syed, Street # 5, Rawalpindi

Enter your Address: H # 5, Street # 10, Ghori Gardens, Islamabad

Enter your Address: H # 7, Street # 1, Sadar, Rawalpindi

Successfully Saved . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
AJ/Lab Manual -93- Object Oriented Programming

Address # 1: H # 9, Jinah Street, Rawalpindi

Address # 2: H # 19, Khan Street, Karachi

Address # 3: H # 4, Khayaban e Syed, Street # 5, Rawalpindi

Address # 4: H # 5, Street # 10, Ghori Gardens, Islamabad

Address # 5: H # 7, Street # 1, Sadar, Rawalpindi

|write code here……..

|
Lab Manual BIIT Series

|
AJ/Lab Manual -94- Object Oriented Programming

|
Lab Manual BIIT Series

|
AJ/Lab Manual -95- Object Oriented Programming

|
Lab Manual BIIT Series

Comments/Signature (Student & Teacher):


AJ/Lab Manual -96- Object Oriented Programming

LAB # 13
Theory: Character I/O

The data in the file can also be written character by character. Similarly the contents of a file can also be
read character by character. The put () function can be used to write single character in a file and the get
() function can be used to read single character from a file. The syntax is:

Obj.put(char)

Obj.get(char)

Task 13.1: Writing characters

Q.1: Write a program that inputs five characters from user and stores
Lab Manual BIIT Series

them in a file.

Sample Output:

Enter a character: a

Enter a character: e

Enter a character: i

Enter a character: o

Enter a character: u

Written…………

Task 13.2: Reading characters


AJ/Lab Manual -97- Object Oriented Programming

Q.2: Write a program that reads characters from file written in

previous example.

Sample Output:

Comments/Signature (Student & Teacher):

Lab Manual BIIT Series


AJ/Lab Manual -98- Object Oriented Programming

LAB # 14

Lab Manual BIIT Series


AJ/Lab Manual -99- Object Oriented Programming

Object Read Write

Object I/O is used to store data in files. It is an efficient method to


store large amount data.

Task 14.1: Writing Objects

Q.1. Write a program that inputs 5 integers and stores it in a file.

write code here……..


| Lab Manual BIIT Series

|
|
|
|
|
|
|
|
|
|
|
|
AJ/Lab Manual -100- Object Oriented Programming

|
|
|
|
|
|

|
|
|
|
Lab Manual BIIT Series

|
|
|
|
|
|
|
|
|
|
|
|
|
AJ/Lab Manual -101- Object Oriented Programming

|
|
|
|
|
|
|
|
|
|
|
Lab Manual BIIT Series

|
|
|
|
|
|
|
|
|

Q.2.Write a program to input records of three students and store it in students.txt file. Each record
contains Roll number, name and marks.
AJ/Lab Manual -102- Object Oriented Programming

Sample Execution:

Enter your Roll number: 08-arid-1819


Enter your Roll name: Asad ali khan
Enter your marks: 88

|write code here……..


|
|
|
|
Lab Manual BIIT Series

|
|
|
|
|
|
|
|
|
|
|
|
|
AJ/Lab Manual -103- Object Oriented Programming

|
|

|
|
|
|
|
|
|
|
Lab Manual BIIT Series

|
|
|
|
|
|
|
|
|
|

|
|
AJ/Lab Manual -104- Object Oriented Programming

|
|
|
|
|
|
|
|
|
|
|
Lab Manual BIIT Series

|
|
|
|
|

Q.3. Write a program that reads the record stored in students.txt file
and display them.

|write code here……..

|
AJ/Lab Manual -105- Object Oriented Programming

| Lab Manual BIIT Series

|
AJ/Lab Manual -106- Object Oriented Programming

| Lab Manual BIIT Series

|
AJ/Lab Manual -107- Object Oriented Programming

| Lab Manual BIIT Series

|
AJ/Lab Manual -108- Object Oriented Programming

Q.4. Write a program that creates a file to store name and email of
user using classes and then display the records as well.

|write code here……..

|
Lab Manual BIIT Series

|
AJ/Lab Manual -109- Object Oriented Programming

|
Lab Manual BIIT Series

|
AJ/Lab Manual -110- Object Oriented Programming

|
Lab Manual BIIT Series

Comments/Signature (Student & Teacher):


AJ/Lab Manual -111- Object Oriented Programming

LAB # 15

Object Read Write (cont..)

The object can also be written and read from a file. The objects
are normally written and read in binary mode. It helps the user to
use as much memory as is needed to store the content of the object.

The method of writing object to a disk is same as writing structures


with binary I/O. the write () method is used to write the object to a
disk.

Lab Manual BIIT Series

Task 15.1: Writing an object to Disk

Q.1. Write a program that stores an object of file country.txt using


binary I/O with name of country and code of country as attributes.

Note: Create country.txt file in this folder d:\OOP\Filing

|write code here……..

|
AJ/Lab Manual -112- Object Oriented Programming

| Lab Manual BIIT Series

|
AJ/Lab Manual -113- Object Oriented Programming

| Lab Manual BIIT Series

|
AJ/Lab Manual -114- Object Oriented Programming

| Lab Manual BIIT Series

|
AJ/Lab Manual -115- Object Oriented Programming

Task 15.2: Reading an object from Disk

Q.2. Write a program that reads10 objects froma file country.txt using
binary I/O that is written in previous example.

|write code here……..

|
Lab Manual BIIT Series

|
AJ/Lab Manual -116- Object Oriented Programming

| Lab Manual BIIT Series

|
AJ/Lab Manual -117- Object Oriented Programming

| Lab Manual BIIT Series

|
AJ/Lab Manual -118- Object Oriented Programming

Task 15.3: Accessing Records Randomly Lab Manual BIIT Series

Q.3. Write a program that maintain the records of phonebook. The


name, contact and email address of a person is stored to a binary file
name phonebook.dat. The program should display the following
manue and work accordingly.
 Press 1 to add contact
 Press 2 to View contacts
 Press 3 to delete contact
 Press 4 to search contact by name
 Press 5 to update any contact
 Press 6 to exit
AJ/Lab Manual -119- Object Oriented Programming

Note: Please note that the program should iterate repeatedly


according to user choice, like press ‘n’ to stop and ‘y’ to continue. Also
use the concept of accessing records randomly

|write code here……..

|
Lab Manual BIIT Series

|
AJ/Lab Manual -120- Object Oriented Programming

| Lab Manual BIIT Series

|
AJ/Lab Manual -121- Object Oriented Programming

| Lab Manual BIIT Series

Comments/Signature (Student & Teacher):


LAB # 16
Theory: String class

A collection of characters written in double quotation is called string


or string constant. It may consist of any alphabetic characters, digits
and special symbols. A string is stored in array of characters. The
array is terminated by special symbol known as null character. It is
denoted by escape sequence \0 and it is used to indicate the end of
string.

The class string is a dynamic class that is used to store characters.


The object of this class uses the concept of dynamic memory
Lab Manual BIIT Series

allocation. The basic class used in Java for character handling is


string.h class.

string.h class contains some basic string handling functions like:


 strcpy(source, destination)
 strcat(ch1[],ch2[])
 strcmp(ch1[],ch2[])
 strlen(ch[])
 strupr(ch[])
 strlwr(ch[])
Task 16.1: String functions

Q.1. Write a program to input a string value from user and display
length of string without using built in function.

|write code here……..

|
Lab Manual BIIT Series

|
|

Lab Manual BIIT Series

|
|

Lab Manual BIIT Series

|
|

Lab Manual BIIT Series

Q.2. write your own version of built in function strcpy().

|write code here……..

|
|

| Lab Manual BIIT Series

|
|

Q.3. write your own version of built in function strcmp ().

|write code here……..

| Lab Manual BIIT Series

|
|

| Lab Manual BIIT Series

Task 16.2: string functions

Q.4. write your own version of built in function strlen ().

|write code here……..

|
|

| Lab Manual BIIT Series

|
|

Lab Manual BIIT Series

Q.5. write your own version of built in function strcat ().

|write code here……..

|
|

| Lab Manual BIIT Series

|
|

Q.6. write your own version of built in function strupr ().

|write code here……..

| Lab Manual BIIT Series

|
|

|
Lab Manual BIIT Series

Comments/Signature (Student & Teacher):

You might also like