Java Programming (4343203) - Summer 2024 Solution
Solution guide for Java Programming (4343203) Summer 2024 exam
Question 1(a) [3 marks]
Explain Garbage collection in java.
Answer: Garbage collection in Java automatically reclaims memory by removing unused objects.

Table: Garbage Collection Process
| Phase | Description |
|---|---|
| Mark | JVM identifies all live objects in memory |
| Sweep | Unused objects are removed |
| Compact | Remaining objects are reorganized to free up space |
- Automatic: No manual memory management required
- Background: Runs in separate low-priority thread
Mnemonic: "MSC: Mark-Sweep-Compact frees memory automatically"
Question 1(b) [4 marks]
Explain JVM in detail.
Answer: JVM (Java Virtual Machine) is a virtual machine that enables Java's platform independence by converting bytecode to machine code.
Diagram: JVM Architecture

- Platform Independence: Write once, run anywhere
- Security: Bytecode verification prevents dangerous operations
- Optimization: Just-in-time compilation improves performance
Mnemonic: "CLASS: Class Loader Leads All System Security"
Question 1(c) [7 marks]
Write a program in java to print Fibonacci series for N terms.
Answer: Fibonacci series generates numbers where each is the sum of the two preceding ones.
Code Block:
Java
- Initialize: Start with 0 and 1
- Loop: Iterate N times to generate sequence
- Calculation: Each number is sum of previous two
Mnemonic: "FSN: First + Second = Next number in sequence"
Question 1(c OR) [7 marks]
Write a program in java to find out minimum from any ten numbers using command line argument.
Answer: Command line arguments allow passing input values directly when executing a Java program.
Code Block:
Java
- Parse Arguments: Convert string arguments to integers
- Initialize: Set first number as minimum
- Compare: Check each number against current minimum
Mnemonic: "ICU: Initialize, Compare, Update the minimum"
Question 2(a) [3 marks]
List out basic concepts of Java OOP. Explain any one in details.
Answer: Java Object-Oriented Programming is built on fundamental concepts for modeling real-world entities.

Table: OOP Concepts in Java
| Concept | Description |
|---|---|
| Encapsulation | Binding data and methods together as a single unit |
| Inheritance | Creating new classes from existing ones |
| Polymorphism | One interface, multiple implementations |
| Abstraction | Hiding implementation details, showing functionality |
- Encapsulation: Protects data through access control
- Data Hiding: Private variables accessible through methods
Mnemonic: "PEAI: Programming Encapsulates Abstracts Inherits"
Question 2(b) [4 marks]
Explain final keyword with example.
Answer: The final keyword in Java restricts modification and creates constants, unchangeable methods, and non-inheritable classes.
Table: Uses of final Keyword
| Usage | Effect | Example |
|---|---|---|
| final variable | Cannot be changed | final int MAX = 100; |
| final method | Cannot be overridden | final void display() {} |
| final class | Cannot be extended | final class Math {} |
Code Block:
Java
Mnemonic: "VCM: Variables Constants Methods can't change"
Question 2(c) [7 marks]
What is constructor? Explain parameterized constructor with example.
Answer: A constructor initializes objects when created, with the same name as its class and no return type.
Diagram: Constructor Types

Code Block:
Java
- Parameters: Accept values during object creation
- Initialization: Set object properties with passed values
- Overloading: Multiple constructors with different parameters
Mnemonic: "SPO: Student Parameters Object initializes properties"
Question 2(a OR) [3 marks]
Explain the Java Program Structure with example.
Answer: Java program structure follows a specific hierarchy of elements organized logically.
Diagram: Java Program Structure

- Package: Groups related classes
- Import: Includes external classes
- Class: Contains variables and methods
Mnemonic: "PIC: Package Imports Class in every program"
Question 2(b OR) [4 marks]
Explain static keyword with suitable example.
Answer: Static keyword creates class-level variables and methods shared by all objects, accessible without creating instances.

Table: Static vs Non-Static
| Feature | Static | Non-Static |
|---|---|---|
| Memory | Single copy | Multiple copies |
| Access | Without object | Through object |
| Reference | Class name | Object name |
| When loaded | Class loading | Object creation |
Code Block:
Java
Mnemonic: "SCM: Static Creates Memory once for all objects"
Question 2(c OR) [7 marks]
Define Inheritance. List out types of it. Explain multilevel and hierarchical inheritance with suitable example.
Answer: Inheritance is an OOP principle where a new class acquires properties and behaviors from an existing class.
Table: Types of Inheritance in Java
| Type | Description |
|---|---|
| Single | One subclass extends one superclass |
| Multilevel | Chain of inheritance (A→B→C) |
| Hierarchical | Multiple subclasses extend one superclass |
| Multiple | One class extends multiple classes (via interfaces) |
Diagram: Multilevel vs Hierarchical Inheritance

