Java Programming (4343203) - Winter 2024 Solution

Solution guide for Java Programming (4343203) Winter 2024 exam

Question 1(a) [3 marks]

List out various Primitive data types in Java.

Answer: Java offers eight primitive data types for storing simple values directly in memory.

Table: Java Primitive Data Types

Data TypeSizeDescriptionRange
byte8 bitsInteger type-128 to 127
short16 bitsInteger type-32,768 to 32,767
int32 bitsInteger type-2^31 to 2^31-1
long64 bitsInteger type-2^63 to 2^63-1
float32 bitsFloating-pointSingle precision
double64 bitsFloating-pointDouble precision
char16 bitsCharacterUnicode characters
boolean1 bitLogicaltrue or false

Mnemonic: "BILFDC-B: Byte Int Long Float Double Char Boolean types"

Question 1(b) [4 marks]

Explain Structure of Java Program with suitable example.

Answer: Java program structure follows a specific organization with package declarations, imports, class definitions, and methods.

Diagram: Java Program Structure

goat

Code Block:

Java

Mnemonic: "PICOM: Package Import Class Objects Methods in order"

Question 1(c) [7 marks]

List arithmetic operators in Java. Develop a Java program using any three arithmetic operators and show the output of program.

Answer: Arithmetic operators in Java perform mathematical operations on numeric values.

Table: Java Arithmetic Operators

OperatorDescriptionExample
+Additiona + b
-Subtractiona - b
*Multiplicationa * b
/Divisiona / b
%Modulus (Remainder)a % b
++Incrementa++ or ++a
--Decrementa-- or --a

Code Block:

Java

Output:

Values: a = 10, b = 3
Addition (a + b): 13
Multiplication (a * b): 30
Modulus (a % b): 1

Mnemonic: "SAME: Sum Addition Multiply Exponentiation basic operations"

Question 1(c OR) [7 marks]

Write syntax of Java for loop statement. Develop a Java program to find out prime number between 1 to 10.

Answer: The for loop in Java provides a compact way to iterate over a range of values.

Syntax of Java for loop:

for (initialization; condition; increment/decrement) {
    // statements to be executed
}

Code Block:

Java

Output:

Prime numbers between 1 and 10:
2 3 5 7

Mnemonic: "ICE: Initialize, Check, Execute steps of for loop"

Question 2(a) [3 marks]

List the differences between Procedure-Oriented Programming (POP) and Object-Oriented Programming (OOP).

Answer: Procedure-Oriented and Object-Oriented Programming represent fundamentally different programming paradigms.

Table: POP vs OOP

FeatureProcedure-OrientedObject-Oriented
FocusFunctions/ProceduresObjects
DataSeparate from functionsEncapsulated in objects
SecurityLess secureMore secure with access control
InheritanceNot supportedSupported
ReusabilityLess reusableHighly reusable
ComplexitySimpler for small programsBetter for complex systems
  • Organization: POP divides into functions; OOP groups into objects
  • Approach: POP follows top-down; OOP follows bottom-up

Mnemonic: "FIOS: Functions In Objects Structure key difference"

Question 2(b) [4 marks]

Explain static keyword with example.

Answer: The static keyword in Java creates class-level members shared across all objects of that class.

Table: Uses of static Keyword

