Object Oriented Programming With Java (4341602) - Summer 2023 Solution
Solution guide for Object Oriented Programming With Java (4341602) Summer 2023 exam
Question 1(a) [3 marks]
Differentiate between Procedure-Oriented Programming (POP) and Object-Oriented Programming (OOP).
Answer:
Table:
| Aspect | POP | OOP |
|---|---|---|
| Focus | Functions/Procedures | Objects and Classes |
| Data Security | Less secure, global data | More secure, data encapsulation |
| Problem Solving | Top-down approach | Bottom-up approach |
| Code Reusability | Limited | High through inheritance |
| Examples | C, Pascal | Java, C++, Python |
- POP: Program divided into functions, data flows between functions
- OOP: Program organized around objects that contain both data and methods
Mnemonic: "POP Functions, OOP Objects"
Question 1(b) [4 marks]
Explain Super keyword in inheritance with suitable example.
Answer:
Super keyword is used to access parent class members from child class.
Table: Super keyword uses
| Use | Purpose | Example |
|---|---|---|
| super() | Call parent constructor | super(name, age) |
| super.method() | Call parent method | super.display() |
| super.variable | Access parent variable | super.name |
Code Block:
Java
Mnemonic: "Super calls Parent"
Question 1(c) [7 marks]
Define: Method Overriding. List out Rules for method overriding. Write a java program that implements method overriding.
Answer:
Method Overriding: Child class provides specific implementation of parent class method with same signature.
Table: Method Overriding Rules
| Rule | Description |
|---|---|
| Same name | Method name must be identical |
| Same parameters | Parameter list must match exactly |
| IS-A relationship | Must have inheritance |
| Access modifier | Cannot reduce visibility |
| Return type | Must be same or covariant |
Code Block:
Java
Mnemonic: "Override Same Signature"
Question 1(c OR) [7 marks]
Describe: Interface. Write a java program using interface to demonstrate multiple inheritance.
Answer:
Interface: Blueprint containing abstract methods and constants. Classes implement interfaces to achieve multiple inheritance.
Table: Interface Features
| Feature | Description |
|---|---|
| Abstract methods | No implementation (before Java 8) |
| Constants | All variables are public static final |
| Multiple inheritance | Class can implement multiple interfaces |
| Default methods | Concrete methods (Java 8+) |
Code Block:
Java
Mnemonic: "Interface Multiple Implementation"
Question 2(a) [3 marks]
Explain the Java Program Structure with example.
Answer:
Java Program Structure consists of package, imports, class declaration, and main method.
Diagram:
goat
Code Block:
Java
Mnemonic: "Package Import Class Main"
Question 2(b) [4 marks]
Explain static keyword with suitable example.
Answer:
Static keyword belongs to class rather than instance. Memory allocated once.
Table: Static Uses
| Type | Description | Example |
|---|---|---|
| Static variable | Shared by all objects | static int count |
| Static method | Called without object | static void display() |
| Static block | Executes before main | static |
Code Block:
Java
Mnemonic: "Static Shared by Class"
Question 2(c) [7 marks]
Define: Constructor. List out types of it. Explain Parameterized and copy constructor with suitable example.
Answer:
Constructor: Special method to initialize objects, same name as class, no return type.
Table: Constructor Types
| Type | Description | Example |
|---|---|---|
| Default | No parameters | Student() |
| Parameterized | With parameters | Student(String name) |
| Copy | Creates copy of object | Student(Student s) |
Code Block:
Java
Mnemonic: "Constructor Initializes Objects"
Question 2(a OR) [3 marks]
Explain the Primitive Data Types and User Defined Data Types in java.
Answer:
Primitive Data Types: Built-in types provided by Java language. User Defined Types: Custom types created by programmer using classes.
Table: Data Types
| Category | Types | Size | Example |
|---|---|---|---|
| Primitive | byte, short, int, long | 1,2,4,8 bytes | int x = 10; |
| Primitive | float, double | 4,8 bytes | double d = 3.14; |
| Primitive | char, boolean | 2,1 bytes | char c = 'A'; |
| User Defined | Class, Interface, Array | Variable | Student s; |
- Primitive: Stored in stack, faster access
- User Defined: Stored in heap, complex operations
Mnemonic: "Primitive Built-in, User Custom"
Question 2(b OR) [4 marks]
Explain this keyword with suitable example.
Answer:
This keyword refers to current object instance, used to distinguish between instance and local variables.
Table: This keyword uses
| Use | Purpose | Example |
|---|---|---|
| this.variable | Access instance variable | this.name = name; |
| this.method() | Call instance method | this.display(); |
| this() | Call constructor | this(name, age); |
Code Block:
Java
Mnemonic: "This Current Object"
Question 2(c OR) [7 marks]
Define Inheritance. List out types of it. Explain multilevel and hierarchical inheritance with suitable example.
Answer:
Inheritance: Mechanism where child class acquires properties and methods of parent class.
Table: Inheritance Types
| Type | Description | Structure |
|---|---|---|
| Single | One parent, one child | A → B |
| Multilevel | Chain of inheritance | A → B → C |
| Hierarchical | One parent, multiple children | A → B, A → C |
| Multiple | Multiple parents (via interfaces) | B,C → A |
Diagram - Multilevel:
Code Block - Multilevel:
Java
Diagram - Hierarchical:
Code Block - Hierarchical:
Java
Mnemonic: "Inheritance Shares Properties"
Question 3(a) [3 marks]
Explain Type Conversion and Casting in java.
Answer:
Type Conversion: Converting one data type to another. Casting: Explicit type conversion by programmer.
Table: Type Conversion
| Type | Description | Example |
|---|---|---|
| Implicit (Widening) | Automatic, smaller to larger | int to double |
| Explicit (Narrowing) | Manual, larger to smaller | double to int |
Code Block:
Java
Mnemonic: "Implicit Auto, Explicit Manual"
Question 3(b) [4 marks]
Explain different visibility controls used in Java.
Answer:
Visibility Controls (Access Modifiers): Control access to classes, methods, and variables.
Table: Access Modifiers
| Modifier | Same Class | Same Package | Subclass | Different Package |
|---|---|---|---|---|
| private | ✓ | ✗ | ✗ | ✗ |
| default | ✓ | ✓ | ✗ | ✗ |
| protected | ✓ | ✓ | ✓ | ✗ |
| public | ✓ | ✓ | ✓ | ✓ |
Code Block:
Java
Mnemonic: "Private Package Protected Public"
Question 3(c) [7 marks]
Define: Thread. List different methods used to create Thread. Explain Thread life cycle in detail.
Answer:
Thread: Lightweight subprocess that allows concurrent execution of multiple parts of program.
Table: Thread Creation Methods
| Method | Description | Example |
|---|---|---|
| Extending Thread | Inherit Thread class | class MyThread extends Thread |
| Implementing Runnable | Implement Runnable interface | class MyTask implements Runnable |
Diagram: Thread Life Cycle
Table: Thread States
| State | Description |
|---|---|
| NEW | Thread created but not started |
| RUNNABLE | Ready to run, waiting for CPU |
| RUNNING | Currently executing |
| BLOCKED | Waiting for resource or sleep |
| TERMINATED | Execution completed |
Code Block:
Java
Mnemonic: "Thread Concurrent Execution"
Question 3(a OR) [3 marks]
Explain the purpose of JVM in java.
Answer:
JVM (Java Virtual Machine): Runtime environment that executes Java bytecode and provides platform independence.
Table: JVM Components
| Component | Purpose |
|---|---|
| Class Loader | Loads .class files into memory |
| Execution Engine | Executes bytecode |
| Memory Area | Manages heap and stack memory |
| Garbage Collector | Automatic memory management |
Diagram:
goat
- Platform Independence: "Write Once, Run Anywhere"
- Memory Management: Automatic garbage collection
- Security: Bytecode verification
Mnemonic: "JVM Java Virtual Machine"
Question 3(b OR) [4 marks]
Define: Package. Write the steps to create a Package with suitable example.
Answer:
Package: Collection of related classes and interfaces grouped together, providing namespace and access control.
Table: Package Benefits
| Benefit | Description |
|---|---|
| Namespace | Avoid name conflicts |
| Access Control | Better encapsulation |
| Organization | Logical grouping |
| Reusability | Easy to maintain |
Steps to create Package:
- Declare package at top of file
- Create directory structure matching package name
- Compile with package structure
- Import in other classes
Code Block:
Java
Directory Structure:
com/
company/
utilities/
Calculator.class
Main.class
Mnemonic: "Package Groups Classes"
Question 3(c OR) [7 marks]
Explain Synchronization in Thread with suitable example.
Answer:
Synchronization: Mechanism to control access to shared resources by multiple threads to avoid data inconsistency.
Table: Synchronization Types
| Type | Description | Usage |
|---|---|---|
| Synchronized method | Entire method locked | synchronized void method() |
| Synchronized block | Specific code block locked | synchronized(object) |
| Static synchronization | Class level locking | synchronized static void method() |
Diagram: Without vs With Synchronization
Code Block:
Java
Mnemonic: "Synchronization Prevents Race Conditions"
Question 4(a) [3 marks]
Differentiate between String class and StringBuffer class.
Answer:
Table: String vs StringBuffer
| Aspect | String | StringBuffer |
|---|---|---|
| Mutability | Immutable (cannot change) | Mutable (can change) |
| Performance | Slower for concatenation | Faster for concatenation |
| Memory | Creates new object each time | Modifies existing object |
| Thread Safety | Thread safe | Thread safe |
| Methods | concat(), substring() | append(), insert(), delete() |
Code Block:
Java
- String: Use when content doesn't change frequently
- StringBuffer: Use when frequent modifications needed
Mnemonic: "String Immutable, StringBuffer Mutable"
Question 4(b) [4 marks]
Write a Java Program to find sum and average of 10 numbers of an array.
Answer:
Code Block:
Java
Output:
Array elements: 10 20 30 40 50 60 70 80 90 100
Sum: 550
Average: 55.0
Logic Steps:
- Initialize array with 10 numbers
- Loop through array to calculate sum
- Calculate average = sum / length
- Display results
Mnemonic: "Loop Sum Divide Average"
Question 4(c) [7 marks]
I) Explain abstract class with suitable example. II) Explain final class with suitable example.
Answer:
I) Abstract Class: Class that cannot be instantiated, contains abstract methods that must be implemented by subclasses.
Table: Abstract Class Features
| Feature | Description |
|---|---|
| Cannot instantiate | No object creation |
| Abstract methods | Methods without implementation |
| Concrete methods | Methods with implementation |
| Inheritance | Subclasses must implement abstract methods |
Code Block - Abstract Class:
Java
II) Final Class: Class that cannot be extended (no inheritance allowed).
Table: Final Class Features
| Feature | Description |
|---|---|
| No inheritance | Cannot be extended |
| Security | Prevents modification |
| Performance | Better optimization |
| Examples | String, Integer, System |
Code Block - Final Class:
Java
Mnemonic: "Abstract Incomplete, Final Complete"
Question 4(a OR) [3 marks]
Explain Garbage Collection in Java.
Answer:
Garbage Collection: Automatic memory management process that removes unused objects from heap memory.
Table: GC Benefits
| Benefit | Description |
|---|---|
| Automatic | No manual memory management |
| Memory leak prevention | Removes unreferenced objects |
| Performance | Optimizes memory usage |
| Safety | Prevents memory errors |
Diagram:
goat
- When occurs: When heap memory is low or System.gc() called
- Process: Mark and Sweep algorithm
- Cannot guarantee: Exact timing of garbage collection
Mnemonic: "GC Automatic Memory Cleanup"
Question 4(b OR) [4 marks]
Write a Java program to handle user defined exception for 'Divide by Zero' error.
Answer:
Code Block:
Java
Output:
Error: Cannot divide by zero!
Steps:
- Create custom exception class extending Exception
- Throw exception when condition occurs
- Handle exception with try-catch block
Mnemonic: "Custom Exception Handle Error"
Question 4(c OR) [7 marks]
Write a java program to demonstrate multiple try block and multiple catch block exception.
Answer:
Code Block:
Java
Output:
Array index error: Index 5 out of bounds for length 3
Null pointer error: null
Arithmetic error: / by zero
Program completed
Features demonstrated:
- Multiple try blocks: Each handles different operations
- Multiple catch blocks: Each handles specific exception type
- Exception hierarchy: General Exception catches all
- Finally block: Always executes
Mnemonic: "Multiple Try Multiple Catch"
Question 5(a) [3 marks]
Write a program in Java to create a file and perform write operation on this file.
Answer:
Code Block:
Java
Steps:
- Import java.io package
- Create File object with filename
- Create FileWriter object
- Write data using write() method
- Close writer to save changes
Mnemonic: "File Writer Write Close"
Question 5(b) [4 marks]
Explain throw and finally in Exception Handling with example.
Answer:
Throw: Keyword used to explicitly throw an exception. Finally: Block that always executes regardless of exception occurrence.
Table: Throw vs Finally
| Keyword | Purpose | Usage |
|---|---|---|
| throw | Explicitly throw exception | throw new Exception() |
| finally | Always execute cleanup code | finally |
Code Block:
Java
Output:
Error: Age must be 18 or above
Finally block always executes
- Throw: Forces exception to occur
- Finally: Cleanup code, closes resources
Mnemonic: "Throw Exception, Finally Always"
Question 5(c) [7 marks]
Describe: Polymorphism. Explain run time polymorphism with suitable example in java.
Answer:
Polymorphism: One interface, multiple implementations. Object behaves differently based on its actual type.
Table: Polymorphism Types
| Type | Description | When Decided |
|---|---|---|
| Compile-time | Method overloading | At compilation |
| Run-time | Method overriding | At execution |
Run-time Polymorphism: Method call resolved at runtime based on actual object type.
Diagram:
Code Block:
Java
Output:
Dog barks
Cat meows
Dog barks
Cat meows
Dog barks
Features:
- Dynamic Method Dispatch: JVM decides which method to call at runtime
- Upcasting: Child object referenced by parent reference
- Flexibility: Same code works with different object types
Mnemonic: "Polymorphism Many Forms Runtime"
Question 5(a OR) [3 marks]
Write a program in Java that read the content of a file byte by byte and copy it into another file.
Answer:
Code Block:
Java
Steps:
- Create FileInputStream for reading
- Create FileOutputStream for writing
- Read byte by byte using read()
- Write each byte using write()
- Close both streams
Mnemonic: "Read Byte Write Byte"
Question 5(b OR) [4 marks]
Explain the different I/O Classes available with Java.
Answer:
Table: Java I/O Classes
| Class Type | Class Name | Purpose |
|---|---|---|
| Byte Stream | FileInputStream | Read bytes from file |
| Byte Stream | FileOutputStream | Write bytes to file |
| Character Stream | FileReader | Read characters from file |
| Character Stream | FileWriter | Write characters to file |
| Buffered | BufferedReader | Efficient character reading |
| Buffered | BufferedWriter | Efficient character writing |
Diagram: I/O Class Hierarchy
goat
Code Example:
Java
Mnemonic: "Byte Character Buffered Streams"
Question 5(c OR) [7 marks]
Write a java program that executes two threads. One thread displays "Java Programming" every 3 seconds, and the other displays "Semester - 4th IT" every 6 seconds.(Create the threads by extending the Thread class)
Answer:
Code Block:
Java
Sample Output:
Java Programming
Semester - 4th IT
Java Programming
Java Programming
Semester - 4th IT
Java Programming
Java Programming
Semester - 4th IT
...
Features:
- Two separate threads: Each with different timing
- Thread.sleep(): Pauses execution for specified milliseconds
- Concurrent execution: Both threads run simultaneously
- Extending Thread class: Override run() method
Execution Pattern:
- JavaThread: Displays every 3 seconds
- SemesterThread: Displays every 6 seconds
- Both run concurrently showing different timing
Mnemonic: "Two Threads Different Timing"