Tribhuvan University
Faculty of Management
Office of the Dean
Official Model Question Paper / Dean's Office Blueprint
Candidates are required to answer all the questions in their own words as far as practicable. Figures in brackets indicate full marks.
- [2]
What is the purpose of this keyword in Java?
View model solution
Purpose of this Keyword in Java
The
thiskeyword in Java is an explicit reference to the current object instance.Primary Purposes:
- Disambiguating Shadowed Fields: Distinguishes between instance variables and local parameters of the same name (e.g.,
this.id = id;). - Constructor Chaining: Invokes another constructor of the same class using
this(args). - Passing/Returning Current Instance: Passes
thisto external methods or returns the current object reference from builder methods (return this;).
- Disambiguating Shadowed Fields: Distinguishes between instance variables and local parameters of the same name (e.g.,
- [2]
Which interfaces and classes are used to serialize and deserialize an object?
View model solution
Interfaces and Classes Used to Serialize and Deserialize Objects in Java
1. Interfaces:
java.io.Serializable: Marker interface (has no methods); informs the JVM that instances of the class are permitted to be serialized.java.io.Externalizable: ExtendsSerializable; provides explicit control over serialization format viawriteExternal()andreadExternal().
2. Classes:
java.io.ObjectOutputStream: Writes objects and primitive data types to an output stream using itswriteObject()method.java.io.ObjectInputStream: Reads and reconstructs serialized object graphs from an input stream using itsreadObject()method.
- [2]
List the difference between StringBuffer and StringBuilder in Java.
View model solution
Differences Between StringBuffer and StringBuilder
Feature StringBuffer(Java 1.0)StringBuilder(Java 5.0)Thread Safety Thread-safe; its public methods are synchronized. Not thread-safe; methods are non-synchronized. Performance Slower due to synchronization lock overhead. Significantly faster in single-threaded environments. Mutability Mutable sequence of characters. Mutable sequence of characters. Use Case When string buffers are shared across multiple concurrent threads. General string concatenation in single-threaded routines (standard practice). - [2]
List the Key Aspects of Java’s Impact on the Internet.
View model solution
Key Aspects of Java’s Impact on the Internet
Java revolutionized early and modern Web computing through:
- Client-Side Dynamic Content (Applets): Introduced portable, interactive graphical programs that ran securely inside client web browsers.
- Platform-Independent Server Architecture (Servlets & JSP): Established high-performance, scalable server-side web backends.
- Robust Security Sandbox: Enforced bytecode verification, memory safety (no raw pointers), and security managers protecting client computers from malicious code over the Internet.
- Enterprise Web Frameworks: Powering modern enterprise banking, e-commerce, and cloud APIs (Spring Boot, Jakarta EE).
- [2]
What is the difference between throw and throws in Java exception handling?
View model solution
Difference Between throw and throws in Java Exception Handling
Parameter throwKeywordthrowsKeywordPurpose Used to explicitly throw an individual exception object. Used in method signatures to declare exceptions that the method might throw. Location Placed inside the body of a method or block. Placed in the method signature declaration line. Syntax throw new ExceptionObject();void method() throws IOException, SQLExceptionMultiplicity Can throw only one exception instance at a time. Can declare multiple comma-separated exception classes.
- [5]
Describe the architecture of JVM, JRE, and JDK.
View model solution
Architecture of JVM, JRE, and JDK
The Java execution environment is structured in concentric layers:
+-------------------------------------------------------------+ | JDK (Java Development Kit) | | +-------------------------------------------------------+ | | | JRE (Java Runtime Environment) | | | | +-------------------------------------------------+ | | | | | JVM (Java Virtual Machine) | | | | | | - ClassLoader Subsystem | | | | | | - Memory Areas (Heap, Stack, Method, PC Reg) | | | | | | - Execution Engine (JIT Compiler, Interpreter)| | | | | | - Garbage Collector | | | | | +-------------------------------------------------+ | | | | - Core Class Libraries (rt.jar, java.base) | | | | - User Interface Toolkits (AWT, Swing) | | | +-------------------------------------------------------+ | | - Development Tools (javac, jdb, javadoc, jar) | +-------------------------------------------------------------+- JVM (Java Virtual Machine): The abstract computing machine that loads, verifies, and executes bytecode.
- JRE (Java Runtime Environment): Includes the JVM plus the core standard class libraries necessary to run compiled Java applications.
- JDK (Java Development Kit): The complete software development environment containing the JRE, compiler (
javac), debugger, and archiving tools.
- [5]
Write a Java program to demonstrate type conversion and casting between different data types.
View model solution
Java Program: Type Conversion and Casting
public class TypeCastingDemo { public static void main(String[] args) { System.out.println("=== Type Conversion and Casting Demonstration ===\n"); // 1. Widening Casting (Implicit / Automatic) // byte -> short -> int -> long -> float -> double int intVal = 100; double doubleVal = intVal; // Automatically converted System.out.println("1. Widening Casting (Implicit):"); System.out.println(" int value : " + intVal); System.out.println(" double value : " + doubleVal); System.out.println(); // 2. Narrowing Casting (Explicit / Manual) // double -> float -> long -> int -> short -> byte double pi = 3.14159265; int truncatedPi = (int) pi; // Explicit typecast System.out.println("2. Narrowing Casting (Explicit):"); System.out.println(" double value : " + pi); System.out.println(" int (cast) : " + truncatedPi); } } - [5]
Explain method overloading and variable length arguments (varargs) in Java.
View model solution
Method Overloading and Variable-Length Arguments (varargs)
1. Concepts:
- Method Overloading: Allows multiple methods with the same name differing in argument signatures.
- Varargs (
...): Allows a method to accept zero or multiple arguments of a specified type without manually packing them into an array.
public class OverloadVarargsDemo { // Overloaded method 1: Two integer parameters static int sum(int a, int b) { return a + b; } // Overloaded method 2: Variable length arguments (varargs) static int sum(int... numbers) { int total = 0; for (int n : numbers) { total += n; } return total; } public static void main(String[] args) { System.out.println("Sum of 2 numbers: " + sum(10, 20)); System.out.println("Sum of 4 numbers: " + sum(5, 10, 15, 20)); System.out.println("Sum with 0 args : " + sum()); } } - [5]
Explain the concept of Sealed classes with example.
View model solution
Concept of Sealed Classes in Java (Java 17+)
A Sealed Class restricts which other classes or interfaces may extend or implement it, providing fine-grained control over the inheritance hierarchy.
Syntax & Keywords:
sealed: Declares the restricted base class.permits: Specifies the exact permitted subclasses.- Permitted subclasses must be declared as
final,sealed, ornon-sealed.
// Base sealed class public sealed abstract class Shape permits Circle, Rectangle { public abstract double area(); } // Permitted subclass marked final public final class Circle extends Shape { private final double radius; public Circle(double r) { this.radius = r; } public double area() { return Math.PI * radius * radius; } } // Permitted subclass marked final public final class Rectangle extends Shape { private final double length, width; public Rectangle(double l, double w) { this.length = l; this.width = w; } public double area() { return length * width; } } - [5]
Write a Java program to demonstrate the use of nested try blocks.
View model solution
Java Program: Nested Try Blocks Demonstration
public class NestedTryDemo { public static void main(String[] args) { System.out.println("=== Nested Try Block Exception Handling ===\n"); try { // Outer try block int[] arr = {10, 20, 30}; try { // Inner try block 1: ArithmeticException int a = 50; int b = 0; int result = a / b; System.out.println("Result: " + result); } catch (ArithmeticException e) { System.out.println("Handled in Inner Catch 1: Division by zero!"); } try { // Inner try block 2: ArrayIndexOutOfBoundsException System.out.println("Accessing arr[5]: " + arr[5]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Handled in Inner Catch 2: Array index out of bounds!"); } } catch (Exception e) { System.out.println("Handled in Outer Catch: General Exception."); } } } - [5]
What are wrapper classes in Java? Describe the concepts of autoboxing and unboxing.
View model solution
Wrapper Classes, Autoboxing, and Unboxing in Java
1. Autoboxing:
The automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes (e.g., converting
inttoInteger).2. Unboxing:
The automatic conversion of an object of a wrapper type back to its corresponding primitive value (e.g., converting
Integertoint).import java.util.ArrayList; public class AutoboxingDemo { public static void main(String[] args) { // Autoboxing: primitive int 25 automatically boxed into Integer object Integer obj = 25; // Unboxing: Integer object automatically unboxed into primitive int int num = obj; ArrayList<Double> marksList = new ArrayList<>(); marksList.add(85.5); // Autoboxing double -> Double double mark = marksList.get(0); // Unboxing Double -> double System.out.println("Autoboxed Integer : " + obj); System.out.println("Unboxed int : " + num); System.out.println("Unboxed mark : " + mark); } } - [5]
Write a Java program using StringBuffer to demonstrate string manipulation by performing operations such as appending, inserting, and deleting characters.
View model solution
Java Program: StringBuffer Manipulation (append, insert, delete)
public class StringBufferManipulationDemo { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Paper"); System.out.println("=== StringBuffer Manipulation Operations ===\n"); System.out.println("Initial StringBuffer : " + sb); // 1. Append sb.append(" Khoj"); System.out.println("After append(\" Khoj\") : " + sb); // 2. Insert sb.insert(5, " Nepal"); System.out.println("After insert(5, \" Nepal\"): " + sb); // 3. Delete sb.delete(5, 11); // Removes " Nepal" System.out.println("After delete(5, 11) : " + sb); } }
- [10]
Write a Java program to demonstrate file handling by performing read and write operations on a file.
View model solution
Java Program: File Handling Read and Write Operations
import java.io.*; public class FileHandlingDemo { public static void main(String[] args) { String fileName = "sample.txt"; System.out.println("=== File Handling (Write and Read) Demonstration ===\n"); // Step 1: Write text to file try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) { writer.write("Tribhuvan University - Faculty of Management"); writer.newLine(); writer.write("Bachelor of Information Technology Management (BITM)"); writer.newLine(); writer.write("Paper Khoj Official Academic Archive."); System.out.println("Successfully wrote data into '" + fileName + "'.\n"); } catch (IOException e) { System.err.println("Write Error: " + e.getMessage()); } // Step 2: Read text from file System.out.println("--- Reading Contents from '" + fileName + "' ---"); try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.err.println("Read Error: " + e.getMessage()); } } } - [10]
Define polymorphism in Java and explain its types with suitable examples.
View model solution
Polymorphism in Java and Its Types
Polymorphism (Greek: “many forms”) is the ability of an object, reference, or method to take on multiple operational behaviors.
1. Compile-Time Polymorphism (Static Binding / Method Overloading):
- Resolved at compilation time based on parameter types and counts.
- Handled via Method Overloading.
2. Runtime Polymorphism (Dynamic Binding / Method Overriding):
- Resolved at runtime via Dynamic Method Dispatch.
- Occurs when a subclass provides a specific implementation of a method declared in its superclass using the
@Overrideannotation.
// Superclass class Payment { void processPayment(double amount) { System.out.println("Processing generic payment of Rs. " + amount); } } // Subclasses overriding method class EsewaPayment extends Payment { @Override void processPayment(double amount) { System.out.println("Processing eSewa digital wallet payment of Rs. " + amount); } } class CardPayment extends Payment { @Override void processPayment(double amount) { System.out.println("Processing debit/credit card payment of Rs. " + amount); } } public class PolymorphismDemo { public static void main(String[] args) { // Superclass reference holding subclass instances Payment p1 = new EsewaPayment(); Payment p2 = new CardPayment(); p1.processPayment(1500.0); p2.processPayment(4200.0); } } - [10]
Write a Java program that simulates a ticket booking system in which multiple threads attempt to book tickets from a limited number of available seats. The program should include a class named TicketCounter with a method for booking tickets, and the total number of tickets should be initialized as 10 tickets. Create multiple threads using the Runnable interface that try to book tickets at the same time. Apply proper synchronization to ensure that tickets are not overbooked. The program should display which thread successfully books tickets and the number of tickets remaining after each transaction. Use the Thread class to create and manage the threads.
View model solution
Java Program: Multi-Threaded Ticket Booking Simulation with Synchronization
// Shared resource with synchronized booking method class TicketCounter { private int availableTickets = 10; public synchronized void bookTicket(String customerName, int requestedTickets) { System.out.println(customerName + " entered counter. Requesting " + requestedTickets + " ticket(s)..."); if (requestedTickets <= availableTickets) { System.out.println("--> SUCCESS: " + customerName + " successfully booked " + requestedTickets + " ticket(s)."); availableTickets -= requestedTickets; System.out.println(" Remaining tickets available: " + availableTickets + "\n"); } else { System.out.println("--> FAILED: Sorry " + customerName + ", not enough tickets. Available: " + availableTickets + "\n"); } } } // Runnable task implementing ticket booking class CustomerTask implements Runnable { private TicketCounter counter; private String customerName; private int numberOfTickets; public CustomerTask(TicketCounter counter, String name, int tickets) { this.counter = counter; this.customerName = name; this.numberOfTickets = tickets; } @Override public void run() { counter.bookTicket(customerName, numberOfTickets); } } public class TicketBookingSystem { public static void main(String[] args) { System.out.println("=== Synchronized Multi-Threaded Ticket Booking System ===\n"); TicketCounter counter = new TicketCounter(); // Create multiple concurrent customer booking threads Thread t1 = new Thread(new CustomerTask(counter, "Passenger-Ram", 4)); Thread t2 = new Thread(new CustomerTask(counter, "Passenger-Sita", 3)); Thread t3 = new Thread(new CustomerTask(counter, "Passenger-Hari", 4)); Thread t4 = new Thread(new CustomerTask(counter, "Passenger-Gita", 2)); // Start threads simultaneously t1.start(); t2.start(); t3.start(); t4.start(); try { t1.join(); t2.join(); t3.join(); t4.join(); } catch (InterruptedException e) { System.err.println("Thread interrupted: " + e.getMessage()); } System.out.println("All ticket booking transactions completed."); } }