Object Oriented Programming with JAVA (4341602) - Summer 2025 Solution

Solution guide for Object Oriented Programming with JAVA (4341602) Summer 2025 exam

Question 1(a) [3 marks]

Differentiate between Procedure Oriented Programming (POP) and object-oriented programming (OOP).

Answer:

Table:

AspectPOPOOP
ApproachTop-down approachBottom-up approach
FocusFunctions and proceduresObjects and classes
Data SecurityLess secure, global dataMore secure, data encapsulation
Problem SolvingDivides into functionsDivides into objects

Key Points:

  • POP: Functions are primary building blocks
  • OOP: Objects contain both data and methods
  • Reusability: OOP provides better code reusability

Mnemonic: "POP Functions, OOP Objects"

Question 1(b) [4 marks]

Enlist and explain the basic concepts of OOP.

Answer:

Basic OOP Concepts:

  • Encapsulation: Binding data and methods together in a class
  • Inheritance: Creating new classes from existing classes
  • Polymorphism: Same method name with different implementations
  • Abstraction: Hiding implementation details from user

Benefits:

  • Code Reusability: Through inheritance and polymorphism
  • Data Security: Through encapsulation
  • Easy Maintenance: Modular approach

Mnemonic: "Every Intelligent Person Abstracts"

Question 1(c) [7 marks]

Define Constructor. Enlist different types of Constructors and explain any 2 of them with a proper example.

Answer:

Constructor Definition: A constructor is a special method that initializes objects when they are created. It has the same name as the class and no return type.

Types of Constructors:

  • Default Constructor: No parameters
  • Parameterized Constructor: Takes parameters
  • Copy Constructor: Creates object from another object
  • Private Constructor: Restricts object creation

Code Example:

Java

Key Features:

  • Automatic Invocation: Called automatically during object creation
  • No Return Type: Constructors don't have return type

Mnemonic: "Constructors Create Objects"

Question 1(c OR) [7 marks]

Explain String class. Enlist different methods of String class and explain any 3 of them with a proper example.

Answer:

String Class: String class in Java represents immutable character sequences. Once created, String objects cannot be modified.

String Methods:

MethodPurpose
length()Returns string length
charAt(index)Returns character at index
substring(start, end)Extracts substring
indexOf(char)Finds character position
toUpperCase()Converts to uppercase

Code Example:

Java

Key Points:

  • Immutable: String objects cannot be changed
  • Memory Efficient: String pool for storage

Mnemonic: "Strings Store Text"

Question 2(a) [3 marks]

Define Garbage collection. Describe the importance of Garbage collection in JAVA Programming.

Answer:

Garbage Collection Definition: Automatic memory management process that reclaims memory occupied by objects that are no longer referenced.

Importance:

  • Automatic Memory Management: No manual memory deallocation needed
  • Prevents Memory Leaks: Automatically frees unused memory
  • Application Performance: Optimizes memory usage

Benefits:

  • Programmer Productivity: Focus on logic, not memory management
  • Reliability: Reduces crashes due to memory issues

Mnemonic: "Garbage Collector Cleans Memory"

Question 2(b) [4 marks]

List down the four ways to make an object eligible for garbage collection.

Answer:

Four Ways for GC Eligibility:

MethodDescription
Nullifying ReferenceSet object reference to null
Reassigning ReferencePoint reference to another object
Anonymous ObjectsCreate objects without reference
Island of IsolationObjects refer only to each other

Examples:

  • Nullifying: obj = null;
  • Reassigning: obj1 = obj2;
  • Anonymous: new Student();
  • Island: Circular references with no external access

Mnemonic: "Null References Attract Islands"

Question 2(c) [7 marks]

Write a Java Program to demonstrate a static block that gets executed before main. Explain its significance.

Answer:

Code Example:

Java

Output:

Static block executed first
Count initialized to: 10
Main method started
Count value: 10

Significance:

  • Early Initialization: Executes before main method
  • Class Loading: Runs when class is first loaded
  • One-time Execution: Executes only once per class

Uses:

  • Static Variable Initialization: Initialize static variables
  • Resource Loading: Load configuration files

Mnemonic: "Static Blocks Start Before Main"

Question 2(a OR) [3 marks]

Describe Minor/Incremental and Major/Full Garbage collection in JAVA.

Answer:

Types of Garbage Collection:

TypeDescriptionFrequency
Minor GCCleans young generationFrequent
Major GCCleans old generationLess frequent

Minor GC:

  • Target: Young generation objects
  • Speed: Fast execution
  • Impact: Low application pause

Major GC:

  • Target: Old generation objects
  • Speed: Slower execution
  • Impact: Higher application pause

Mnemonic: "Minor Frequent, Major Slow"

Question 2(b OR) [4 marks]

Explicate the finalize() method in java with its advantages.

Answer:

finalize() Method: Special method called by garbage collector before object destruction for cleanup operations.

Syntax:

Java

