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:

AspectPOPOOP
FocusFunctions/ProceduresObjects and Classes
Data SecurityLess secure, global dataMore secure, data encapsulation
Problem SolvingTop-down approachBottom-up approach
Code ReusabilityLimitedHigh through inheritance
ExamplesC, PascalJava, 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

UsePurposeExample
super()Call parent constructorsuper(name, age)
super.method()Call parent methodsuper.display()
super.variableAccess parent variablesuper.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

RuleDescription
Same nameMethod name must be identical
Same parametersParameter list must match exactly
IS-A relationshipMust have inheritance
Access modifierCannot reduce visibility
Return typeMust 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

FeatureDescription
Abstract methodsNo implementation (before Java 8)
ConstantsAll variables are public static final
Multiple inheritanceClass can implement multiple interfaces
Default methodsConcrete 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

TypeDescriptionExample
Static variableShared by all objectsstatic int count
Static methodCalled without objectstatic void display()
Static blockExecutes before mainstatic

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

TypeDescriptionExample
DefaultNo parametersStudent()
ParameterizedWith parametersStudent(String name)
CopyCreates copy of objectStudent(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

CategoryTypesSizeExample
Primitivebyte, short, int, long1,2,4,8 bytesint x = 10;
Primitivefloat, double4,8 bytesdouble d = 3.14;
Primitivechar, boolean2,1 byteschar c = 'A';
User DefinedClass, Interface, ArrayVariableStudent 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

UsePurposeExample
this.variableAccess instance variablethis.name = name;
this.method()Call instance methodthis.display();
this()Call constructorthis(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

TypeDescriptionStructure
SingleOne parent, one childA → B
MultilevelChain of inheritanceA → B → C
HierarchicalOne parent, multiple childrenA → B, A → C
MultipleMultiple 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

TypeDescriptionExample
Implicit (Widening)Automatic, smaller to largerint to double
Explicit (Narrowing)Manual, larger to smallerdouble 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

ModifierSame ClassSame PackageSubclassDifferent 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

MethodDescriptionExample
Extending ThreadInherit Thread classclass MyThread extends Thread
Implementing RunnableImplement Runnable interfaceclass MyTask implements Runnable

Diagram: Thread Life Cycle

Table: Thread States

StateDescription
NEWThread created but not started
RUNNABLEReady to run, waiting for CPU
RUNNINGCurrently executing
BLOCKEDWaiting for resource or sleep
TERMINATEDExecution 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

ComponentPurpose
Class LoaderLoads .class files into memory
Execution EngineExecutes bytecode
Memory AreaManages heap and stack memory
Garbage CollectorAutomatic 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

BenefitDescription
NamespaceAvoid name conflicts
Access ControlBetter encapsulation
OrganizationLogical grouping
ReusabilityEasy to maintain

Steps to create Package:

  1. Declare package at top of file
  2. Create directory structure matching package name
  3. Compile with package structure
  4. 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

TypeDescriptionUsage
Synchronized methodEntire method lockedsynchronized void method()
Synchronized blockSpecific code block lockedsynchronized(object)
Static synchronizationClass level lockingsynchronized 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

AspectStringStringBuffer
MutabilityImmutable (cannot change)Mutable (can change)
PerformanceSlower for concatenationFaster for concatenation
MemoryCreates new object each timeModifies existing object
Thread SafetyThread safeThread safe
Methodsconcat(), 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:

  1. Initialize array with 10 numbers
  2. Loop through array to calculate sum
  3. Calculate average = sum / length
  4. 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

FeatureDescription
Cannot instantiateNo object creation
Abstract methodsMethods without implementation
Concrete methodsMethods with implementation
InheritanceSubclasses must implement abstract methods

Code Block - Abstract Class:

Java

II) Final Class: Class that cannot be extended (no inheritance allowed).

Table: Final Class Features

FeatureDescription
No inheritanceCannot be extended
SecurityPrevents modification
PerformanceBetter optimization
ExamplesString, 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

BenefitDescription
AutomaticNo manual memory management
Memory leak preventionRemoves unreferenced objects
PerformanceOptimizes memory usage
SafetyPrevents 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:

  1. Create custom exception class extending Exception
  2. Throw exception when condition occurs
  3. 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:

  1. Import java.io package
  2. Create File object with filename
  3. Create FileWriter object
  4. Write data using write() method
  5. 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

KeywordPurposeUsage
throwExplicitly throw exceptionthrow new Exception()
finallyAlways execute cleanup codefinally

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

TypeDescriptionWhen Decided
Compile-timeMethod overloadingAt compilation
Run-timeMethod overridingAt 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:

  1. Create FileInputStream for reading
  2. Create FileOutputStream for writing
  3. Read byte by byte using read()
  4. Write each byte using write()
  5. 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 TypeClass NamePurpose
Byte StreamFileInputStreamRead bytes from file
Byte StreamFileOutputStreamWrite bytes to file
Character StreamFileReaderRead characters from file
Character StreamFileWriterWrite characters to file
BufferedBufferedReaderEfficient character reading
BufferedBufferedWriterEfficient 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"