0% found this document useful (0 votes)
123 views18 pages

Object Oriented Programming Assessment Key

The document is an internal assessment answer key for a course on Object Oriented Programming at Loyola Institute of Technology and Science. It covers key concepts such as features of OOP, comparisons between structured and object-oriented programming, definitions of objects and inheritance types, and explanations of arrays and garbage collection in Java. Additionally, it includes examples of static members and recursion.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
123 views18 pages

Object Oriented Programming Assessment Key

The document is an internal assessment answer key for a course on Object Oriented Programming at Loyola Institute of Technology and Science. It covers key concepts such as features of OOP, comparisons between structured and object-oriented programming, definitions of objects and inheritance types, and explanations of arrays and garbage collection in Java. Additionally, it includes examples of static members and recursion.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Loyola INSTITUTE OF TECHNOLOGY AND SCIENCE, THOVALAI

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

INTERNAL ASSESSMENT – 1(Answer Key)


(Regulation 2021)
Course Code: CS3391
Course Name: Object Oriented Programming
Year/Semester: II/III

Part –A(6x2=12 Marks)

1 List the most striking features of Object Oriented Programming?

There are three major features in object-oriented programming that makes them different
than non-OOP languages: encapsulation, inheritance and polymorphism.

2 Compare Object Oriented and Structured languages.

Structured Programming Object-Oriented Programming

It is a subset of procedural It relies on concept of objects that contain data and


programming. code.

Programs are divided into small


programs or functions. Programs are divided into objects or entities.

It is all about facilitating creation of


programs with readable code and It is all about creating objects that usually contain
reusable components. both functions and data.

Its main aim is to improve and


increase quality, clarity, and
development time of computer Its main aim is to improve and increase both quality
program. and productivity of system analysis and design.

It simply focuses on representing both structure and


behavior of information system into tiny or small
It simply focuses on functions and modules that generally combines data and process
processes that usually work on data. both.

In this, methods are written globally In this, method works dynamically, make calls as per
and code lines are processed one by
one i.e., Run sequentially. need of code for certain time.

It generally follows “Top-Down


Approach”. It generally follows “Bottom-Up Approach”.

It provides less flexibility and


abstraction as compared to object- It provides more flexibility and abstraction as
oriented programming. compared to structured programming.

It is more difficult to modify structured


program and reuse code as compared It is less difficult to modify object-oriented programs
to object-oriented programs. and reuse code as compared to structured programs.

It gives more importance of code. It gives more importance to data.

3 Define objects in object oriented programming

An object is a software "bundle" consisting of a set of variables which define the states
the object can exist in and a set of functions that define the behavior of that object. Software
objects are often used to model the real-world objects that you find in everyday life.

4 Write a program to print the elements in an array using enhanced for loop.
int[] highScores = { 10, 9, 8, 8};
String[] names = {"Jamal", "Emily", "Destiny", "Mateo"};
// for each loop: for each value in highScores
// for (type variable : arrayname)
for (int value : highScores)
{
// Notice no index or [ ], just the variable value!
[Link]( value );
}
// for each loop with a String array to print each name
// the type for variable name is String!
for (String name : names)
{
[Link](name);
}
5 List the types of inheritance.

 Single Inheritance
 Multiple Inheritance
 Multilevel Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance

6 Illustrate an abstract class?


An abstract class in Java is one that is declared with the abstract keyword. It may have
both abstract and non-abstract methods(methods with bodies). An abstract is a java
modifier applicable for classes and methods in java but not for Variables.
Illustration: Abstract class
abstract class Shape
{
int color;
// An abstract function
abstract void draw();
}

Part –B(3x16=48 Marks)

7a. Explain One Dimensional and Multidimensional Arrays.

An array is a collection of similar data types (like int, float, or char), which takes memory in a
contiguous fashion in Primary memory locations.
We can declare an array in C as
int arr[50];
Where arr is an array with can hold 50 elements of integer types.

Two Type of array:

1). Single/One Dimensional array


2). Multi-Dimensional Array
One Dimensional Array