Advantages:

  • Resource Cleanup: Close files, database connections
  • Memory Management: Free native resources
  • Safety Net: Last chance for cleanup

Example:

Java

Mnemonic: "Finalize Frees Resources"

Question 2(c OR) [7 marks]

Explain the syntax of public static void main (String[] args). Write a Java Program to print input taken as command line argument.

Answer:

Main Method Syntax:

Java

Explanation:

  • public: Accessible from anywhere
  • static: Can be called without object creation
  • void: No return value
  • main: Method name recognized by JVM
  • String[] args: Command line arguments array

Code Example:

Java

Execution:

Bash

Output:

Number of arguments: 3
Command line arguments:
Arg 0: Hello
Arg 1: World
Arg 2: 123

Mnemonic: "Public Static Void Main Args"

Question 3(a) [3 marks]

Enlist and Explain various Java access modifier(s).

Answer:

Java Access Modifiers:

ModifierClassPackageSubclassWorld
public
protected
default
private

Usage:

  • public: Accessible everywhere
  • protected: Accessible in package and subclasses
  • default: Package-level access only
  • private: Class-level access only

Mnemonic: "Public Protected Default Private"

Question 3(b) [4 marks]

Describe interface in JAVA. Demonstrate inheritance of an interface with an executable example.

Answer:

Interface in Java: A contract that defines method signatures without implementation. Classes implement interfaces to provide method definitions.

Interface Inheritance Example:

Java

Key Features:

  • Multiple Inheritance: Interface supports multiple inheritance
  • Contract: Defines what class must implement

Mnemonic: "Interfaces Inherit Contracts"

Question 3(c) [7 marks]

Define super keyword and demonstrate the use of super keyword with an executable Java Program

Answer:

super Keyword: References immediate parent class object. Used to access parent class methods, variables, and constructors.

Code Example:

Java

Uses of super:

  • Constructor Call: super(parameters)
  • Method Call: super.methodName()
  • Variable Access: super.variableName

Mnemonic: "Super Calls Parent"

Question 3(a OR) [3 marks]

Explain package in JAVA with workable illustration.

Answer:

Package in Java: A namespace that organizes related classes and interfaces together. Provides access control and namespace management.

Package Structure:

com.company.project
├── model
│   └── Student.java
├── service
│   └── StudentService.java
└── Main.java

Example:

Java

Benefits:

  • Organization: Groups related classes
  • Access Control: Package-level access

Mnemonic: "Packages Organize Classes"

Question 3(b OR) [4 marks]

Explain abstract and final keywords with a viable illustration.

Answer:

Keywords Explanation:

KeywordPurposeUsage
abstractIncomplete implementationClasses and methods
finalPrevent modificationClasses, methods, variables

Code Example:

Java

Key Points:

  • abstract: Must be overridden in subclass
  • final: Cannot be overridden or extended

Mnemonic: "Abstract Allows, Final Forbids"

Question 3(c OR) [7 marks]

State Dynamic Method Dispatch in Java Programming language context. Construct an executable program demonstrating Dynamic Method Dispatch.

Answer:

Dynamic Method Dispatch: Runtime polymorphism where method call is resolved during execution based on actual object type, not reference type.

Code Example:

Java

Output:

Dog barks
Cat meows
Animal makes sound

Key Features:

  • Runtime Resolution: Method determined at runtime
  • Polymorphism: Same interface, different behavior
  • Virtual Method Table: JVM uses vtable for method lookup

Mnemonic: "Dynamic Dispatch Decides Runtime"

Question 4(a) [3 marks]

Explain throw and finally keywords in Exception Handling.

Answer:

Exception Handling Keywords:

KeywordPurposeUsage
throwManually throw exceptionthrow new Exception();
finallyAlways executed blockAfter try-catch

Examples:

Java

Key Points:

  • throw: Creates and throws exception explicitly
  • finally: Executes regardless of exception occurrence

Mnemonic: "Throw Creates, Finally Cleans"

Question 4(b) [4 marks]

Write a program demonstrating try…catch block in JAVA

Answer:

Code Example:

Java

Output:

Array index error: Index 5 out of bounds for length 3
Program continues...

Benefits:

  • Exception Handling: Graceful error management
  • Program Continuity: Program doesn't crash

Mnemonic: "Try Code, Catch Errors"

Question 4(c) [7 marks]

Define ArrayIndexOutOfBoundsException Exception. Write a workable JAVA program exhibiting it. Also mention input(s) which will raise this Exception.

Answer:

ArrayIndexOutOfBoundsException: Runtime exception thrown when trying to access array element with invalid index (negative or >= array length).

Code Example:

Java

Inputs that raise exception:

  • Negative Index: arr[-1]
  • Index >= Length: arr[5] for array of size 5
  • Empty Array Access: arr[0] for empty array

Prevention:

  • Bounds Checking: Verify index before access
  • Array Length: Use array.length property

Mnemonic: "Array Bounds Break Programs"

Question 4(a OR) [3 marks]