Code Block:
Java
Mnemonic: "SMHM: Single Multilevel Hierarchical Makes inheritance types"
Question 3(a) [3 marks]
Explain this keyword with suitable example.
Answer: The 'this' keyword in Java refers to the current object, used to differentiate between instance variables and parameters.

Table: Uses of 'this' Keyword
| Use | Purpose |
|---|---|
| this.variable | Access instance variables |
| this() | Call current class constructor |
| return this | Return current object |
Code Block:
Java
Mnemonic: "VAR: Variables Access Resolution using this"
Question 3(b) [4 marks]
Explain different access controls in Java.
Answer: Access controls in Java regulate visibility and accessibility of classes, methods, and variables.
Table: Java Access Modifiers
| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
| private | ✓ | ✗ | ✗ | ✗ |
| default | ✓ | ✓ | ✗ | ✗ |
| protected | ✓ | ✓ | ✓ | ✗ |
| public | ✓ | ✓ | ✓ | ✓ |
- Private: Only within the same class
- Default: Within the same package
- Protected: Within package and subclasses
- Public: Accessible everywhere
Mnemonic: "PDPP: Private Default Protected Public from narrow to wide"
Question 3(c) [7 marks]
What is interface? Explain multiple inheritance using interface with example.
Answer: An interface is a contract that specifies what a class must do, containing abstract methods, constants, and (since Java 8) default methods.
Diagram: Multiple Inheritance with Interfaces

Code Block:
Java
- Contract: Defines behavior without implementation
- Implements: Classes fulfill the contract
- Multiple: Can implement many interfaces
Mnemonic: "CIM: Contract Implements Multiple interfaces"
Question 3(a OR) [3 marks]
Explain super keyword with example.
Answer: The super keyword refers to the parent class, used to access parent methods, constructors, and variables.
Table: Uses of super Keyword
| Use | Purpose |
|---|---|
| super.variable | Access parent variable |
| super.method() | Call parent method |
| super() | Call parent constructor |
Code Block:
Java
Mnemonic: "VMC: Variables Methods Constructors accessed by super"
Question 3(b OR) [4 marks]
What is package? Write steps to create a package and give example of it.
Answer: A package in Java is a namespace that organizes related classes and interfaces, preventing naming conflicts.
Table: Steps to Create a Package
| Step | Action |
|---|---|
| 1 | Declare package name at top of file |
| 2 | Create directory structure matching package name |
| 3 | Save Java file in the directory |
| 4 | Compile with -d option |
| 5 | Import package to use it |
Code Block:
Java
Mnemonic: "DISCO: Declare Import Save Compile Organize"
Question 3(c OR) [7 marks]
Define: Method Overriding. List out Rules for method overriding. Write a java program that implements method overriding.
Answer: Method overriding occurs when a subclass provides a specific implementation for a method already defined in its parent class.

Table: Rules for Method Overriding
| Rule | Description |
|---|---|
| Same name | Method must have same name |
| Same parameters | Parameter count and type must match |
| Same return type | Return type must be same or subtype (covariant) |
| Access modifier | Can't be more restrictive |
| Exceptions | Can't throw broader checked exceptions |
Code Block:
Java
- Runtime Polymorphism: Method resolution at runtime
- @Override: Annotation ensures method is overriding
- Inheritance: Requires IS-A relationship
Mnemonic: "SPARE: Same Parameters Access Return Exceptions"
Question 4(a) [3 marks]
Explain abstract class with suitable example.
Answer: An abstract class cannot be instantiated and may contain abstract methods that must be implemented by subclasses.

Table: Abstract Class vs Interface
| Feature | Abstract Class | Interface |
|---|---|---|
| Instantiation | Cannot | Cannot |
| Methods | Concrete and abstract | Abstract (+ default since Java 8) |
| Variables | Any type | Only constants |
| Constructor | Has | Doesn't have |
Code Block:
Java
Mnemonic: "PAI: Partial Abstract Implementation is key"
Question 4(b) [4 marks]
What is Thread? Explain Thread life cycle.
Answer: A thread is a lightweight subprocess, the smallest unit of processing that allows concurrent execution.
Diagram: Thread Life Cycle

