Java Programming (4343203) - Summer 2024 Solution

Solution guide for Java Programming (4343203) Summer 2024 exam

Question 1(a) [3 marks]

Explain Garbage collection in java.

Answer: Garbage collection in Java automatically reclaims memory by removing unused objects.

Garbage Collection Concept

Table: Garbage Collection Process

PhaseDescription
MarkJVM identifies all live objects in memory
SweepUnused objects are removed
CompactRemaining objects are reorganized to free up space
  • Automatic: No manual memory management required
  • Background: Runs in separate low-priority thread

Mnemonic: "MSC: Mark-Sweep-Compact frees memory automatically"

Question 1(b) [4 marks]

Explain JVM in detail.

Answer: JVM (Java Virtual Machine) is a virtual machine that enables Java's platform independence by converting bytecode to machine code.

Diagram: JVM Architecture

JVM Architecture

  • Platform Independence: Write once, run anywhere
  • Security: Bytecode verification prevents dangerous operations
  • Optimization: Just-in-time compilation improves performance

Mnemonic: "CLASS: Class Loader Leads All System Security"

Question 1(c) [7 marks]

Write a program in java to print Fibonacci series for N terms.

Answer: Fibonacci series generates numbers where each is the sum of the two preceding ones.

Code Block:

Java
  • Initialize: Start with 0 and 1
  • Loop: Iterate N times to generate sequence
  • Calculation: Each number is sum of previous two

Mnemonic: "FSN: First + Second = Next number in sequence"

Question 1(c OR) [7 marks]

Write a program in java to find out minimum from any ten numbers using command line argument.

Answer: Command line arguments allow passing input values directly when executing a Java program.

Code Block:

Java
  • Parse Arguments: Convert string arguments to integers
  • Initialize: Set first number as minimum
  • Compare: Check each number against current minimum

Mnemonic: "ICU: Initialize, Compare, Update the minimum"

Question 2(a) [3 marks]

List out basic concepts of Java OOP. Explain any one in details.

Answer: Java Object-Oriented Programming is built on fundamental concepts for modeling real-world entities.

OOP Concepts

Table: OOP Concepts in Java

ConceptDescription
EncapsulationBinding data and methods together as a single unit
InheritanceCreating new classes from existing ones
PolymorphismOne interface, multiple implementations
AbstractionHiding implementation details, showing functionality
  • Encapsulation: Protects data through access control
  • Data Hiding: Private variables accessible through methods

Mnemonic: "PEAI: Programming Encapsulates Abstracts Inherits"

Question 2(b) [4 marks]

Explain final keyword with example.

Answer: The final keyword in Java restricts modification and creates constants, unchangeable methods, and non-inheritable classes.

Table: Uses of final Keyword

UsageEffectExample
final variableCannot be changedfinal int MAX = 100;
final methodCannot be overriddenfinal void display() {}
final classCannot be extendedfinal class Math {}

Code Block:

Java

Mnemonic: "VCM: Variables Constants Methods can't change"

Question 2(c) [7 marks]

What is constructor? Explain parameterized constructor with example.

Answer: A constructor initializes objects when created, with the same name as its class and no return type.

Diagram: Constructor Types

Constructor Types

Code Block:

Java
  • Parameters: Accept values during object creation
  • Initialization: Set object properties with passed values
  • Overloading: Multiple constructors with different parameters

Mnemonic: "SPO: Student Parameters Object initializes properties"

Question 2(a OR) [3 marks]

Explain the Java Program Structure with example.

Answer: Java program structure follows a specific hierarchy of elements organized logically.

Diagram: Java Program Structure

Java Program Structure

  • Package: Groups related classes
  • Import: Includes external classes
  • Class: Contains variables and methods

Mnemonic: "PIC: Package Imports Class in every program"

Question 2(b OR) [4 marks]

Explain static keyword with suitable example.

Answer: Static keyword creates class-level variables and methods shared by all objects, accessible without creating instances.

Static Keyword Metaphor

Table: Static vs Non-Static

FeatureStaticNon-Static
MemorySingle copyMultiple copies
AccessWithout objectThrough object
ReferenceClass nameObject name
When loadedClass loadingObject creation

Code Block:

Java

Mnemonic: "SCM: Static Creates Memory once for all objects"

Question 2(c OR) [7 marks]

Define Inheritance. List out types of it. Explain multilevel and hierarchical inheritance with suitable example.

Answer: Inheritance is an OOP principle where a new class acquires properties and behaviors from an existing class.

