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 Type | Size | Description | Range |
|---|---|---|---|
| byte | 8 bits | Integer type | -128 to 127 |
| short | 16 bits | Integer type | -32,768 to 32,767 |
| int | 32 bits | Integer type | -2^31 to 2^31-1 |
| long | 64 bits | Integer type | -2^63 to 2^63-1 |
| float | 32 bits | Floating-point | Single precision |
| double | 64 bits | Floating-point | Double precision |
| char | 16 bits | Character | Unicode characters |
| boolean | 1 bit | Logical | true 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
| Operator | Description | Example |
|---|---|---|
| + | Addition | a + b |
| - | Subtraction | a - b |
| * | Multiplication | a * b |
| / | Division | a / b |
| % | Modulus (Remainder) | a % b |
| ++ | Increment | a++ or ++a |
| -- | Decrement | a-- 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
| Feature | Procedure-Oriented | Object-Oriented |
|---|---|---|
| Focus | Functions/Procedures | Objects |
| Data | Separate from functions | Encapsulated in objects |
| Security | Less secure | More secure with access control |
| Inheritance | Not supported | Supported |
| Reusability | Less reusable | Highly reusable |
| Complexity | Simpler for small programs | Better 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
| Use | Purpose | Example |
|---|---|---|
| static variable | Shared across all objects | static int count; |
| static method | Can be called without object | static void display() |
| static block | Executed when class loads | static { // code } |
| static nested class | Associated with outer class | static 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
| Type | Description | Example |
|---|---|---|
| Default | No parameters, created by compiler | Student() {} |
| No-arg | Explicitly defined, no parameters | Student() { name = "Unknown"; } |
| Parameterized | Accepts parameters | Student(String n) { name = n; } |
| Copy | Creates object from another object | Student(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
| Concept | Description |
|---|---|
| Encapsulation | Binding data and methods together |
| Inheritance | Creating new classes from existing ones |
| Polymorphism | One interface, multiple implementations |
| Abstraction | Hiding implementation details |
| Association | Relationship 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
| Use | Effect | Example |
|---|---|---|
| final variable | Cannot be modified | final int MAX = 100; |
| final method | Cannot be overridden | final void display() {} |
| final class | Cannot be extended | final class Math {} |
| final parameter | Cannot be changed in method | void 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
| Modifier | Class | Package | Subclass | World |
|---|---|---|---|---|
| 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
| Type | Description |
|---|---|
| Single | One class extends one class |
| Multilevel | Chain of inheritance (A→B→C) |
| Hierarchical | Multiple classes extend one class |
| Multiple | One class inherits from multiple classes (through interfaces) |
| Hybrid | Combination 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
| Method | Purpose | Syntax |
|---|---|---|
| append() | Adds string at the end | sb.append(String str) |
| insert() | Adds string at specified position | sb.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
| Feature | Abstract Class | Interface |
|---|---|---|
| Keyword | abstract | interface |
| Methods | Both abstract and concrete | Abstract (and default since Java 8) |
| Variables | Any type | Only public static final |
| Constructor | Has | Doesn't have |
| Inheritance | Single | Multiple |
| Access Modifiers | Any | Only public |
| Purpose | Partial implementation | Complete 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
| Method | Purpose | Syntax |
|---|---|---|
| substring() | Extracts portion of string | str.substring(int beginIndex, int endIndex) |
| equals() | Compares string content | str1.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
| Step | Action |
|---|---|
| 1 | Declare package name at the top of source files |
| 2 | Create proper directory structure matching package name |
| 3 | Save Java file in the appropriate directory |
| 4 | Compile with javac -d option to create package directory |
| 5 | Run 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 Type | When Occurs | Example |
|---|---|---|
| Compile-time Errors | During compilation | Syntax errors, type errors |
| Runtime Errors | During execution | NullPointerException, ArrayIndexOutOfBoundsException |
| Logical Errors | During execution with wrong output | Incorrect calculation, infinite loop |
| Linkage Errors | During class loading | NoClassDefFoundError |
| Thread Death | When thread terminates | ThreadDeath |
- 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
| Feature | Method Overloading | Method Overriding |
|---|---|---|
| Occurrence | Same class | Parent and child classes |
| Parameters | Different parameters | Same parameters |
| Return Type | Can be different | Must be same or covariant |
| Access Modifier | Can be different | Can't be more restrictive |
| Binding | Compile-time (static) | Runtime (dynamic) |
| Purpose | Multiple behaviors of same method | Specialized implementation |
| Inheritance | Not required | Required |
| @Override | Not used | Recommended |
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
| Exception | Cause | Package |
|---|---|---|
| NullPointerException | Access/modify null reference | java.lang |
| ArrayIndexOutOfBoundsException | Invalid array index | java.lang |
| ArithmeticException | Invalid arithmetic operation (division by zero) | java.lang |
| ClassCastException | Invalid class casting | java.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
| Usage | Purpose |
|---|---|
| throw new ExceptionType() | Create and throw exception |
| throw new ExceptionType(message) | Create with custom message |
| throws in method signature | Declare exceptions method might throw |
| Can throw checked/unchecked | Requires 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
| Feature | this Keyword | super Keyword |
|---|---|---|
| Reference | Current class | Parent class |
| Usage | Access current class members | Access parent class members |
| Constructor call | this() | super() |
| Variable resolution | this.var (current class) | super.var (parent class) |
| Method invocation | this.method() (current class) | super.method() (parent class) |
| Position | First statement in constructor | First statement in constructor |
| Inheritance | Not related to inheritance | Used 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
| Category | Stream Classes |
|---|---|
| Byte Streams | FileInputStream, FileOutputStream, BufferedInputStream, BufferedOutputStream |
| Character Streams | FileReader, FileWriter, BufferedReader, BufferedWriter |
| Data Streams | DataInputStream, DataOutputStream |
| Object Streams | ObjectInputStream, ObjectOutputStream |
| Print Streams | PrintStream, 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
| Operation | Description | Classes Used |
|---|---|---|
| File Creation | Create new files | File, FileOutputStream, FileWriter |
| File Reading | Read from files | FileInputStream, FileReader, Scanner |
| File Writing | Write to files | FileOutputStream, FileWriter, PrintWriter |
| File Deletion | Delete files | File.delete() |
| File Information | Get file metadata | File methods (length, isFile, etc.) |
| Directory Operations | Create/list directories | File methods (mkdir, list, etc.) |
| File Copy | Copy file contents | FileInputStream with FileOutputStream |
| File Renaming | Rename or move files | File.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"