Draw and explain the life cycle of Thread in JAVA with example.

Answer:

Thread Life Cycle:

States:

  • NEW: Thread created but not started
  • RUNNABLE: Ready to run or running
  • BLOCKED: Waiting for resource
  • WAITING: Waiting indefinitely
  • TIMED_WAITING: Waiting for specific time
  • TERMINATED: Thread execution completed

Mnemonic: "New Runs, Blocks Wait, Terminates"

Question 4(b OR) [4 marks]

Explain JAVA Optional class. Describe the OfNullable() method of Optional class.

Answer:

Optional Class: Container object that may or may not contain a value. Helps avoid NullPointerException and makes code more readable.

ofNullable() Method: Returns Optional containing value if non-null, otherwise returns empty Optional.

Code Example:

Java

Benefits:

  • Null Safety: Prevents NullPointerException
  • Readable Code: Clear indication of optional values

Mnemonic: "Optional Offers Null Safety"

Question 4(c OR) [7 marks]

Write a workable JAVA program showcasing nested try…catch block.

Answer:

Code Example:

Java

Output:

Outer try block started
Inner try block started
Inner catch: Array index error - Index 5 out of bounds for length 3
Outer catch: Runtime error - Error in inner block
Outer finally: Cleanup operations
Program execution completed

Key Features:

  • Multiple Levels: Inner and outer exception handling
  • Exception Propagation: Inner exceptions can be caught by outer blocks
  • Specific Handling: Different exceptions at different levels

Mnemonic: "Nested Try Catches Layers"

Question 5(a) [3 marks]

Explain thread synchronization with an executable code in JAVA.

Answer:

Thread Synchronization: Mechanism to control access to shared resources by multiple threads to prevent data inconsistency and race conditions.

Code Example:

Java

Benefits:

  • Data Consistency: Prevents race conditions
  • Thread Safety: Safe access to shared resources

Mnemonic: "Synchronize Secures Shared Data"

Question 5(b) [4 marks]

Enlist various stream classes in JAVA. Explain anyone with an executable example.

Answer:

Stream Classes:

ClassPurposeType
FileInputStreamRead bytes from fileInput
FileOutputStreamWrite bytes to fileOutput
BufferedReaderBuffered character readingInput
PrintWriterFormatted text outputOutput

FileInputStream Example:

Java

Stream Features:

  • Byte-oriented: Handles binary data
  • Character-oriented: Handles text data

Mnemonic: "Streams Send Data"

Question 5(c) [7 marks]

Write a JAVA program extending Thread class to display odd numbers between given two integer numbers using thread.

Answer:

Code Example:

Java

Output:

Thread started: OddThread-1
Finding odd numbers between 1 and 10
Thread started: OddThread-2
Finding odd numbers between 11 and 20
Odd number: 1
Odd number: 11
Odd number: 3
Odd number: 13
...

Thread Features:

  • Concurrent Execution: Multiple threads run simultaneously
  • Thread Extension: Extends Thread class for custom behavior

Mnemonic: "Threads Take Turns"

Question 5(a OR) [3 marks]

Explain join() and alive() methods of Thread class in JAVA.

Answer:

Thread Methods:

MethodPurposeReturn Type
join()Wait for thread completionvoid
isAlive()Check if thread is runningboolean

Method Explanations:

  • join(): Current thread waits until the specified thread completes execution
  • isAlive(): Returns true if thread is still running, false if completed

Code Example:

Java

Mnemonic: "Join Waits, Alive Checks"

Question 5(b OR) [4 marks]

Define user-defined exceptions in JAVA. Write a program to show user defined exception.

Answer:

User-defined Exceptions: Custom exception classes created by extending Exception class or its subclasses to handle specific application errors.

Code Example:

Java

Output:

Valid age set: 25
Custom Exception: Age cannot be negative: -5
Custom Exception: Age cannot exceed 150: 200

Benefits:

  • Specific Error Handling: Handle application-specific errors
  • Better Code Organization: Separate exception logic

Mnemonic: "Custom Exceptions Catch Specific Errors"

Question 5(c OR) [7 marks]

Write a JAVA program to copy content of file a.txt to b.txt.

Answer:

Code Example:

Java

Output:

Source file created with sample data
File copied successfully using Stream
File copied successfully using BufferedReader

Content of buffered_b.txt:
Hello World!
This is sample text.
Java File Operations.

File Operations:

  • FileInputStream/FileOutputStream: Byte-level operations
  • BufferedReader/PrintWriter: Line-level operations with buffering
  • Exception Handling: Proper error management

Key Features:

  • Multiple Methods: Different approaches for file copying
  • Error Handling: Try-catch blocks for IOException
  • Resource Management: Proper closing of file streams

Best Practices:

  • Close Streams: Always close file streams after use
  • Exception Handling: Handle IOException properly
  • Buffer Usage: Use buffered streams for better performance

Mnemonic: "Files Flow From Source To Target"