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:

ComponentDescription
Package declarationOptional, defines package membership
Import statementsImports required classes/packages
Class declarationDefines the main class
Main methodEntry 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:

FeatureDescription
Platform IndependentWrite once, run anywhere
Object OrientedEverything is an object
SimpleEasy syntax, no pointers
SecureBuilt-in security features
RobustStrong memory management
MultithreadedConcurrent 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:

StepOperationExample (123)
1Extract last digit (n%10)123%10 = 3
2Add to sumsum = 0+3 = 3
3Remove last digit (n/10)123/10 = 12
4Repeat until n=0Continue
  • 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:

StepActionDetails
1Check argsEnsure 10 numbers provided
2Initialize maxFirst number as initial max
3Compare loopCheck each remaining number
4Update maxIf 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:

ConceptDescription
EncapsulationData hiding and bundling
InheritanceCode reuse from parent class
PolymorphismOne interface, many forms
AbstractionHiding 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:

ComponentFunction
Class LoaderLoads .class files into memory
Memory AreasHeap, Stack, Method area
Execution EngineExecutes bytecode
JIT CompilerOptimizes 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:

ConstructorParametersUse Case
DefaultNoneBasic object creation
Single paramName onlyPartial initialization
Two paramName, AgeMore specific data
Full paramAll fieldsComplete 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:

PrimitiveWrapper Class
byteByte
intInteger
floatFloat
doubleDouble
charCharacter
booleanBoolean

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:

FeatureCharacteristics
Static VariableShared among all instances
Static MethodCalled without object creation
Static BlockExecuted once when class loads
MemoryStored 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:

TypePurposeParameters
DefaultBasic initializationNone
ParameterizedCustom initializationUser-defined
CopyClone existing objectSame 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:

FunctionPurposeExample
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:

TypeDescription
SingleOne parent, one child
MultilevelChain of inheritance
HierarchicalOne parent, multiple children
MultipleMultiple 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:

FeatureInterfaceClass
MethodsAbstract (default/static allowed)Concrete
Variablespublic static finalAny type
InheritanceMultiple allowedSingle only
InstantiationCannot create objectsCan 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 CasePurpose
Instance variableDifferentiate from parameter
Method callCall another method of same class
Constructor callCall another constructor
Return objectReturn 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:

RuleDescription
Same signatureMethod name, parameters must match
InheritanceMust be in parent-child relationship
@OverrideAnnotation for compiler checking
Runtime decisionMethod 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:

StepActionCommand/Code
1Create directorymkdir com/company/utils
2Add package declarationpackage com.company.utils;
3Write classpublic class MathUtils
4Compilejavac -d . MathUtils.java
5Import and useimport 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:

BenefitDescription
OrganizationLogical grouping of classes
NamespaceAvoid naming conflicts
Access controlPackage-private access
MaintenanceEasier code management

Mnemonic: "ONAM - Organization, Namespace, Access, Maintenance"

Question 4(a) [3 marks]

Explain thread priorities with suitable example.

Answer:

Thread Priority Table:

Priority LevelConstantValue
MinimumMIN_PRIORITY1
NormalNORM_PRIORITY5
MaximumMAX_PRIORITY10

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:

StateDescription
NEWThread created but not started
RUNNABLEReady to run, waiting for CPU
RUNNINGCurrently executing
BLOCKED/WAITINGWaiting for resource/condition
TERMINATEDExecution 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:

StepAction
1Extend Thread class
2Override run() method
3Create thread objects
4Call 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:

ConceptDescription
ExceptionRuntime error that disrupts normal flow
try blockCode that might throw exception
catch blockHandles specific exception types
finally blockAlways 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:

RuleDescription
Specific firstHandle specific exceptions before general
One catch executesOnly first matching catch runs
Order mattersMore specific to more general
finally alwaysfinally 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:

TypeDescriptionExample
CheckedMust be handled at compile timeIOException
UncheckedRuntime exceptionsArithmeticException
ErrorSystem-level problemsOutOfMemoryError

ArithmeticException Causes:

  • Division by zero: Most common cause
  • Modulo by zero: Remainder operation with zero
  • Invalid operations: Mathematical impossibilities

Program Flow:

  1. Normal execution: Try block runs
  2. Exception occurs: ArithmeticException thrown
  3. Exception caught: Catch block handles it
  4. Cleanup: Finally block executes
  5. 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:

CauseDescriptionExample
Negative indexIndex less than 0arr[-1]
Index >= lengthIndex beyond array sizearr[5] for size 3
Empty arrayAccess on zero-length arrayarr[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 TypePurposeClasses
Byte StreamsHandle binary dataInputStream, OutputStream
Character StreamsHandle text dataReader, Writer
Buffered StreamsImprove performanceBufferedReader, BufferedWriter
File StreamsFile operationsFileInputStream, 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:

MethodPerformanceResource ManagementUse Case
FileWriterBasicManual close()Simple writes
BufferedWriterHighManual close()Large data
Try-with-resourcesHighAutomaticRecommended

Write Operation Steps:

  1. Create writer object: FileWriter or BufferedWriter
  2. Write data: Use write() method
  3. Close stream: Release resources
  4. 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:

OperationResultException
Integer divisionUndefinedArithmeticException
Float divisionInfinityNo exception
Modulo by zeroUndefinedArithmeticException

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:

BlockPurposeExecution
tryContains risky codeAlways executed first
catchHandles exceptionsOnly if exception occurs
finallyCleanup codeAlways 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:

OperationMethodPurpose
CreateFileWriter(filename)Create new file
ReadBufferedReader.readLine()Read file content
AppendFileWriter(filename, true)Add to existing file
DisplaySystem.out.println()Show content

File Operations Flow:

  1. Create initial file: Write initial content
  2. Display content: Read and show current content
  3. Append data: Add new information
  4. Display updated: Show modified content
  5. 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"