Object Oriented Programming with Java (4341602) - Winter 2023 Solution
Solution guide for Object Oriented Programming with Java (4341602) Winter 2023 exam
Question 1(a) [3 marks]
List out basic concepts of oop. Explain any one in detail.
Answer:
| Basic OOP Concepts | Description |
|---|---|
| Class | Blueprint for objects |
| Object | Instance of a class |
| Encapsulation | Data hiding mechanism |
| Inheritance | Acquiring properties from parent |
| Polymorphism | One interface, multiple forms |
| Abstraction | Hiding implementation details |
Encapsulation is the process of binding data and methods together within a class and hiding internal implementation from outside world. It provides data security by making variables private and accessing them through public methods.
Mnemonic: "CEO-IPA" (Class, Encapsulation, Object, Inheritance, Polymorphism, Abstraction)
Question 1(b) [4 marks]
Explain JVM in detail.
Answer:
JVM (Java Virtual Machine) is a runtime environment that executes Java bytecode. It provides platform independence by converting bytecode to machine-specific code.
- Class Loader: Loads class files into memory
- Memory Management: Handles heap and stack memory
- Execution Engine: Executes bytecode instructions
- Garbage Collector: Automatically manages memory
Mnemonic: "CMEG" (Class loader, Memory, Execution, Garbage collection)
Question 1(c) [7 marks]
Write a program in java to print Fibonacci series for n terms.
Answer:
Java
- Logic: Start with 0,1 and add previous two numbers
- Loop: Continues for n terms
- Variables: first, second, next for calculation
Mnemonic: "FSN" (First, Second, Next)
Question 1(c OR) [7 marks]
Write a program in java to find out minimum from any ten numbers using command line argument.
Answer:
Java
- Command Line: java FindMinimum 5 3 8 1 9 2 7 4 6 0
- Logic: Compare each number with current minimum
- Method: Integer.parseInt() converts string to integer
Mnemonic: "CIM" (Check, Integer.parseInt, Minimum)
Question 2(a) [3 marks]
What is wrapper class? Explain with example.
Answer:
| Primitive | Wrapper Class |
|---|---|
| int | Integer |
| char | Character |
| boolean | Boolean |
| double | Double |
Wrapper classes convert primitive data types into objects. They provide utility methods and enable primitives to be used in collections.
Example: Integer obj = new Integer(25); or Integer obj = 25; (autoboxing)
Mnemonic: "POC" (Primitive to Object Conversion)
Question 2(b) [4 marks]
List out different features of java. Explain any two.
Answer:
| Java Features | Description |
|---|---|
| Platform Independent | Write once, run anywhere |
| Object Oriented | Everything is an object |
| Simple | Easy syntax, no pointers |
| Secure | Bytecode verification |
| Robust | Strong memory management |
| Multithreaded | Concurrent execution |
Platform Independence: Java source code compiles to bytecode which runs on any platform with JVM installed.
Object Oriented: Java follows OOP principles like encapsulation, inheritance, and polymorphism for better code organization.
Mnemonic: "POSSMR" (Platform, Object, Simple, Secure, Multithreaded, Robust)
Question 2(c) [7 marks]
What is method overload? Explain with example.
Answer:
Method Overloading allows multiple methods with same name but different parameters in the same class.
Java
- Rules: Different parameter types or number of parameters
- Compile Time: Decision made during compilation
- Return Type: Cannot be only difference
Mnemonic: "SNRT" (Same Name, different paRameters, compile Time)
Question 2(a OR) [3 marks]
Explain Garbage collection in java.
Answer:
goat
Garbage Collection automatically deallocates memory of unreferenced objects. JVM runs garbage collector periodically to free up heap memory.
- Automatic: No manual memory management needed
- Mark and Sweep: Marks unreferenced objects, then removes them
Mnemonic: "ARMS" (Automatic Reference Management System)
Question 2(b OR) [4 marks]
Explain final keyword with example.
Answer:
| Usage | Description | Example |
|---|---|---|
| final variable | Cannot be changed | final int x = 10; |
| final method | Cannot be overridden | final void display() |
| final class | Cannot be inherited | final class MyClass |
Example:
Java
Mnemonic: "VCM" (Variable constant, Class not inherited, Method not overridden)
Question 2(c OR) [7 marks]
What is constructor? Explain parameterized constructor with example.
Answer:
Constructor is a special method that initializes objects when created. It has same name as class and no return type.
Java
- Purpose: Initialize object with specific values
- Parameters: Accepts arguments to set initial state
- Automatic: Called automatically when object is created
Mnemonic: "SPA" (Same name, Parameters, Automatic call)
Question 3(a) [3 marks]
Explain super keyword with example.
Answer:
super keyword refers to parent class members and constructor. It resolves naming conflicts between parent and child classes.
Java
- super.variable: Access parent class variable
- super.method(): Call parent class method
- super(): Call parent class constructor
Mnemonic: "VMC" (Variable, Method, Constructor)
Question 3(b) [4 marks]
List out different types of inheritance. Explain multilevel inheritance.
Answer:
| Inheritance Types | Description |
|---|---|
| Single | One parent, one child |
| Multilevel | Chain of inheritance |
| Hierarchical | One parent, multiple children |
| Multiple | Multiple parents (via interfaces) |
Multilevel Inheritance: Class inherits from another class which itself inherits from another class, forming a chain.
Java
Mnemonic: "SMHM" (Single, Multilevel, Hierarchical, Multiple)
Question 3(c) [7 marks]
What is interface? Explain multiple inheritance with example.
Answer:
Interface is a contract that defines what methods a class must implement. It contains only abstract methods and constants.
Java
Multiple Inheritance: A class can implement multiple interfaces, achieving multiple inheritance of behavior.
- Abstract Methods: All methods are abstract by default
- Constants: All variables are public, static, final
- implements: Keyword to implement interface
Mnemonic: "ACI" (Abstract methods, Constants, implements keyword)
Question 3(a OR) [3 marks]
Explain static keyword with example.
Answer:
static keyword creates class-level members that belong to class rather than instances. Memory allocated once when class loads.
Java
- static variable: Shared among all objects
- static method: Called without object creation
- Memory: Allocated in method area
Mnemonic: "SOM" (Shared, Object not needed, Method area)
Question 3(b OR) [4 marks]
Explain different access controls in Java.
Answer:
| Access Modifier | Same Class | Same Package | Subclass | Different Package |
|---|---|---|---|---|
| private | ✓ | ✗ | ✗ | ✗ |
| default | ✓ | ✓ | ✗ | ✗ |
| protected | ✓ | ✓ | ✓ | ✗ |
| public | ✓ | ✓ | ✓ | ✓ |
Access Control determines visibility and accessibility of classes, methods, and variables.
Mnemonic: "PriDef ProPub" (Private, Default, Protected, Public)
Question 3(c OR) [7 marks]
What is package? Write steps to create a package and give example of it.
Answer:
Package is a namespace that organizes related classes and interfaces. It provides access protection and namespace management.
Steps to create package:
- Use
packagestatement at top of file - Create directory structure matching package name
- Compile with
-doption - Import package in other files
Java
Compilation: javac -d . MyClass.java
Mnemonic: "PDCI" (Package statement, Directory, Compile, Import)
Question 4(a) [3 marks]
Explain thread priorities with suitable example.
Answer:
Thread Priority determines execution order of threads. Java provides 10 priority levels from 1 (lowest) to 10 (highest).
Java
Priority Constants: MIN_PRIORITY (1), NORM_PRIORITY (5), MAX_PRIORITY (10)
Mnemonic: "MNM" (MIN, NORM, MAX)
Question 4(b) [4 marks]
What is Thread? Explain Thread life cycle.
Answer:
Thread is a lightweight subprocess that enables concurrent execution within a program.
Thread Life Cycle States:
- New: Thread created but not started
- Runnable: Ready to run, waiting for CPU
- Running: Currently executing
- Blocked: Waiting for resource or I/O
- Dead: Thread execution completed
Mnemonic: "NRRBD" (New, Runnable, Running, Blocked, Dead)
Question 4(c) [7 marks]
Write a program in java that create the multiple threads by implementing the Thread class.
Answer:
Java
- extends Thread: Inherit Thread class functionality
- Override run(): Define thread execution logic
- start(): Begin thread execution
Mnemonic: "EOS" (Extends, Override run, Start method)
Question 4(a OR) [3 marks]
List four different inbuilt exceptions. Explain any one inbuilt exception.
Answer:
| Inbuilt Exceptions | Description |
|---|---|
| NullPointerException | Null reference access |
| ArrayIndexOutOfBoundsException | Invalid array index |
| NumberFormatException | Invalid number format |
| ClassCastException | Invalid type casting |
NullPointerException occurs when trying to access methods or variables of a null reference.
Java
Mnemonic: "NANC" (NullPointer, ArrayIndex, NumberFormat, ClassCast)
Question 4(b OR) [4 marks]
Explain multiple catch with suitable example.
Answer:
Multiple catch blocks handle different types of exceptions that might occur in try block. Each catch handles specific exception type.
Java
Order: Specific exceptions first, general exceptions last
Mnemonic: "SGO" (Specific first, General last, Ordered)
Question 4(c OR) [7 marks]
What is Exception? Write a program that show the use of Arithmetic Exception.
Answer:
Exception is an abnormal condition that disrupts normal program flow. It's an object representing an error condition.
Java
ArithmeticException thrown when mathematical error occurs like division by zero.
Exception Hierarchy: Object → Throwable → Exception → RuntimeException → ArithmeticException
Mnemonic: "OTERRA" (Object, Throwable, Exception, RuntimeException, ArithmeticException)
Question 5(a) [3 marks]
Explain ArrayIndexOutOfBound Exception in Java with example.
Answer:
ArrayIndexOutOfBoundsException occurs when accessing array element with invalid index (negative or >= array length).
Java
- Valid Range: 0 to (length-1)
- Runtime Exception: Unchecked exception
- Common Cause: Loop condition errors
Mnemonic: "VRC" (Valid range, Runtime exception, Common in loops)
Question 5(b) [4 marks]
Explain basics of stream classes.
Answer:
Stream Classes provide input/output operations for reading and writing data.
| Stream Type | Purpose | Base Classes |
|---|---|---|
| Byte Streams | Binary data | InputStream, OutputStream |
| Character Streams | Text data | Reader, Writer |
- Input Streams: Read data from source
- Output Streams: Write data to destination
- Buffered Streams: Improve performance with buffering
Mnemonic: "BIOC" (Byte, Input/Output, Character streams)
Question 5(c) [7 marks]
Write a java program to create a text file and perform read operation on the text file.
Answer:
Java
- FileWriter: Creates and writes to text file
- FileReader: Reads from text file
- BufferedReader: Efficient line-by-line reading
Mnemonic: "WRB" (Writer creates, Reader reads, Buffered for efficiency)
Question 5(a OR) [3 marks]
Explain Divide by Zero Exception in Java with example.
Answer:
ArithmeticException (Divide by Zero) occurs when integer is divided by zero. Floating-point division by zero returns Infinity.
Java
- Integer Division: Throws ArithmeticException
- Float Division: Returns Infinity or NaN
Mnemonic: "IFI" (Integer throws exception, Float returns Infinity)
Question 5(b OR) [4 marks]
Explain java I/O process.
Answer:
goat
Java I/O Process handles data transfer between program and external sources using streams.
| Component | Purpose |
|---|---|
| Source | Data origin (file, keyboard, network) |
| Stream | Data pathway (byte/character streams) |
| Destination | Data target (file, screen, network) |
Process Steps:
- Open Stream: Create connection to source/destination
- Process Data: Read/write operations
- Close Stream: Release resources
Mnemonic: "OPC" (Open, Process, Close)
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
- FileWriter(filename, true): Append mode enabled
- displayFileContent(): Reusable method for reading
- BufferedReader: Efficient line reading
Mnemonic: "ARB" (Append mode, Reusable method, Buffered reading)