UsePurposeExample
static variableShared across all objectsstatic int count;
static methodCan be called without objectstatic void display()
static blockExecuted when class loadsstatic { // code }
static nested classAssociated with outer classstatic class Inner {}

Code Block:

Java

Output:

Static count: 3
c1's instance count: 1
c2's instance count: 1
c3's instance count: 1

Mnemonic: "CBMS: Class-level, Before objects, Memory single, Shared by all"

Question 2(c) [7 marks]

Define Constructor. List types of Constructors. Develop a java code to explain Parameterized constructor.

Answer: A constructor is a special method with the same name as its class, used to initialize objects when created.

Types of Constructors:

Table: Constructor Types in Java

TypeDescriptionExample
DefaultNo parameters, created by compilerStudent() {}
No-argExplicitly defined, no parametersStudent() { name = "Unknown"; }
ParameterizedAccepts parametersStudent(String n) { name = n; }
CopyCreates object from another objectStudent(Student s) { name = s.name; }

Code Block:

Java

Output:

Student Details:
Name: John
Age: 20
Course: Computer Science
Student Details:
Name: Lisa
Age: 22
Course: Engineering

Mnemonic: "IDCR: Initialize Data Create Ready objects"

Question 2(a OR) [3 marks]

List the basic OOP concepts in Java and explain any one.

Answer: Java implements Object-Oriented Programming through several fundamental concepts.

Table: Basic OOP Concepts in Java

ConceptDescription
EncapsulationBinding data and methods together
InheritanceCreating new classes from existing ones
PolymorphismOne interface, multiple implementations
AbstractionHiding implementation details
AssociationRelationship between objects

Encapsulation Example:

Java
  • Data Hiding: Private variables inaccessible from outside
  • Controlled Access: Through public methods (getters/setters)
  • Integrity: Data validation ensures correct values

Mnemonic: "EIPA: Encapsulate Inherit Polymorphize Abstract"

Question 2(b OR) [4 marks]

Explain final keyword with example.

Answer: The final keyword in Java restricts changes to entities, creating constants, unchangeable methods, and non-inheritable classes.

Table: Uses of final Keyword

UseEffectExample
final variableCannot be modifiedfinal int MAX = 100;
final methodCannot be overriddenfinal void display() {}
final classCannot be extendedfinal class Math {}
final parameterCannot be changed in methodvoid method(final int x) {}

Code Block:

Java

Output:

Speed limit: 120

Mnemonic: "VMP: Variables Methods Permanence with final"

Question 2(c OR) [7 marks]

Write scope of java access modifier. Develop a java code to explain public modifier.

Answer: Access modifiers in Java control visibility and accessibility of classes, methods, and variables.

Table: Java Access Modifier Scope

ModifierClassPackageSubclassWorld
private
default (no modifier)
protected
public

Code Block:

Java

Output:

Message: Hello, World!
Hello, World!
Modified message

Mnemonic: "CEPM: Class Everywhere Public Most accessible"

Question 3(a) [3 marks]

List out different types of inheritance and explain any one with example.

Answer: Inheritance enables a class to inherit attributes and behaviors from another class.

Table: Types of Inheritance in Java

TypeDescription
SingleOne class extends one class
MultilevelChain of inheritance (A→B→C)
HierarchicalMultiple classes extend one class
MultipleOne class inherits from multiple classes (through interfaces)
HybridCombination of multiple inheritance types

Single Inheritance Example:

Java

Output:

Name: Max
Breed: Labrador
Max is eating
Max is barking

Mnemonic: "SMHMH: Single Multilevel Hierarchical Multiple Hybrid types"

Question 3(b) [4 marks]

Explain any two String buffer class methods with suitable example.

Answer: StringBuffer is a mutable sequence of characters used for modifying strings, offering various manipulation methods.

Table: Two StringBuffer Methods

MethodPurposeSyntax
append()Adds string at the endsb.append(String str)
insert()Adds string at specified positionsb.insert(int offset, String str)

Code Block:

Java

Output:

Original: Hello
After append(): Hello World
After appending more: Hello World!2024

New Original: Java
After insert() at beginning: Learn Java
After insert() in middle: Learn Java Programming

Mnemonic: "AIMS: Append Insert Modify StringBuffer"

Question 3(c) [7 marks]

Define Interface. Write a java program to demonstrate multiple inheritance using interface.

Answer: An interface is a contract that declares methods a class must implement, enabling multiple inheritance in Java.

Definition: An interface is a reference type containing only constants, method signatures, default methods, static methods, and nested types with no implementation for abstract methods.

Diagram: Multiple Inheritance using Interfaces

Code Block:

Java

Output:

Device Model: HP LaserJet
HP LaserJet is printing a document
HP LaserJet is scanning a document
Is device Printable? true
Is device Scannable? true

Mnemonic: "IMAC: Interface Multiple Abstract Contract"

Question 3(a OR) [3 marks]

Give differences between Abstract class and Interface.

Answer: Abstract classes and interfaces are both used for abstraction but differ in several key aspects.

Table: Abstract Class vs Interface

FeatureAbstract ClassInterface
Keywordabstractinterface
MethodsBoth abstract and concreteAbstract (and default since Java 8)
VariablesAny typeOnly public static final
ConstructorHasDoesn't have
InheritanceSingleMultiple
Access ModifiersAnyOnly public
PurposePartial implementationComplete abstraction
  • Implementation: Abstract classes can provide partial implementation; interfaces traditionally provide none
  • Relationship: Abstract class says "is-a"; interface says "can-do-this"

Mnemonic: "MAPS: Methods Access Purpose Single vs multiple"

Question 3(b OR) [4 marks]

Explain any two String class methods with suitable example.

Answer: The String class offers various methods for string manipulation, comparison, and transformation.

Table: Two String Methods

MethodPurposeSyntax
substring()Extracts portion of stringstr.substring(int beginIndex, int endIndex)
equals()Compares string contentstr1.equals(str2)

Code Block:

Java

Output:

substring(0, 4): Java
substring(5): Programming

Comparing strings with equals():
str1.equals(str2): true
str1.equals(str3): false
str1.equals(str4): true

Comparing strings with ==:
str1 == str2: true
str1 == str4: false

Mnemonic: "SEC: Substring Equals Compare string content"

Question 3(c OR) [7 marks]

Explain package and list out steps to create package with suitable example.

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

Steps to Create a Package:

Table: Package Creation Steps

StepAction
1Declare package name at the top of source files
2Create proper directory structure matching package name
3Save Java file in the appropriate directory
4Compile with javac -d option to create package directory
5Run the program with fully qualified name

Code Block:

Java

Terminal Commands:

// Step 2: Create directory structure
mkdir -p com/example/math
mkdir -p com/example/app

// Step 3: Place files in appropriate directories
mv Calculator.java com/example/math/
mv CalculatorApp.java com/example/app/

// Step 4: Compile with -d option
javac -d . com/example/math/Calculator.java
javac -d . -cp . com/example/app/CalculatorApp.java

// Step 5: Run with fully qualified name
java com.example.app.CalculatorApp

Output:

Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0

Mnemonic: "DISCO: Declare Import Save Compile Organize"

Question 4(a) [3 marks]

List types of errors in Java.

Answer: Java programs can encounter various errors during development and execution.

Table: Types of Errors in Java

Error TypeWhen OccursExample
Compile-time ErrorsDuring compilationSyntax errors, type errors
Runtime ErrorsDuring executionNullPointerException, ArrayIndexOutOfBoundsException
Logical ErrorsDuring execution with wrong outputIncorrect calculation, infinite loop
Linkage ErrorsDuring class loadingNoClassDefFoundError
Thread DeathWhen thread terminatesThreadDeath
  • Syntax Errors: Missing semicolons, brackets, or typos
  • Semantic Errors: Type mismatches, incompatible operations
  • Exceptions: Runtime issues requiring handling

Mnemonic: "CRLLT: Compile Runtime Logical Linkage Thread errors"

Question 4(b) [4 marks]

Explain try catch block with example.

Answer: The try-catch block in Java handles exceptions, allowing programs to continue executing despite errors.

Diagram: Try-Catch Flow

Code Block:

Java

Output:

Exception caught: Index 4 out of bounds for length 3
Array index out of bounds
Finally block executed
Program continues after exception handling

Mnemonic: "TCFE: Try Catch Finally Execute despite errors"

Question 4(c) [7 marks]

List out any four differences between method overloading and overriding. Write a java code to explain method overriding.

Answer: Method overloading and overriding are both forms of polymorphism but differ in functionality and implementation.

Table: Method Overloading vs Overriding

FeatureMethod OverloadingMethod Overriding
OccurrenceSame classParent and child classes
ParametersDifferent parametersSame parameters
Return TypeCan be differentMust be same or covariant
Access ModifierCan be differentCan't be more restrictive
BindingCompile-time (static)Runtime (dynamic)
PurposeMultiple behaviors of same methodSpecialized implementation
InheritanceNot requiredRequired
@OverrideNot usedRecommended

Code Block:

Java

Output:

Animal behavior:
Animal makes a sound
Animal eats food

Dog behavior:
Dog barks
Dog eats meat

Cat behavior:
Cat meows
Animal eats food

Mnemonic: "SBRE: Same-name, Base-derived, Runtime-resolution, Extend functionality"

Question 4(a OR) [3 marks]

List any four inbuilt exceptions.

Answer: Java provides many built-in exception classes that represent various error conditions.

Table: Four Common Inbuilt Exceptions

ExceptionCausePackage
NullPointerExceptionAccess/modify null referencejava.lang
ArrayIndexOutOfBoundsExceptionInvalid array indexjava.lang
ArithmeticExceptionInvalid arithmetic operation (division by zero)java.lang
ClassCastExceptionInvalid class castingjava.lang
  • Unchecked: Runtime exceptions (don't require explicit handling)
  • Hierarchy: All extend from Exception class
  • Handling: Can be caught with try-catch blocks

Mnemonic: "NAAC: Null Array Arithmetic Cast common exceptions"

Question 4(b OR) [4 marks]

Explain "throw" keyword with suitable example.

Answer: The throw keyword in Java manually generates exceptions for exceptional conditions in programs.

Table: throw Keyword Usage

UsagePurpose
throw new ExceptionType()Create and throw exception
throw new ExceptionType(message)Create with custom message
throws in method signatureDeclare exceptions method might throw
Can throw checked/uncheckedRequires try-catch for checked exceptions

Code Block:

Java

Output:

Validating age 20:
Eligible to vote

Validating age 15:
ArithmeticException: Not eligible to vote

Validating age -5:
Exception: Age cannot be negative

Mnemonic: "CET: Create Exception Throw for error handling"

Question 4(c OR) [7 marks]

Compare 'this' keyword Vs 'Super' keyword. Explain super keyword with suitable Example.

Answer: The 'this' and 'super' keywords are used for referencing in Java, with distinct purposes and behaviors.

Table: this vs super Keyword Comparison

Featurethis Keywordsuper Keyword
ReferenceCurrent classParent class
UsageAccess current class membersAccess parent class members
Constructor callthis()super()
Variable resolutionthis.var (current class)super.var (parent class)
Method invocationthis.method() (current class)super.method() (parent class)
PositionFirst statement in constructorFirst statement in constructor
InheritanceNot related to inheritanceUsed with inheritance

Code Block:

Java

Output:

Vehicle constructor called
Car constructor called

Variable access with this and super:
Car brand (this): Toyota
Car color (this): Blue
Vehicle brand (super): Ford
Vehicle color (super): Red

Method call with super:
Car information:
Brand: Ford
Color: Red
Model: Corolla

Mnemonic: "PCIM: Parent Class Inheritance Members with super"

Question 5(a) [3 marks]

List Different Stream Classes.

Answer: Java I/O provides various stream classes for handling input and output operations.

Table: Java Stream Classes

CategoryStream Classes
Byte StreamsFileInputStream, FileOutputStream, BufferedInputStream, BufferedOutputStream
Character StreamsFileReader, FileWriter, BufferedReader, BufferedWriter
Data StreamsDataInputStream, DataOutputStream
Object StreamsObjectInputStream, ObjectOutputStream
Print StreamsPrintStream, PrintWriter
  • Byte Streams: Work with binary data (8-bit bytes)
  • Character Streams: Work with characters (16-bit Unicode)
  • Buffered Streams: Improve performance through buffering

Mnemonic: "BCDOP: Byte Character Data Object Print streams"

Question 5(b) [4 marks]

Write a java program to develop user defined exception for "Divide by zero" error.

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

Code Block:

Java

Output:

10 / 2 = 5.0
Error: Division by zero not allowed
Custom exception stack trace:
DivideByZeroException: Division by zero not allowed
    at CustomExceptionDemo.divide(CustomExceptionDemo.java:19)
    at CustomExceptionDemo.main(CustomExceptionDemo.java:29)
Program continues execution...

Mnemonic: "ETC: Extend Throw Catch custom exceptions"

Question 5(c) [7 marks]

Write a program in Java that reads the content of a file byte by byte and copy it into another file.

Answer: File I/O operations in Java allow reading from and writing to files, with byte streams handling binary data.

Code Block:

Java

Creating source.txt file first:

Java

Output:

Source file created successfully!
Copying file source.txt to destination.txt
File copied successfully!
Total bytes copied: 82
File streams closed successfully

Mnemonic: "CROW: Create Read Open Write file operations"

Question 5(a OR) [3 marks]

List different file operations in Java.

Answer: Java provides comprehensive file handling capabilities through various file operations.

Table: File Operations in Java

OperationDescriptionClasses Used
File CreationCreate new filesFile, FileOutputStream, FileWriter
File ReadingRead from filesFileInputStream, FileReader, Scanner
File WritingWrite to filesFileOutputStream, FileWriter, PrintWriter
File DeletionDelete filesFile.delete()
File InformationGet file metadataFile methods (length, isFile, etc.)
Directory OperationsCreate/list directoriesFile methods (mkdir, list, etc.)
File CopyCopy file contentsFileInputStream with FileOutputStream
File RenamingRename or move filesFile.renameTo()
  • Stream-based: Low-level byte or character streams
  • Reader/Writer: Character-oriented file operations
  • NIO Package: Enhanced file operations (since Java 7)

Mnemonic: "CRWD: Create Read Write Delete basic operations"

Question 5(b OR) [4 marks]

Write a java program to explain finally block in exception handling.

Answer: The finally block in exception handling ensures code execution regardless of whether an exception occurs.

Diagram: try-catch-finally Flow

Code Block:

Java

Output:

Example 1: No exception
Result: 2
Finally block executed - Example 1

Example 2: Exception caught
Arithmetic exception caught: / by zero
Finally block executed - Example 2

Example 3: Resource management
File not found: nonexistent.txt (No such file or directory)
File resource closed in finally block

Program continues execution...

Mnemonic: "ACRE: Always Cleanup Resources Executes"

Question 5(c OR) [7 marks]

Write a java program to create a file and perform write operation on this file.

Answer: Java provides several ways to create files and write data to them using character or byte streams.

Code Block:

Java

Example output:

File created successfully: sample_data.txt

Enter text to write to file (type 'exit' to finish):
This is line 1 of my file.
This is line 2 with some Java content.
Here is line 3 with more text.
exit

File write operation completed successfully!

Mnemonic: "COWS: Create Open Write Save file operations"