Table: Types of Inheritance in Java

TypeDescription
SingleOne subclass extends one superclass
MultilevelChain of inheritance (A→B→C)
HierarchicalMultiple subclasses extend one superclass
MultipleOne class extends multiple classes (via interfaces)

Diagram: Multilevel vs Hierarchical Inheritance

Inheritance Types

Code Block:

Java

Mnemonic: "SMHM: Single Multilevel Hierarchical Makes inheritance types"

Question 3(a) [3 marks]

Explain this keyword with suitable example.

Answer: The 'this' keyword in Java refers to the current object, used to differentiate between instance variables and parameters.

This Keyword Metaphor

Table: Uses of 'this' Keyword

UsePurpose
this.variableAccess instance variables
this()Call current class constructor
return thisReturn current object

Code Block:

Java

Mnemonic: "VAR: Variables Access Resolution using this"

Question 3(b) [4 marks]

Explain different access controls in Java.

Answer: Access controls in Java regulate visibility and accessibility of classes, methods, and variables.

Table: Java Access Modifiers

ModifierClassPackageSubclassWorld
private
default
protected
public
  • Private: Only within the same class
  • Default: Within the same package
  • Protected: Within package and subclasses
  • Public: Accessible everywhere

Mnemonic: "PDPP: Private Default Protected Public from narrow to wide"

Question 3(c) [7 marks]

What is interface? Explain multiple inheritance using interface with example.

Answer: An interface is a contract that specifies what a class must do, containing abstract methods, constants, and (since Java 8) default methods.

Diagram: Multiple Inheritance with Interfaces

Multiple Inheritance

Code Block:

Java
  • Contract: Defines behavior without implementation
  • Implements: Classes fulfill the contract
  • Multiple: Can implement many interfaces

Mnemonic: "CIM: Contract Implements Multiple interfaces"

Question 3(a OR) [3 marks]

Explain super keyword with example.

Answer: The super keyword refers to the parent class, used to access parent methods, constructors, and variables.

Table: Uses of super Keyword

UsePurpose
super.variableAccess parent variable
super.method()Call parent method
super()Call parent constructor

Code Block:

Java

Mnemonic: "VMC: Variables Methods Constructors accessed by super"

Question 3(b OR) [4 marks]

What is package? Write steps to create a package and give example of it.

Answer: A package in Java is a namespace that organizes related classes and interfaces, preventing naming conflicts.

Table: Steps to Create a Package

StepAction
1Declare package name at top of file
2Create directory structure matching package name
3Save Java file in the directory
4Compile with -d option
5Import package to use it

Code Block:

Java

Mnemonic: "DISCO: Declare Import Save Compile Organize"

Question 3(c OR) [7 marks]

Define: Method Overriding. List out Rules for method overriding. Write a java program that implements method overriding.

Answer: Method overriding occurs when a subclass provides a specific implementation for a method already defined in its parent class.

Method Overriding Metaphor

Table: Rules for Method Overriding

RuleDescription
Same nameMethod must have same name
Same parametersParameter count and type must match
Same return typeReturn type must be same or subtype (covariant)
Access modifierCan't be more restrictive
ExceptionsCan't throw broader checked exceptions

Code Block:

Java
  • Runtime Polymorphism: Method resolution at runtime
  • @Override: Annotation ensures method is overriding
  • Inheritance: Requires IS-A relationship

Mnemonic: "SPARE: Same Parameters Access Return Exceptions"

Question 4(a) [3 marks]

Explain abstract class with suitable example.

Answer: An abstract class cannot be instantiated and may contain abstract methods that must be implemented by subclasses.

Abstract Class Blueprint

Table: Abstract Class vs Interface

FeatureAbstract ClassInterface
InstantiationCannotCannot
MethodsConcrete and abstractAbstract (+ default since Java 8)
VariablesAny typeOnly constants
ConstructorHasDoesn't have

Code Block:

Java

Mnemonic: "PAI: Partial Abstract Implementation is key"

Question 4(b) [4 marks]

What is Thread? Explain Thread life cycle.

Answer: A thread is a lightweight subprocess, the smallest unit of processing that allows concurrent execution.

Diagram: Thread Life Cycle

Thread Life Cycle

  • New: Thread created but not started
  • Runnable: Ready to run when CPU time is given
  • Running: Currently executing
  • Blocked/Waiting: Temporarily inactive
  • Terminated: Completed execution