- New: Thread created but not started
- Runnable: Ready to run when CPU time is given
- Running: Currently executing
- Blocked/Waiting: Temporarily inactive
- Terminated: Completed execution
Mnemonic: "NRRBT: New Runnable Running Blocked Terminated"
Question 4(c) [7 marks]
Write a program in java that creates the multiple threads by implementing the Thread class.
Answer: Creating threads by implementing Thread class allows multiple tasks to execute concurrently.
Code Block:
Java
- Extend Thread: Create thread by extending Thread class
- Override run(): Define task in run method
- start(): Begin thread execution
Mnemonic: "ERS: Extend Run Start to create threads"
Question 4(a OR) [3 marks]
Explain final class with suitable example.
Answer: A final class cannot be extended, preventing inheritance and modification of its design.
Table: Final Class Characteristics
| Feature | Description |
|---|---|
| Inheritance | Cannot be subclassed |
| Methods | Implicitly final |
| Security | Prevents design alteration |
| Example | String, Math classes |
Code Block:
Java
- Security: Protects sensitive implementations
- Immutability: Helps create immutable classes
- Optimization: JVM can optimize final classes
Mnemonic: "SIO: Security Immutability Optimization"
Question 4(b OR) [4 marks]
Explain thread priorities with suitable example.
Answer: Thread priorities determine the order in which threads are scheduled for execution, from 1 (lowest) to 10 (highest).
Table: Thread Priority Constants
| Constant | Value | Description |
|---|---|---|
| MIN_PRIORITY | 1 | Lowest priority |
| NORM_PRIORITY | 5 | Default priority |
| MAX_PRIORITY | 10 | Highest priority |
Code Block:
Java
Mnemonic: "HNL: High Normal Low priorities in threads"
Question 4(c OR) [7 marks]
What is Exception? Write a program that shows the use of Arithmetic Exception.
Answer: An exception is an abnormal condition that disrupts the normal flow of program execution.
Diagram: Exception Hierarchy

Code Block:
Java
- Try Block: Contains code that might throw exceptions
- Catch Block: Handles the specific exception
- Finally Block: Always executes regardless of exception
Mnemonic: "TCF: Try Catch Finally handles exceptions"
Question 5(a) [3 marks]
Write a Java Program to find sum and average of 10 numbers of an array.
Answer: Arrays store multiple values of the same type, enabling sequential processing of elements.

Code Block:
Java
- Declaration: Creates fixed-size collection
- Iteration: Sequential access to elements
- Calculation: Process values for results
Mnemonic: "DIC: Declare Iterate Calculate for array processing"
Question 5(b) [4 marks]
Write a Java program to handle user defined exception for 'Divide by Zero' error.
Answer: User-defined exceptions allow creating custom exception types for specific application requirements.
Code Block:
Java
- Custom Class: Extends Exception class
- Throwing: Use throw keyword with new instance
- Handling: Catch specific exception type
Mnemonic: "CTE: Create Throw Exception when needed"
Question 5(c) [7 marks]
Write a java program to create a text file and perform read operation on the text file.
Answer: Java provides I/O classes to work with files, allowing creation, writing, and reading operations.
Code Block:
Java
- FileWriter: Creates and writes to files
- FileReader: Reads character data from files
- BufferedReader: Efficiently reads text by lines
Mnemonic: "WRC: Write Read Close for file operations"
Question 5(a OR) [3 marks]
Explain java I/O process.
Answer: Java I/O process involves transferring data to and from various sources using streams.
Table: Java I/O Stream Types
| Classification | Types |
|---|---|
| Direction | Input, Output |
| Data Type | Byte Streams, Character Streams |
| Functionality | Basic, Buffered, Data, Object |
Diagram: Java I/O Hierarchy

- Stream: Sequence of data flowing between source and destination
- Buffering: Improves performance by reducing disk access
Mnemonic: "SBI: Stream Buffered Input/Output"
Question 5(b OR) [4 marks]
Explain throw and finally in Exception Handling with example.
Answer: Exception handling mechanisms control program flow during errors, ensuring graceful execution.
Table: throw vs finally
| Feature | throw | finally |
|---|---|---|
| Purpose | Explicitly throws exception | Ensures code execution |
| Placement | Inside method | After try-catch blocks |
| Execution | When condition met | Always, even with return |
| Usage | Control flow | Resource cleanup |
Code Block:
Java
Mnemonic: "TERA: Throw Exception Regardless Always finally executes"
Question 5(c OR) [7 marks]
Write a java program to display the content of a text file and perform append operation on the text file.
Code Block:
Java
- FileWriter(file, true): Second parameter enables append mode
- BufferedReader: Efficiently reads text by lines
- Reusable Method: Encapsulates reading functionality
Mnemonic: "CAD: Create Append Display file operations"