Object Oriented Programming with Java (4341602) - Summer 2024 Solution
Solution guide for Object Oriented Programming with Java (4341602) Summer 2024 exam
Question 1(a) [3 marks]
Explain the basic structure of Java program.
Answer:
Basic Structure Table:
| Component | Description |
|---|---|
| Package declaration | Optional, defines package membership |
| Import statements | Imports required classes/packages |
| Class declaration | Defines the main class |
| Main method | Entry point: public static void main(String[] args) |
Diagram:
goat
- Package: Groups related classes
- Import: Access external classes
- Class: Blueprint for objects
- Main method: Program execution starts here
Mnemonic: "PICM - Package, Import, Class, Main"
Question 1(b) [4 marks]
List out different features of java. Explain any two.
Answer:
Java Features Table:
| Feature | Description |
|---|---|
| Platform Independent | Write once, run anywhere |
| Object Oriented | Everything is an object |
| Simple | Easy syntax, no pointers |
| Secure | Built-in security features |
| Robust | Strong memory management |
| Multithreaded | Concurrent execution support |
Detailed Explanation:
Platform Independence:
- Java code compiles to bytecode
- JVM interprets bytecode on any platform
- Same program runs on Windows, Linux, Mac
Object Oriented:
- Encapsulation: Data hiding in classes
- Inheritance: Code reuse through extends
- Polymorphism: Same method, different behavior
Mnemonic: "POSRMM - Platform, Object, Simple, Robust, Multithreaded, Memory"
Question 1(c) [7 marks]
Write a program in java to find out sum of the digits of entered number. (Ex. Number is 123 output is 6).
Answer:
Java
Algorithm Table:
| Step | Operation | Example (123) |
|---|---|---|
| 1 | Extract last digit (n%10) | 123%10 = 3 |
| 2 | Add to sum | sum = 0+3 = 3 |
| 3 | Remove last digit (n/10) | 123/10 = 12 |
| 4 | Repeat until n=0 | Continue |
- Input: Command line argument
- Process: Extract digits using modulo
- Output: Sum of all digits
Mnemonic: "EARD - Extract, Add, Remove, Done"
Question 1(c OR) [7 marks]
Write a program in java to find out maximum from any ten numbers using command line argument.
Answer:
Java
Process Table:
| Step | Action | Details |
|---|---|---|
| 1 | Check args | Ensure 10 numbers provided |
| 2 | Initialize max | First number as initial max |
| 3 | Compare loop | Check each remaining number |
| 4 | Update max | If current > max, update |
- Validation: Check argument count
- Comparison: Standard maximum finding
- Output: Display the largest number
Mnemonic: "VCIU - Validate, Compare, Initialize, Update"
Question 2(a) [3 marks]
List out different concept of oop. Explain anyone in detail.
Answer:
OOP Concepts Table:
| Concept | Description |
|---|---|
| Encapsulation | Data hiding and bundling |
| Inheritance | Code reuse from parent class |
| Polymorphism | One interface, many forms |
| Abstraction | Hiding implementation details |
Encapsulation Details:
- Combines data and methods in single unit
- Uses private access modifiers for data
- Provides public getter/setter methods
- Protects data from unauthorized access
Benefits:
- Security: Data protection
- Maintenance: Easy code updates
- Flexibility: Change implementation easily
Mnemonic: "EIPA - Encapsulation, Inheritance, Polymorphism, Abstraction"
Question 2(b) [4 marks]
Explain JVM in detail.
Answer:
JVM Architecture Diagram:
JVM Components Table:
| Component | Function |
|---|---|
| Class Loader | Loads .class files into memory |
| Memory Areas | Heap, Stack, Method area |
| Execution Engine | Executes bytecode |
| JIT Compiler | Optimizes frequently used code |
- Platform Independence: Same bytecode runs everywhere
- Memory Management: Automatic garbage collection
- Security: Bytecode verification before execution
Mnemonic: "CEMJ - Class loader, Execution, Memory, JIT"
Question 2(c) [7 marks]
Explain constructor overloading with example.
Answer:
Java
Constructor Types Table:
| Constructor | Parameters | Use Case |
|---|---|---|
| Default | None | Basic object creation |
| Single param | Name only | Partial initialization |
| Two param | Name, Age | More specific data |
| Full param | All fields | Complete initialization |
- Same name: All constructors have class name
- Different parameters: Number or type varies
- Compile-time: Decision made during compilation
Mnemonic: "SNDF - Same Name, Different Parameters, Flexible"
Question 2(a OR) [3 marks]
What is wrapper class? Explain with example.
Answer:
Wrapper Classes Table:
| Primitive | Wrapper Class |
|---|---|
| byte | Byte |
| int | Integer |
| float | Float |
| double | Double |
| char | Character |
| boolean | Boolean |
Example:
Java
- Boxing: Convert primitive to wrapper object
- Unboxing: Extract primitive from wrapper
- Collections: Only objects allowed in collections
Mnemonic: "BUC - Boxing, Unboxing, Collections"
Question 2(b OR) [4 marks]
Explain static keyword with example.
Answer:
Java
Static Features Table:
| Feature | Characteristics |
|---|---|
| Static Variable | Shared among all instances |
| Static Method | Called without object creation |
| Static Block | Executed once when class loads |
| Memory | Stored in method area |
- Class level: Belongs to class, not instance
- Memory efficiency: Single copy for all objects
- Access: Use class name to access
Mnemonic: "SCMA - Shared, Class-level, Memory, Access"
Question 2(c OR) [7 marks]
What is constructor? Explain copy constructor with example.
Answer:
Constructor Definition: Constructor is a special method that initializes objects when they are created.
Java
Constructor Types Table:
| Type | Purpose | Parameters |
|---|---|---|
| Default | Basic initialization | None |
| Parameterized | Custom initialization | User-defined |
| Copy | Clone existing object | Same class object |
- Same name: Constructor name = class name
- No return type: Not even void
- Automatic call: Called when object created
Mnemonic: "SNAC - Same Name, Automatic Call"
Question 3(a) [3 marks]
Explain any four-string function in java with example.
Answer:
String Functions Table:
| Function | Purpose | Example |
|---|---|---|
| length() | Returns string length | "Hello".length() → 5 |
| charAt(index) | Character at position | "Java".charAt(1) → 'a' |
| substring(start) | Extract portion | "Program".substring(3) → "gram" |
| toUpperCase() | Convert to uppercase | "java".toUpperCase() → "JAVA" |
Code Example:
Java
- Immutable: String objects cannot be changed
- Return new: Methods return new string objects
- Zero-indexed: Position counting starts from 0
Mnemonic: "LCST - Length, Character, Substring, Transform"
Question 3(b) [4 marks]
List out different types of inheritance. Explain multilevel inheritance.
Answer:
Inheritance Types Table:
| Type | Description |
|---|---|
| Single | One parent, one child |
| Multilevel | Chain of inheritance |
| Hierarchical | One parent, multiple children |
| Multiple | Multiple parents (via interfaces) |
Multilevel Inheritance Diagram:
Example:
Java
- Chain inheritance: Grandparent → Parent → Child
- Feature accumulation: Child gets all ancestor features
- Method access: Can call methods from all levels
Mnemonic: "SMHM - Single, Multilevel, Hierarchical, Multiple"
Question 3(c) [7 marks]
What is interface? Explain multiple inheritance with example.
Answer:
Interface Definition: Interface is a contract that defines what methods a class must implement, without providing implementation.
Java
Interface vs Class Table:
| Feature | Interface | Class |
|---|---|---|
| Methods | Abstract (default/static allowed) | Concrete |
| Variables | public static final | Any type |
| Inheritance | Multiple allowed | Single only |
| Instantiation | Cannot create objects | Can create objects |
Multiple Inheritance Diagram:
- Contract: Defines what, not how
- Multiple implementation: One class, many interfaces
- Diamond problem solution: Interfaces solve multiple inheritance issues
Mnemonic: "CMDS - Contract, Multiple, Diamond-solution"
Question 3(a OR) [3 marks]
Explain this keyword with example.
Answer:
'this' Keyword Uses Table:
| Use Case | Purpose |
|---|---|
| Instance variable | Differentiate from parameter |
| Method call | Call another method of same class |
| Constructor call | Call another constructor |
| Return object | Return current object reference |
Example:
Java
- Current object: Refers to current instance
- Parameter conflict: Resolve naming conflicts
- Method chaining: Enable fluent interface
Mnemonic: "CRPM - Current, Resolve, Parameter, Method"
Question 3(b OR) [4 marks]
Explain method overriding with example.
Answer:
Java
Overriding Rules Table:
| Rule | Description |
|---|---|
| Same signature | Method name, parameters must match |
| Inheritance | Must be in parent-child relationship |
| @Override | Annotation for compiler checking |
| Runtime decision | Method called based on object type |
Usage:
Java
- Runtime polymorphism: Decision made during execution
- Same interface: Different behavior for different classes
- Dynamic binding: Method resolution at runtime
Mnemonic: "SSRD - Same Signature, Runtime Decision"
Question 3(c OR) [7 marks]
What is package? Write steps to create a package and give example of it.
Answer:
Package Definition: Package is a namespace that organizes related classes and interfaces, providing access control and avoiding naming conflicts.
Steps to Create Package:
| Step | Action | Command/Code |
|---|---|---|
| 1 | Create directory | mkdir com/company/utils |
| 2 | Add package declaration | package com.company.utils; |
| 3 | Write class | public class MathUtils |
| 4 | Compile | javac -d . MathUtils.java |
| 5 | Import and use | import com.company.utils.*; |
Example Package Structure:
src/
com/
company/
utils/
MathUtils.java
StringUtils.java
models/
Student.java
MathUtils.java:
Java
Using Package:
Java
Package Benefits Table:
| Benefit | Description |
|---|---|
| Organization | Logical grouping of classes |
| Namespace | Avoid naming conflicts |
| Access control | Package-private access |
| Maintenance | Easier code management |
Mnemonic: "ONAM - Organization, Namespace, Access, Maintenance"
Question 4(a) [3 marks]
Explain thread priorities with suitable example.
Answer:
Thread Priority Table:
| Priority Level | Constant | Value |
|---|---|---|
| Minimum | MIN_PRIORITY | 1 |
| Normal | NORM_PRIORITY | 5 |
| Maximum | MAX_PRIORITY | 10 |
Example:
Java
- Higher priority: More likely to get CPU time
- Not guaranteed: JVM decides actual scheduling
- Default priority: Every thread starts with NORM_PRIORITY
Mnemonic: "HNG - Higher priority, Not Guaranteed"
Question 4(b) [4 marks]
What is Thread? Explain Thread life cycle.
Answer:
Thread Definition: Thread is a lightweight sub-process that allows concurrent execution of multiple tasks within a program.
Thread Life Cycle Diagram:
Thread States Table:
| State | Description |
|---|---|
| NEW | Thread created but not started |
| RUNNABLE | Ready to run, waiting for CPU |
| RUNNING | Currently executing |
| BLOCKED/WAITING | Waiting for resource/condition |
| TERMINATED | Execution completed |
State Transitions:
-
NEW → RUNNABLE: start() method called
-
RUNNABLE → RUNNING: Thread scheduler assigns CPU
-
RUNNING → BLOCKED: Waiting for I/O or lock
-
RUNNING → TERMINATED: run() method completes
-
Concurrent execution: Multiple threads run simultaneously
-
JVM managed: Thread scheduler controls execution
-
Resource sharing: Threads share memory space
Mnemonic: "NRBT - New, Runnable, Blocked, Terminated"
Question 4(c) [7 marks]
Write a program in java that create the multiple threads by implementing the Thread class.
Answer:
Java
Implementation Steps Table:
| Step | Action |
|---|---|
| 1 | Extend Thread class |
| 2 | Override run() method |
| 3 | Create thread objects |
| 4 | Call start() method |
- Extends Thread: Inherit threading capabilities
- Override run(): Define thread's execution logic
- start() method: Begin thread execution
- Concurrent execution: All threads run simultaneously
Mnemonic: "EOCS - Extend, Override, Create, Start"
Question 4(a OR) [3 marks]
Explain basic concept of Exception Handling.
Answer:
Exception Handling Concepts Table:
| Concept | Description |
|---|---|
| Exception | Runtime error that disrupts normal flow |
| try block | Code that might throw exception |
| catch block | Handles specific exception types |
| finally block | Always executes, cleanup code |
Exception Hierarchy:
Basic Syntax:
Java
- Graceful handling: Program continues after exception
- Error prevention: Avoid program crash
- Resource cleanup: finally block ensures cleanup
Mnemonic: "TRCF - Try, Runtime error, Catch, Finally"
Question 4(b OR) [4 marks]
Explain multiple catch with suitable example.
Answer:
Java
Multiple Catch Rules Table:
| Rule | Description |
|---|---|
| Specific first | Handle specific exceptions before general |
| One catch executes | Only first matching catch runs |
| Order matters | More specific to more general |
| finally always | finally block always executes |
Exception Flow:
- ArrayIndexOutOfBoundsException: Invalid array access
- ArithmeticException: Division by zero
- NumberFormatException: Invalid number conversion
- Exception: Catches any remaining exceptions
Mnemonic: "SOOF - Specific first, One executes, Order matters, Finally"
Question 4(c OR) [7 marks]
What is Exception? Write a program that show the use of Arithmetic Exception.
Answer:
Exception Definition: Exception is an event that occurs during program execution and disrupts the normal flow of instructions.
Java
Exception Types Table:
| Type | Description | Example |
|---|---|---|
| Checked | Must be handled at compile time | IOException |
| Unchecked | Runtime exceptions | ArithmeticException |
| Error | System-level problems | OutOfMemoryError |
ArithmeticException Causes:
- Division by zero: Most common cause
- Modulo by zero: Remainder operation with zero
- Invalid operations: Mathematical impossibilities
Program Flow:
- Normal execution: Try block runs
- Exception occurs: ArithmeticException thrown
- Exception caught: Catch block handles it
- Cleanup: Finally block executes
- Continue: Program continues after handling
Mnemonic: "DZMI - Division by Zero, Mathematical Invalid"
Question 5(a) [3 marks]
Explain ArrayIndexOutOfBound Exception in Java with example.
Answer:
ArrayIndexOutOfBound Exception Table:
| Cause | Description | Example |
|---|---|---|
| Negative index | Index less than 0 | arr[-1] |
| Index >= length | Index beyond array size | arr[5] for size 3 |
| Empty array | Access on zero-length array | arr[0] for length 0 |
Example:
Java
- Runtime exception: Occurs during program execution
- Index validation: Always check array bounds
- Prevention: Use array.length for bounds checking
Mnemonic: "NIE - Negative, Index-exceed, Empty"
Question 5(b) [4 marks]
Explain basics of stream classes.
Answer:
Stream Classes Hierarchy:
Stream Types Table:
| Stream Type | Purpose | Classes |
|---|---|---|
| Byte Streams | Handle binary data | InputStream, OutputStream |
| Character Streams | Handle text data | Reader, Writer |
| Buffered Streams | Improve performance | BufferedReader, BufferedWriter |
| File Streams | File operations | FileInputStream, FileOutputStream |
Basic Operations:
- Input: Read data from source
- Output: Write data to destination
- Buffering: Store data temporarily for efficiency
- Closing: Release system resources
Stream Benefits:
- Abstraction: Uniform interface for I/O
- Efficiency: Buffered operations
- Flexibility: Various data sources/destinations
Mnemonic: "BCIF - Byte, Character, Input/Output, File"
Question 5(c) [7 marks]
Write a java program to create a text file and perform write operation on the text file.
Answer:
Java
File Write Methods Table:
| Method | Performance | Resource Management | Use Case |
|---|---|---|---|
| FileWriter | Basic | Manual close() | Simple writes |
| BufferedWriter | High | Manual close() | Large data |
| Try-with-resources | High | Automatic | Recommended |
Write Operation Steps:
- Create writer object: FileWriter or BufferedWriter
- Write data: Use write() method
- Close stream: Release resources
- Handle exceptions: IOException management
File Operations:
- Create: New file if doesn't exist
- Overwrite: Replaces existing content
- Append: Add to existing content (use append mode)
Mnemonic: "CWCH - Create, Write, Close, Handle"
Question 5(a OR) [3 marks]
Explain Divide by Zero Exception in Java with example.
Answer:
Divide by Zero Exception Table:
| Operation | Result | Exception |
|---|---|---|
| Integer division | Undefined | ArithmeticException |
| Float division | Infinity | No exception |
| Modulo by zero | Undefined | ArithmeticException |
Example:
Java
- Integer arithmetic: Throws ArithmeticException
- Floating point: Returns Infinity (IEEE 754 standard)
- Prevention: Check denominator before division
Mnemonic: "IFM - Integer exception, Float infinity, Modulo error"
Question 5(b OR) [4 marks]
Explain try and catch block with example.
Answer:
Try-Catch Structure:
Java
Example:
Java
Try-Catch Flow Table:
| Block | Purpose | Execution |
|---|---|---|
| try | Contains risky code | Always executed first |
| catch | Handles exceptions | Only if exception occurs |
| finally | Cleanup code | Always executed |
- Exception matching: First matching catch block executes
- Control flow: Program continues after catch block
- Multiple catches: Handle different exception types
Mnemonic: "TCF - Try risky, Catch exception, Finally cleanup"
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.
Answer:
Java
File Operations Table:
| Operation | Method | Purpose |
|---|---|---|
| Create | FileWriter(filename) | Create new file |
| Read | BufferedReader.readLine() | Read file content |
| Append | FileWriter(filename, true) | Add to existing file |
| Display | System.out.println() | Show content |
File Operations Flow:
- Create initial file: Write initial content
- Display content: Read and show current content
- Append data: Add new information
- Display updated: Show modified content
- Statistics: Count lines and characters
Append vs Write:
- Write mode: Overwrites existing content
- Append mode: Adds to end of existing content
- Constructor parameter: Second parameter true enables append
Resource Management:
- Try-with-resources: Automatic close()
- Exception handling: FileNotFoundException, IOException
- Buffered operations: Better performance for large files
Mnemonic: "CDADS - Create, Display, Append, Display, Statistics"