OOPJ GTU SUMMER 2023
Q.1 (a) Differentiate between Procedure-Oriented Programming (POP) and Object-Oriented
Programming (OOP). (3 marks)
**Answer:**
| Feature | POP | OOP |
|-------------------------------|-------------------------------------------------|--------------------------------------
---|
| **Approach** | Follows a top-down approach | Follows a bottom-up
approach |
| **Data Handling** | Data is exposed to the whole program | Data is encapsulated
within objects |
| **Focus** | Focuses on functions | Focuses on data and objects |
| **Modularity** | Less modular, harder to manage large programs | Highly modular,
easier to manage |
| **Examples** | C, Pascal | Java, C++, Python |
### Q.1 (b) Explain the Super keyword in inheritance with a suitable example. (4 marks)
**Answer:**
The `super` keyword in Java is used to refer to the immediate parent class object. It can be
used to access parent class variables, methods, and constructors.
*Example:*
```java
class Animal {
void eat() {
System.out.println("Animal is eating");
1|Pa ge DHYAN PATEL
OOPJ GTU SUMMER 2023
class Dog extends Animal {
void eat() {
System.out.println("Dog is eating");
void display() {
super.eat(); // calls the parent class method
public class TestSuper {
public static void main(String[] args) {
Dog dog = new Dog();
dog.display(); // Output: Animal is eating
```
### Q.1 (c) Define: Method Overriding. List out Rules for method overriding. Write a Java
program that implements method overriding. (7 marks)
**Answer:**
**Definition:**
Method Overriding occurs when a subclass provides a specific implementation for a method
that is already defined in its superclass.
**Rules for Method Overriding:**
1. The method in the child class must have the same name, return type, and parameter list as
the method in the parent class.
2. The overriding method cannot have a more restrictive access modifier than the overridden
method (e.g., if the parent method is public, the child method cannot be protected).
2|Pa ge DHYAN PATEL
OOPJ GTU SUMMER 2023
3. The overriding method can throw narrower or fewer checked exceptions than the overridden
method.
*Example:*
```java
class Animal {
void sound() {
System.out.println("Animal makes a sound");
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
public class TestOverriding {
public static void main(String[] args) {
Animal animal = new Animal();
Animal dog = new Dog();
animal.sound(); // Output: Animal makes a sound
dog.sound(); // Output: Dog barks
```
### Q.2 (a) Explain the Java Program Structure with example. (3 marks)
3|Pa ge DHYAN PATEL
OOPJ GTU SUMMER 2023
**Answer:**
A typical Java program structure includes:
1. **Package Declaration** (optional)
2. **Import Statements** (optional)
3. **Class Definition**
4. **Main Method**
*Example:*
```java
// Package declaration (optional)
package mypackage;
// Import statements (optional)
import java.util.Scanner;
// Class definition
public class HelloWorld {
// Main method
public static void main(String[] args) {
System.out.println("Hello, World!");
```
### Q.2 (b) Explain the static keyword with a suitable example. (4 marks)
**Answer:**
4|Pa ge DHYAN PATEL
OOPJ GTU SUMMER 2023
The `static` keyword in Java is used for memory management primarily. It can be applied to
variables, methods, blocks, and nested classes.
*Example:*
```java
class StaticExample {
// Static variable
static int count = 0;
// Static method
static void displayCount() {
System.out.println("Count: " + count);
// Constructor
StaticExample() {
count++;
public static void main(String[] args) {
StaticExample obj1 = new StaticExample();
StaticExample obj2 = new StaticExample();
StaticExample.displayCount(); // Output: Count: 2
```
### Q.2 (c) Define: Constructor. List out types of it. Explain Parameterized and copy constructor
with a suitable example. (7 marks)
**Answer:**
5|Pa ge DHYAN PATEL
OOPJ GTU SUMMER 2023
**Definition:**
A constructor in Java is a block of code that initializes a newly created object. It has the same
name as the class and no return type.
**Types of Constructors:**
1. **Default Constructor**
2. **Parameterized Constructor**
3. **Copy Constructor**
**Parameterized Constructor Example:**
```java
class Student {
int id;
String name;
// Parameterized constructor
Student(int i, String n) {
id = i;
name = n;
void display() {
System.out.println(id + " " + name);
public static void main(String[] args) {
Student s1 = new Student(101, "Alice");
Student s2 = new Student(102, "Bob");
s1.display(); // Output: 101 Alice
6|Pa ge DHYAN PATEL
OOPJ GTU SUMMER 2023
s2.display(); // Output: 102 Bob
```
**Copy Constructor Example:**
```java
class Student {
int id;
String name;
// Parameterized constructor
Student(int i, String n) {
id = i;
name = n;
// Copy constructor
Student(Student s) {
id = s.id;
name = s.name;
void display() {
System.out.println(id + " " + name);
public static void main(String[] args) {
Student s1 = new Student(101, "Alice");
Student s2 = new Student(s1);
7|Pa ge DHYAN PATEL
OOPJ GTU SUMMER 2023
s1.display(); // Output: 101 Alice
s2.display(); // Output: 101 Alice
```
### Q.3 (a) Explain Type Conversion and Casting in Java. (3 marks)
**Answer:**
**Type Conversion:** It is the process of converting one data type into another. Java supports
two types of type conversion:
1. **Implicit Type Conversion (Widening Conversion):** Automatically done by the compiler.
E.g., converting `int` to `float`.
2. **Explicit Type Conversion (Narrowing Conversion):** Manually done by the programmer.
E.g., converting `float` to `int`.
**Type Casting Example:**
```java
public class TypeCasting {
public static void main(String[] args) {
// Implicit Type Conversion
int i = 100;
long l = i;
float f = l;
System.out.println("Implicit Type Conversion: " + f); // Output: 100.0
// Explicit Type Conversion
double d = 100.04;
long l2 = (long) d;
int i2 = (int) l2;
8|Pa ge DHYAN PATEL
OOPJ GTU SUMMER 2023
System.out.println("Explicit Type Conversion: " + i2); // Output: 100
```
### Q.3 (b) Explain different visibility controls used in Java. (4 marks)
**Answer:**
**Visibility Controls in Java:**
1. **Private:** Accessible only within the declared class.
2. **Default (Package-private):** Accessible within the same package.
3. **Protected:** Accessible within the same package and subclasses.
4. **Public:** Accessible from any other class.
*Example:*
```java
class Visibility {
private int privateVar = 10;
int defaultVar = 20; // Default access
protected int protectedVar = 30;
public int publicVar = 40;
public void display() {
System.out.println("Private: " + privateVar);
System.out.println("Default: " + defaultVar);
System.out.println("Protected: " + protectedVar);
System.out.println("Public: " + publicVar);
9|Pa ge DHYAN PATEL
OOPJ GTU SUMMER 2023
public class TestVisibility {
public static void main(String[] args) {
Visibility obj = new Visibility();
obj.display();
// System.out.println(obj.privateVar); // Error: privateVar has private access in Visibility
System.out.println("Default: " + obj.defaultVar);
System.out.println("Protected: " + obj.protectedVar);
System.out.println("Public: " + obj.publicVar);
```
### Q.3 (c) Define: Thread. List different methods used to create Thread. Explain Thread life
cycle in detail. (7 marks)
**Answer:**
**Definition:**
A thread in Java is a lightweight process that enables multitasking within a program. Threads
share the process's resources but execute independently.
**Methods to Create Threads:**
1. Extending the `Thread` class.
2. Implementing the `Runnable` interface.
**Thread Life Cycle:**
1. **New:** The thread is created but not yet started.
2. **Runnable:** The thread is ready to run and waiting for CPU time.
3. **Running:** The thread is currently executing.
4. **Blocked/Waiting:** The thread is not eligible to run, waiting for a resource or another thread
to perform a specific action.
10 | P a g e DHYAN PATEL
OOPJ GTU SUMMER 2023
5. **Terminated:** The thread has completed execution.
*Example of Creating Thread by Extending Thread Class:*
```java
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
public static void main(String[] args) {
MyThread t1 = new MyThread();
1.start();
```
*Example of Creating Thread by Implementing Runnable Interface:*
```java
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running");
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
t1.start();
11 | P a g e DHYAN PATEL
OOPJ GTU SUMMER 2023
```
**Thread Life Cycle Example:**
```java
class MyThread extends Thread {
public void run() {
System.out.println("Thread started");
try {
Thread.sleep(1000); // Thread is now in Waiting state
} catch (InterruptedException e) {
System.out.println(e);
System.out.println("Thread ended");
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // Thread moves to Runnable state
```
### Q.4 (a) Differentiate between String class and StringBuffer class. (3 marks)
**Answer:**
| Feature | String | StringBuffer |
|------------------------|-------------------------------------|-------------------------------------|
| **Mutability** | Immutable (cannot be changed) | Mutable (can be changed) |
12 | P a g e DHYAN PATEL
OOPJ GTU SUMMER 2023
| **Thread Safety** | Not thread-safe | Thread-safe |
| **Performance** | Slower for concatenation operations | Faster for concatenation
operations |
| **Usage** | Used for fixed-length data | Used for variable-length data |
### Q.4 (b) Write a Java Program to find the sum and average of 10 numbers of an array. (4
marks)
**Answer:**
```java
public class SumAndAverage {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int sum = 0;
for (int number : numbers) {
sum += number;
double average = sum / 10.0;
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
```
Q-4(C) I) Explain abstract class with suitable example.
II) Explain final class with suitable example.
### I) Explain abstract class with a suitable example.
**Abstract Class:**
13 | P a g e DHYAN PATEL
OOPJ GTU SUMMER 2023
An abstract class in Java is a class that cannot be instantiated on its own and is meant to be
subclassed. It can contain both abstract methods (without a body) and concrete methods (with
a body). Abstract methods must be implemented by the subclasses.
**Characteristics of Abstract Class:**
1. Cannot be instantiated directly.
2. Can have abstract methods, which are methods declared without an implementation.
3. Can have concrete methods with an implementation.
4. Subclasses must override abstract methods or be declared abstract themselves.
**Example:**
```java
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
abstract void sound();
// Regular method
void sleep() {
System.out.println("This animal is sleeping.");
// Subclass (inherits from Animal)
class Dog extends Animal {
// Providing implementation of the abstract method
void sound() {
System.out.println("Dog barks");
14 | P a g e DHYAN PATEL
OOPJ GTU SUMMER 2023
public class TestAbstractClass {
public static void main(String[] args) {
// Animal animal = new Animal(); // This will give an error because Animal is abstract
Dog dog = new Dog();
dog.sound(); // Output: Dog barks
dog.sleep(); // Output: This animal is sleeping.
```
In this example, `Animal` is an abstract class with an abstract method `sound()` and a
concrete method `sleep()`. The `Dog` class extends `Animal` and provides an
implementation for the `sound()` method. The `main` method creates an instance of `Dog`
and calls its methods.
### II) Explain final class with a suitable example.
**Final Class:**
A final class in Java is a class that cannot be subclassed. This means no other class can extend
a final class. This is useful when you want to prevent inheritance for security reasons or to
ensure the class's implementation remains unchanged.
**Characteristics of Final Class:**
1. Cannot be extended by any other class.
2. All methods in a final class are implicitly final.
**Example:**
```java
// Final class
15 | P a g e DHYAN PATEL
OOPJ GTU SUMMER 2023
final class Vehicle {
// Method in a final class
void display() {
System.out.println("This is a vehicle.");
// The following class declaration will give an error
// class Car extends Vehicle {
// // Compilation Error: The type Car cannot subclass the final class Vehicle
// }
public class TestFinalClass {
public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
vehicle.display(); // Output: This is a vehicle.
```
### Q.5 (a) Write a program in Java to create a file and perform write operation on this file. (3
marks)
**Answer:**
```java
import java.io.FileWriter;
import java.io.IOException;
public class FileWriteExample {
public static void main(String[] args) {
16 | P a g e DHYAN PATEL
OOPJ GTU SUMMER 2023
try {
FileWriter writer = new FileWriter("example.txt");
writer.write("Hello, this is a sample text file.");
writer.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
```
### Q.5 (b) Explain throw and finally in Exception Handling with an example. (4 marks)
**Answer:**
**throw:** The `throw` keyword is used to explicitly throw an exception from a method or any
block of code.
**finally:** The `finally` block is used to execute important code such as closing resources,
and it will always execute regardless of whether an exception is thrown or not.
*Example:*
```java
public class ExceptionHandlingExample {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
} else {
System.out.println("Access granted - You are old enough!");
17 | P a g e DHYAN PATEL
OOPJ GTU SUMMER 2023
public static void main(String[] args) {
try {
checkAge(15);
} catch (ArithmeticException e) {
System.out.println("Caught Exception: " + e.getMessage());
} finally {
System.out.println("Finally block is always executed.");
```
### Q.5 (c) Describe Polymorphism. Explain run-time polymorphism with a suitable example in
Java. (7 marks)
**Answer:**
**Polymorphism:**
Polymorphism in Java allows methods to perform different tasks based on the object that it is
acting upon. It can be achieved by method overloading (compile-time polymorphism) and
method overriding (run-time polymorphism).
**Run-time Polymorphism:**
Run-time polymorphism is achieved through method overriding. It allows a subclass to provide
a specific implementation of a method that is already defined in its superclass.
*Example:*
```java
18 | P a g e DHYAN PATEL
OOPJ GTU SUMMER 2023
class Animal {
void sound() {
System.out.println("Animal makes a sound");
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
class Cat extends Animal {
@Override
void sound() {
System.out.println("Cat meows");
public class TestPolymorphism {
public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog();
Animal myCat = new Cat();
myAnimal.sound(); // Output: Animal makes a sound
myDog.sound(); // Output: Dog barks
myCat.sound(); // Output: Cat meows
19 | P a g e DHYAN PATEL
OOPJ GTU SUMMER 2023
```
20 | P a g e DHYAN PATEL