Mnemonic: "NRRBT: New Runnable Running Blocked Terminated"

Question 4(c) [7 marks]

Write a program in java that creates the multiple threads by implementing the Thread class.

Answer: Creating threads by implementing Thread class allows multiple tasks to execute concurrently.

Code Block:

Java
  • Extend Thread: Create thread by extending Thread class
  • Override run(): Define task in run method
  • start(): Begin thread execution

Mnemonic: "ERS: Extend Run Start to create threads"

Question 4(a OR) [3 marks]

Explain final class with suitable example.

Answer: A final class cannot be extended, preventing inheritance and modification of its design.

Table: Final Class Characteristics

FeatureDescription
InheritanceCannot be subclassed
MethodsImplicitly final
SecurityPrevents design alteration
ExampleString, Math classes

Code Block:

Java
  • Security: Protects sensitive implementations
  • Immutability: Helps create immutable classes
  • Optimization: JVM can optimize final classes

Mnemonic: "SIO: Security Immutability Optimization"

Question 4(b OR) [4 marks]

Explain thread priorities with suitable example.

Answer: Thread priorities determine the order in which threads are scheduled for execution, from 1 (lowest) to 10 (highest).

Table: Thread Priority Constants

ConstantValueDescription
MIN_PRIORITY1Lowest priority
NORM_PRIORITY5Default priority
MAX_PRIORITY10Highest priority

Code Block:

Java

Mnemonic: "HNL: High Normal Low priorities in threads"

Question 4(c OR) [7 marks]

What is Exception? Write a program that shows the use of Arithmetic Exception.

Answer: An exception is an abnormal condition that disrupts the normal flow of program execution.

Diagram: Exception Hierarchy

Exception Hierarchy

Code Block:

Java
  • Try Block: Contains code that might throw exceptions
  • Catch Block: Handles the specific exception
  • Finally Block: Always executes regardless of exception

Mnemonic: "TCF: Try Catch Finally handles exceptions"

Question 5(a) [3 marks]

Write a Java Program to find sum and average of 10 numbers of an array.

Answer: Arrays store multiple values of the same type, enabling sequential processing of elements.

Java Arrays Concept

Code Block:

Java
  • Declaration: Creates fixed-size collection
  • Iteration: Sequential access to elements
  • Calculation: Process values for results

Mnemonic: "DIC: Declare Iterate Calculate for array processing"

Question 5(b) [4 marks]

Write a Java program to handle user defined exception for 'Divide by Zero' error.

Answer: User-defined exceptions allow creating custom exception types for specific application requirements.

Code Block:

Java
  • Custom Class: Extends Exception class
  • Throwing: Use throw keyword with new instance
  • Handling: Catch specific exception type

Mnemonic: "CTE: Create Throw Exception when needed"

Question 5(c) [7 marks]

Write a java program to create a text file and perform read operation on the text file.

Answer: Java provides I/O classes to work with files, allowing creation, writing, and reading operations.

Code Block:

Java
  • FileWriter: Creates and writes to files
  • FileReader: Reads character data from files
  • BufferedReader: Efficiently reads text by lines

Mnemonic: "WRC: Write Read Close for file operations"

Question 5(a OR) [3 marks]

Explain java I/O process.

Answer: Java I/O process involves transferring data to and from various sources using streams.

Table: Java I/O Stream Types

ClassificationTypes
DirectionInput, Output
Data TypeByte Streams, Character Streams
FunctionalityBasic, Buffered, Data, Object

Diagram: Java I/O Hierarchy

Java I/O Hierarchy

  • Stream: Sequence of data flowing between source and destination
  • Buffering: Improves performance by reducing disk access

Mnemonic: "SBI: Stream Buffered Input/Output"

Question 5(b OR) [4 marks]

Explain throw and finally in Exception Handling with example.

Answer: Exception handling mechanisms control program flow during errors, ensuring graceful execution.

Table: throw vs finally

Featurethrowfinally
PurposeExplicitly throws exceptionEnsures code execution
PlacementInside methodAfter try-catch blocks
ExecutionWhen condition metAlways, even with return
UsageControl flowResource cleanup

Code Block:

Java

Mnemonic: "TERA: Throw Exception Regardless Always finally executes"

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.

Code Block:

Java
  • FileWriter(file, true): Second parameter enables append mode
  • BufferedReader: Efficiently reads text by lines
  • Reusable Method: Encapsulates reading functionality

Mnemonic: "CAD: Create Append Display file operations"