Declaration of one dimensional array:

An array can be declared with the bracket punctuators [ ], as shown in the below syntax:
Data_Type Array_Name[Number_Of_Elements]
The below example shows a declaration of an array having the capacity to hold 50 elements of
type integers and the name of that array is arr :
int arr[50];
Initializing the array:

We can initialize an array in C by assigning value to each index one by one or by using a single
statement as follows −
Example 1 :
Assign one value each time to the array
int arr[50];
arr[0]=12;
arr[1]= 43;
arr[2] = 14;
.
.
arr[49] = 54;
Example 2:
Using a single statement
int arr[5] = {10,32,11,45,38};
Program in C to implement One dimensional array:

#include <stdio.h>

int main () {

int n[50]; /* n is an array of 50 integers */

int i,j;

/* initialize elements of array n to 0 */

for ( i = 0; i < 50; i++ ) {

n[ i ] = i + 50; /* set element at location i to i + 50 */

/* output each array element's value */

for (j = 0; j < 50; j++ ) {

printf("Element[%d] = %d\n", j, n[j] );


}

return 0;

Multidimensional Arrays

We can say a Multidimensional array is an array of arrays. Two Dimensional arrays is also a
multidimensional array. In a Multi-Dimensional array, elements of an array are arranged in the
form of rows and columns.
Multidimensional array stores elements in tabular form which is also known as in row-major
order or column-major order.
Declaration of Multi-dimensional Array

data_type array_name[size1][size2]….[sizeN];
data_type: It defines the type of data that can be held by an array. Here data_type can be int,
char, float. etc.
array_name: Name of the array
size1, size2,… ,sizeN: Sizes of the dimensions
Pictorial representation of a multidimensional array

number_of_arrays: number of arrays which flow in the z-axis


rows: number of the rows in the y-axis
columns: number of the columns flow in the x-axis

(OR)

7b. Explain about Garbage Collection.

Garbage collection in Java is the process by which Java programs perform automatic
memory management. Java programs compile to bytecode that can be run on a Java Virtual
Machine, or JVM for short. When Java programs run on the JVM, objects are created on the
heap, which is a portion of memory dedicated to the program. Eventually, some objects will no
longer be needed. The garbage collector finds these unused objects and deletes them to free up
memory.
In C/C++, a programmer is responsible for both the creation and destruction of objects.
Usually, programmer neglects the destruction of useless objects. Due to this negligence, at a
certain point, sufficient memory may not be available to create new objects, and the entire
program will terminate abnormally, causing OutOfMemoryErrors.

But in Java, the programmer need not care for all those objects which are no longer in use.
Garbage collector destroys these objects. The main objective of Garbage Collector is to free
heap memory by destroying unreachable objects. The garbage collector is the best example of
the Daemon thread as it is always running in the background.

How Does Garbage Collection in Java works?


Java garbage collection is an automatic process. Automatic garbage collection is the process of
looking at heap memory, identifying which objects are in use and which are not, and deleting
the unused objects. An in-use object, or a referenced object, means that some part of your
program still maintains a pointer to that object. An unused or unreferenced object is no longer
referenced by any part of your program. So the memory used by an unreferenced object can be
reclaimed. The programmer does not need to mark objects to be deleted explicitly. The garbage
collection implementation lives in the JVM.

Types of Activities in Java Garbage Collection

Two types of garbage collection activity usually happen in Java. These are:
1. Minor or incremental Garbage Collection: It is said to have occurred when
unreachable objects in the young generation heap memory are removed.
2. Major or Full Garbage Collection: It is said to have occurred when the objects that
survived the minor garbage collection are copied into the old generation or permanent
generation heap memory are removed. When compared to the young generation, garbage
collection happens less frequently in the old generation.

Important Concepts Related to Garbage Collection in Java

1. Unreachable objects: An object is said to be unreachable if it doesn’t contain any reference


to it. Also, note that objects which are part of the island of isolation are also unreachable.
Integer i = new Integer(4);
// the new Integer object is reachable via the reference in 'i'
i = null;
// the Integer object is no longer reachable.
2. Eligibility for garbage collection: An object is said to be eligible for GC(garbage
collection) if it is unreachable. After i = null, integer object 4 in the heap area is suitable for
garbage collection in the above image.
Ways to make an object eligible for Garbage Collector
 Even though the programmer is not responsible for destroying useless objects but it is
highly recommended to make an object unreachable(thus eligible for GC) if it is no longer
required.
 There are generally four ways to make an object eligible for garbage collection.
1. Nullifying the reference variable
2. Re-assigning the reference variable
3. An object created inside the method
4. Island of Isolation
Ways for requesting JVM to run Garbage Collector
 Once we make an object eligible for garbage collection, it may not destroy immediately
by the garbage collector. Whenever JVM runs the Garbage Collector program, then only
the object will be destroyed. But when JVM runs Garbage Collector, we can not expect.
 We can also request JVM to run Garbage Collector. There are two ways to do it :
1. Using [Link]() method: System class contain static method gc() for
requesting JVM to run Garbage Collector.
2. Using [Link]().gc() method: Runtime class allows the
application to interface with the JVM in which the application is running. Hence by
using its gc() method, we can request JVM to run Garbage Collector.
3. There is no guarantee that any of the above two methods will run Garbage
Collector.
4. The call [Link]() is effectively equivalent to the
call : [Link]().gc()
Finalization
 Just before destroying an object, Garbage Collector calls finalize() method on the object
to perform cleanup activities. Once finalize() method completes, Garbage Collector
destroys that object.
 finalize() method is present in Object class with the following prototype.
protected void finalize() throws Throwable
Based on our requirement, we can override finalize() method for performing our cleanup
activities like closing connection from the database.
1. The finalize() method is called by Garbage Collector, not JVM. However, Garbage
Collector is one of the modules of JVM.
2. Object class finalize() method has an empty implementation. Thus, it is recommended
to override the finalize() method to dispose of system resources or perform other cleanups.
3. The finalize() method is never invoked more than once for any object.
4. If an uncaught exception is thrown by the finalize() method, the exception is ignored,
and the finalization of that object terminates.
Advantages of Garbage Collection in Java
The advantages of Garbage Collection in Java are:
 It makes java memory-efficient because the garbage collector removes the unreferenced
objects from heap memory.
 It is automatically done by the garbage collector(a part of JVM), so we don’t need extra
effort.
Real-World Example
Let’s take a real-life example, where we use the concept of the garbage collector.

8.a Explain the Static Members


In Java, static members are those which belongs to the class and you can access these members
without instantiating the class.
The static keyword can be used with methods, fields, classes (inner/nested), blocks.
Static Methods − You can create a static method by using the keyword static. Static methods
can access only static fields, methods. To access static methods there is no need to instantiate
the class, you can do it just using the class name as −

Example

public class MyClass {


public static void sample(){
[Link]("Hello");
}
public static void main(String args[]){
[Link]();
}
}
Output : Hello

Static Fields − You can create a static field by using the keyword static. The static fields have
the same value in all the instances of the class. These are created and initialized when the class
is loaded for the first time. Just like static methods you can access static fields using the class
name (without instantiation).

Example

public class MyClass {


public static int data = 20;
public static void main(String args[]){
[Link]([Link]);
}
Java Arrays with Answers
27
}

Output : 20

Static Blocks − These are a block of codes with a static keyword. In general, these are used to
initialize the static members. JVM executes static blocks before the main method at the time of
class loading.

Example

public class MyClass {


static{
[Link]("Hello this is a static block");
}
public static void main(String args[]){
[Link]("This is main method");
}
}

Output

Hello this is a static block


This is main method
(OR)

8.b Demonstrate

i. A Simple Class

A Simple Class Definition

class Count {
public static void main(String args[])
throws [Link]
{
int count = 0;

while ([Link]() != -1)


count++;
[Link]("Input has " + count + " chars.");
}
}
In the Java language, all methods and variables must exist within a class. So, the first line
of the character-counting application defines a class, Count, that defines the methods,
variables, and any other classes needed to implement the character-counting application.
Since this program is such a simple one, the Count class just defines one method
named main().

ii. Declaring Objects

Creating Objects

As you know, a class provides the blueprint for objects; you create an object from a class.
Each of the following statements taken from the CreateObjectDemo program creates an
object and assigns it to a variable:

Point originOne = new Point(23, 94);


Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);

The first line creates an object of the Point class, and the second and third lines each
create an object of the Rectangle class.

Each of these statements has three parts (discussed in detail below):


1. Declaration: The code set in bold are all variable declarations that associate a
variable name with an object type.
2. Instantiation: The new keyword is a Java operator that creates the object.
3. Initialization: The new operator is followed by a call to a constructor, which
initializes the new object.

Declaring a Variable to Refer to an Object

Previously, you learned that to declare a variable, you write:

type name;

This notifies the compiler that you will use name to refer to data whose type is type. With
a primitive variable, this declaration also reserves the proper amount of memory for the
variable.

we can also declare a reference variable on its own line. For example:

Point originOne;

If you declare originOne like this, its value will be undetermined until an object is
actually created and assigned to it. Simply declaring a reference variable does not create
an object. For that, you need to use the new operator, as described in the next section.
You must assign an object to originOne before you use it in your code. Otherwise, you
will get a compiler error.

A variable in this state, which currently references no object, can be illustrated as follows
(the variable name, originOne, plus a reference pointing to nothing):

9.a Describe about Recursion

Recursion is the technique of making a function call itself. This technique provides a way
to break complicated problems down into simple problems which are easier to solve.

Recursion may be a bit difficult to understand. The best way to figure out how it works is to
experiment with it.

Recursion Example

Adding two numbers together is easy to do, but adding a range of numbers is more complicated.
In the following example, recursion is used to add a range of numbers together by breaking it
down into the simple task of adding two numbers:

Example
Use recursion to add all of the numbers up to 10.

public class Main {

public static void main(String[] args) {

int result = sum(10);

[Link](result);

public static int sum(int k) {

if (k > 0) {

return k + sum(k - 1);

} else {

return 0;

Example Explained

When the sum() function is called, it adds parameter k to the sum of all numbers smaller
than k and returns the result. When k becomes 0, the function just returns 0. When running, the
program follows these steps:

10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0

Since the function does not call itself when k is 0, the program stops there and returns the result.

Halting Condition

Just as loops can run into the problem of infinite looping, recursive functions can run into the
problem of infinite recursion. Infinite recursion is when the function never stops calling itself.
Every recursive function should have a halting condition, which is the condition where the
function stops calling itself. In the previous example, the halting condition is when the
parameter k becomes 0.

It is helpful to see a variety of different examples to better understand the concept. In this
example, the function adds a range of numbers between a start and an end. The halting condition
for this recursive function is when end is not greater than start:

Example

Use recursion to add all of the numbers between 5 to 10.

public class Main {

public static void main(String[] args) {

int result = sum(5, 10);

[Link](result);

public static int sum(int start, int end) {

if (end > start) {

return end + sum(start, end - 1);

} else {

return end;

(OR)

9.b Explain about Inheritance

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java

o For Method Overriding (so runtime polymorphism can be achieved).


o For Code Reusability.

Terms used in Inheritance

o Class: A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called
a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You can
use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance

1. class Subclass-name extends Superclass-name


2. {
3. //methods and fields
4. }

The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new
class is called child or subclass.
Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
The relationship between the two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee.

1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. [Link]("Programmer salary is:"+[Link]);
9. [Link]("Bonus of Programmer is:"+[Link]);
10. }
11. }
Programmer salary is:40000.0
Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.

File: [Link]

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}}

Output:

barking...
eating...

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal
class, so there is a multilevel inheritance.

File: [Link]

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class BabyDog extends Dog{
void weep(){[Link]("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}}
Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.

File: [Link]

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class Cat extends Animal{
void meow(){[Link]("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}}

Output:

meowing...
eating...

You might also like