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 ConceptsDescription
ClassBlueprint for objects
ObjectInstance of a class
EncapsulationData hiding mechanism
InheritanceAcquiring properties from parent
PolymorphismOne interface, multiple forms
AbstractionHiding 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:

PrimitiveWrapper Class
intInteger
charCharacter
booleanBoolean
doubleDouble

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 FeaturesDescription
Platform IndependentWrite once, run anywhere
Object OrientedEverything is an object
SimpleEasy syntax, no pointers
SecureBytecode verification
RobustStrong memory management
MultithreadedConcurrent 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:

UsageDescriptionExample
final variableCannot be changedfinal int x = 10;
final methodCannot be overriddenfinal void display()
final classCannot be inheritedfinal 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 TypesDescription
SingleOne parent, one child
MultilevelChain of inheritance
HierarchicalOne parent, multiple children
MultipleMultiple 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 ModifierSame ClassSame PackageSubclassDifferent 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:

  1. Use package statement at top of file
  2. Create directory structure matching package name
  3. Compile with -d option
  4. 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 ExceptionsDescription
NullPointerExceptionNull reference access
ArrayIndexOutOfBoundsExceptionInvalid array index
NumberFormatExceptionInvalid number format
ClassCastExceptionInvalid 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 TypePurposeBase Classes
Byte StreamsBinary dataInputStream, OutputStream
Character StreamsText dataReader, 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.

ComponentPurpose
SourceData origin (file, keyboard, network)
StreamData pathway (byte/character streams)
DestinationData target (file, screen, network)

Process Steps:

  1. Open Stream: Create connection to source/destination
  2. Process Data: Read/write operations
  3. 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)