BE Computer Engineering (Pokhara University) Advanced Programming with Java (PU, CMP 228) Question Paper 2078 Nepal
This is the official BE Computer Engineering (Pokhara University) Advanced Programming with Java (PU, CMP 228) question paper for 2078, as set in the regular annual examination. It carries 100 full marks and a time allowance of 180 minutes, across 11 questions. On Kekkei you can attempt this Advanced Programming with Java (PU, CMP 228) past paper online with a timer, get instant AI feedback and step-by-step solutions, and track the topics where you lose marks — completely free. Whether you are revising for your BE Computer Engineering (Pokhara University) Advanced Programming with Java (PU, CMP 228) exam or solving previous years' question papers, this 2078 paper is a great way to practise under real exam conditions.
Section A: Long Answer Questions
Attempt all / any as specified.
Object-oriented programming forms the foundation of Java.
(a) Differentiate between method overloading and method overriding with suitable code examples. (5)
(b) Explain the four pillars of OOP (encapsulation, inheritance, polymorphism, and abstraction). Write a Java program that defines an abstract class Shape with an abstract method area(), and two subclasses Circle and Rectangle that provide their own implementations. Demonstrate runtime polymorphism using a reference of type Shape. (7)
(a) Method Overloading vs Method Overriding (5)
| Aspect | Method Overloading | Method Overriding |
|---|---|---|
| Definition | Same method name with different parameter lists in the same class | Subclass provides a new implementation of a method already defined in its superclass |
| Binding | Compile-time (static) polymorphism | Runtime (dynamic) polymorphism |
| Signature | Must differ in number/type/order of parameters | Must be identical (name + parameters + compatible return type) |
| Inheritance | Not required | Required (an IS-A relationship) |
| Keyword | None | Marked with @Override (recommended) |
Overloading example:
class Calc {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; } // different param types
int add(int a, int b, int c) { return a + b + c; } // different param count
}
Overriding example:
class Animal {
void sound() { System.out.println("Some sound"); }
}
class Dog extends Animal {
@Override
void sound() { System.out.println("Bark"); } // redefines parent method
}
(b) Four Pillars of OOP + Abstract Shape Program (7)
1. Encapsulation — Binding data (fields) and the methods that operate on them into a single unit (class) and hiding internal state using private fields exposed through getters/setters.
2. Inheritance — A subclass acquires the fields and methods of a superclass using extends, promoting code reuse and an IS-A relationship.
3. Polymorphism — "One name, many forms." A superclass reference can refer to subclass objects, and the correct overridden method is chosen at runtime.
4. Abstraction — Showing only essential features while hiding implementation details, achieved through abstract classes and interfaces.
abstract class Shape {
abstract double area(); // abstract method, no body
void describe() {
System.out.println("Area = " + area());
}
}
class Circle extends Shape {
private double r;
Circle(double r) { this.r = r; }
@Override
double area() { return Math.PI * r * r; }
}
class Rectangle extends Shape {
private double l, b;
Rectangle(double l, double b) { this.l = l; this.b = b; }
@Override
double area() { return l * b; }
}
public class Main {
public static void main(String[] args) {
Shape s; // reference of type Shape
s = new Circle(5); // runtime polymorphism
s.describe(); // calls Circle.area() -> 78.54
s = new Rectangle(4, 6);
s.describe(); // calls Rectangle.area() -> 24.0
}
}
The single Shape reference s invokes different area() implementations at runtime, demonstrating runtime (dynamic) polymorphism.
Multithreading allows concurrent execution of two or more parts of a program.
(a) Describe the life cycle of a thread in Java with a neat state-transition diagram. (4)
(b) Compare the two ways of creating threads in Java: extending the Thread class versus implementing the Runnable interface. State which one you would prefer and why. (4)
(c) What is a race condition? Write a Java program that simulates a shared bank account being accessed by multiple threads, and use the synchronized keyword to prevent inconsistent withdrawals. (6)
(a) Life Cycle of a Thread (4)
A Java thread passes through the following states (defined in Thread.State):
- New — Thread object created (
new Thread()) butstart()not yet called. - Runnable — After
start()is called; the thread is ready and waiting for CPU scheduling (includes "ready" and "running"). - Running — The thread scheduler picks the thread and it executes
run(). - Blocked / Waiting / Timed-Waiting — Thread temporarily inactive: waiting for a lock (Blocked), waiting indefinitely via
wait()/join()(Waiting), or waiting for a time viasleep(ms)/wait(ms)(Timed-Waiting). - Terminated (Dead) —
run()completes or the thread is stopped; it cannot be restarted.
State-transition diagram (described):
New --start()--> Runnable <----> Running --run() ends--> Terminated
^ |
| | sleep()/wait()/lock unavailable
| v
notify()/timeout/ Blocked / Waiting / Timed-Waiting
lock acquired
(b) Thread Class vs Runnable Interface (4)
| Aspect | Extending Thread | Implementing Runnable |
|---|---|---|
| Inheritance | Uses up the single-inheritance slot (cannot extend another class) | Class is free to extend another class |
| Coupling | Task and thread are coupled | Task (Runnable) separated from execution mechanism |
| Reusability | Lower | Higher; same Runnable can be given to a thread pool/Executor |
| Object sharing | Each thread is a separate object | One Runnable can be shared by many threads |
Preferred: Runnable, because Java allows only single class inheritance, so implementing Runnable keeps the class free to extend another class, separates the task from the thread, and works seamlessly with ExecutorService thread pools.
(c) Race Condition + Synchronized Bank Account (6)
A race condition occurs when two or more threads access and modify shared data concurrently and the final result depends on the unpredictable order of execution, producing inconsistent values. It is prevented by allowing only one thread into the critical section at a time using synchronized.
class BankAccount {
private int balance = 1000;
// synchronized: only one thread can withdraw at a time
synchronized void withdraw(int amount) {
if (balance >= amount) {
System.out.println(Thread.currentThread().getName() + " withdrawing " + amount);
balance -= amount;
System.out.println("Remaining balance: " + balance);
} else {
System.out.println(Thread.currentThread().getName() + ": Insufficient funds");
}
}
}
public class BankDemo {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
Runnable task = () -> {
for (int i = 0; i < 3; i++) acc.withdraw(200);
};
Thread t1 = new Thread(task, "T1");
Thread t2 = new Thread(task, "T2");
t1.start();
t2.start();
}
}
The synchronized keyword serialises access to withdraw(), so the balance check and update happen atomically and the account never goes negative.
JDBC provides an API for connecting Java applications to relational databases.
(a) Explain the steps involved in connecting a Java program to a database using JDBC. (4)
(b) Differentiate between Statement, PreparedStatement, and CallableStatement. Why is PreparedStatement preferred to prevent SQL injection? (4)
(c) Write a complete JDBC program that connects to a Student(roll, name, marks) table in MySQL, inserts a new record, and then retrieves and displays all records whose marks are greater than 60. (4)
(a) Steps to Connect a Java Program to a Database using JDBC (4)
- Load/register the driver —
Class.forName("com.mysql.cj.jdbc.Driver")(auto-loaded in JDBC 4+). - Establish a connection —
Connection con = DriverManager.getConnection(url, user, password); - Create a statement —
Statement/PreparedStatement/CallableStatementobject from the connection. - Execute the query —
executeQuery()for SELECT (returnsResultSet) orexecuteUpdate()for INSERT/UPDATE/DELETE. - Process the
ResultSet— iterate withrs.next()and read columns. - Close the resources — close
ResultSet,Statement, andConnection(or use try-with-resources).
(b) Statement vs PreparedStatement vs CallableStatement (4)
| Feature | Statement | PreparedStatement | CallableStatement |
|---|---|---|---|
| Purpose | Static SQL | Pre-compiled, parameterised SQL | Calls stored procedures |
| Parameters | None (string concatenation) | ? placeholders set via setters | IN, OUT, INOUT params |
| Performance | Compiled every time | Compiled once, reused | Optimised for procedures |
| SQL injection | Vulnerable | Safe | Safe |
Why PreparedStatement prevents SQL injection: Parameters are bound as typed values (setString, setInt) rather than concatenated into the SQL text, so malicious input such as ' OR '1'='1 is treated as literal data, not executable SQL.
(c) JDBC Program for Student Table (4)
import java.sql.*;
public class StudentJDBC {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/school";
String user = "root", pass = "password";
try (Connection con = DriverManager.getConnection(url, user, pass)) {
// Insert a new record
String ins = "INSERT INTO Student(roll, name, marks) VALUES (?, ?, ?)";
try (PreparedStatement ps = con.prepareStatement(ins)) {
ps.setInt(1, 101);
ps.setString(2, "Ram");
ps.setInt(3, 75);
ps.executeUpdate();
}
// Retrieve students with marks > 60
String sel = "SELECT roll, name, marks FROM Student WHERE marks > ?";
try (PreparedStatement ps = con.prepareStatement(sel)) {
ps.setInt(1, 60);
ResultSet rs = ps.executeQuery();
System.out.println("Roll\tName\tMarks");
while (rs.next()) {
System.out.println(rs.getInt("roll") + "\t"
+ rs.getString("name") + "\t" + rs.getInt("marks"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Swing is used to build platform-independent graphical user interfaces in Java.
(a) Explain the delegation event model in Java with the roles of event source, event listener, and event object. (4)
(b) Design a Swing-based simple login form containing a username field, a password field, and a Login button. When the button is clicked, the program should display "Login Successful" if the username is admin and password is 1234; otherwise display "Invalid Credentials". Write the complete code including the appropriate event handler. (6)
(a) Delegation Event Model (4)
The delegation event model is the standard mechanism by which Java handles events (since JDK 1.1). An event generated by a source is delegated to one or more registered listener objects that handle it. It has three participants:
- Event Source — The GUI component (e.g. a
JButton) on which the event occurs. It maintains a list of registered listeners and creates an event object when acted upon. - Event Object — An object (e.g.
ActionEvent) that encapsulates information about the event (source, type, coordinates, etc.) and is passed to the listener. - Event Listener — An object that implements a listener interface (e.g.
ActionListener) and contains the handler method (e.g.actionPerformed()) invoked when the event occurs.
Flow: A listener registers with the source using addActionListener(listener). When the user acts, the source creates an event object and calls the listener's handler method, passing the event object.
(b) Swing Login Form (6)
import javax.swing.*;
import java.awt.event.*;
public class LoginForm extends JFrame implements ActionListener {
JTextField userField = new JTextField(15);
JPasswordField passField = new JPasswordField(15);
JButton loginBtn = new JButton("Login");
JLabel result = new JLabel("");
LoginForm() {
setLayout(null);
JLabel u = new JLabel("Username:"); u.setBounds(30, 30, 80, 25);
JLabel p = new JLabel("Password:"); p.setBounds(30, 70, 80, 25);
userField.setBounds(120, 30, 150, 25);
passField.setBounds(120, 70, 150, 25);
loginBtn.setBounds(120, 110, 90, 30);
result.setBounds(30, 150, 250, 25);
add(u); add(p); add(userField); add(passField); add(loginBtn); add(result);
loginBtn.addActionListener(this); // register listener
setSize(320, 230);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String user = userField.getText();
String pass = new String(passField.getPassword());
if (user.equals("admin") && pass.equals("1234"))
result.setText("Login Successful");
else
result.setText("Invalid Credentials");
}
public static void main(String[] args) {
new LoginForm();
}
}
The loginBtn is the event source, this (the ActionListener) is the listener, and ActionEvent e is the event object delivered to actionPerformed().
Section B: Short Answer Questions
Attempt all / any as specified.
(a) Differentiate between checked and unchecked exceptions with one example of each. (3)
(b) Explain the use of the try, catch, finally, and throw keywords. Write a program that defines a custom exception InvalidAgeException and throws it when an entered age is less than 18. (5)
(a) Checked vs Unchecked Exceptions (3)
| Aspect | Checked Exception | Unchecked Exception |
|---|---|---|
| Hierarchy | Subclass of Exception (excluding RuntimeException) | Subclass of RuntimeException |
| Detection | Checked at compile time | Occurs at runtime |
| Handling | Must be caught or declared with throws | Not enforced by the compiler |
| Example | IOException, SQLException | NullPointerException, ArithmeticException |
(b) try / catch / finally / throw + Custom Exception (5)
try— Encloses code that may throw an exception.catch— Handles a specific exception thrown inside thetryblock.finally— Always executes (whether or not an exception occurs); used for cleanup such as closing resources.throw— Used to explicitly throw an exception object.
class InvalidAgeException extends Exception {
InvalidAgeException(String msg) { super(msg); }
}
public class AgeTest {
static void validate(int age) throws InvalidAgeException {
if (age < 18)
throw new InvalidAgeException("Age " + age + " is below 18 — not eligible");
System.out.println("Valid age: " + age);
}
public static void main(String[] args) {
try {
validate(15);
} catch (InvalidAgeException e) {
System.out.println("Caught: " + e.getMessage());
} finally {
System.out.println("Validation finished");
}
}
}
Output:
Caught: Age 15 is below 18 — not eligible
Validation finished
(a) Distinguish between ArrayList and LinkedList in terms of internal structure and performance. (3)
(b) Write a Java program using the Collections framework that stores a list of student names in an ArrayList, removes duplicates by converting it to a HashSet, and finally prints the unique names in sorted order using a TreeSet. (5)
(a) ArrayList vs LinkedList (3)
| Aspect | ArrayList | LinkedList |
|---|---|---|
| Internal structure | Resizable dynamic array | Doubly linked list of nodes |
Random access (get(i)) | Fast — O(1) | Slow — O(n) (traverses nodes) |
| Insert/delete in middle | Slow — O(n) (shifting elements) | Fast — O(1) once positioned (just relink nodes) |
| Memory | Less (only data) | More (stores prev/next pointers) |
Summary: Use ArrayList for frequent random access/reads; use LinkedList for frequent insertions/deletions.
(b) ArrayList -> HashSet -> TreeSet Program (5)
import java.util.*;
public class UniqueNames {
public static void main(String[] args) {
// 1. Store names (with duplicates) in an ArrayList
ArrayList<String> names = new ArrayList<>(
Arrays.asList("Sita", "Ram", "Hari", "Sita", "Ram", "Gita"));
// 2. Remove duplicates using a HashSet
HashSet<String> set = new HashSet<>(names);
// 3. Sort by inserting into a TreeSet (natural ordering)
TreeSet<String> sorted = new TreeSet<>(set);
System.out.println("Unique sorted names: " + sorted);
}
}
Output:
Unique sorted names: [Gita, Hari, Ram, Sita]
HashSet discards duplicates; TreeSet stores the unique names in ascending (natural) sorted order.
(a) Differentiate between TCP and UDP communication in Java. Which classes are used for each? (3)
(b) Write a simple client-server program using ServerSocket and Socket where the client sends a message to the server and the server echoes the message back to the client. (5)
(a) TCP vs UDP in Java (3)
| Aspect | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented (handshake) | Connectionless |
| Reliability | Reliable, ordered, error-checked, no data loss | Unreliable, no delivery/order guarantee |
| Speed/overhead | Slower, higher overhead | Faster, low overhead |
| Use case | File transfer, HTTP, email | Streaming, gaming, DNS |
| Java classes | Socket, ServerSocket | DatagramSocket, DatagramPacket |
(b) TCP Echo Client-Server (5)
Server:
import java.io.*;
import java.net.*;
public class EchoServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(5000);
System.out.println("Server waiting...");
Socket s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
String msg = in.readLine();
System.out.println("Received: " + msg);
out.println(msg); // echo back
s.close(); ss.close();
}
}
Client:
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost", 5000);
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out.println("Hello Server"); // send
System.out.println("Echo: " + in.readLine()); // receive echo
s.close();
}
}
Run the server first, then the client; the client prints Echo: Hello Server.
(a) Explain the servlet life cycle with the role of the init(), service(), and destroy() methods. (3)
(b) Differentiate between a Servlet and a JSP. State two advantages of JSP over servlets. (3)
(a) Servlet Life Cycle (3)
The servlet container (web server) manages a servlet through three life-cycle methods:
init()— Called once when the servlet is first loaded/instantiated. Used for one-time initialisation (e.g. opening a DB connection).service()— Called for every client request. It examines the HTTP method and dispatches todoGet(),doPost(), etc. Runs in a separate thread per request.destroy()— Called once before the servlet is unloaded/removed. Used to release resources (close connections, save state).
Flow: Loading & Instantiation -> init() -> service() (repeated per request) -> destroy().
(b) Servlet vs JSP (3)
| Aspect | Servlet | JSP |
|---|---|---|
| Nature | Java class with HTML embedded in out.println() | HTML page with embedded Java |
| Focus | Better for business/control logic | Better for presentation/view |
| Coding | More code to generate HTML | Less code; HTML written directly |
| Compilation | Compiled manually | Auto-translated into a servlet by the container |
Two advantages of JSP over servlets:
- Easier presentation — HTML is written directly, so designing the view is simpler and more readable.
- Automatic recompilation / separation of concerns — JSP pages are auto-translated and recompiled when changed, and they cleanly separate presentation from logic (especially with tags/EL).
(a) Differentiate between String, StringBuffer, and StringBuilder with respect to mutability and thread safety. (3)
(b) Write a Java program that accepts a string from the user and checks whether it is a palindrome without using any built-in reverse method. (3)
(a) String vs StringBuffer vs StringBuilder (3)
| Aspect | String | StringBuffer | StringBuilder |
|---|---|---|---|
| Mutability | Immutable | Mutable | Mutable |
| Thread safety | Thread-safe (immutable) | Thread-safe (synchronized) | Not thread-safe |
| Performance | Slow for many edits (new object each time) | Slower than StringBuilder (sync overhead) | Fastest for single-threaded edits |
| Use case | Fixed/constant text | Multithreaded string editing | Single-threaded string editing |
(b) Palindrome Check Without Built-in Reverse (3)
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
boolean isPalindrome = true;
int i = 0, j = str.length() - 1;
while (i < j) {
if (str.charAt(i) != str.charAt(j)) {
isPalindrome = false;
break;
}
i++; j--;
}
System.out.println(str + (isPalindrome ? " is a palindrome" : " is not a palindrome"));
}
}
The two pointers move inward comparing characters from both ends; if all matching pairs are equal, the string is a palindrome (e.g. madam -> palindrome).
(a) What is inter-thread communication? Explain the role of the wait(), notify(), and notifyAll() methods. (3)
(b) Briefly describe the producer-consumer problem and how it can be solved in Java. (3)
(a) Inter-Thread Communication (3)
Inter-thread communication is a mechanism that lets synchronized threads cooperate by signalling one another, so a thread can pause and let another proceed instead of busy-waiting. It uses three methods of Object, called from within a synchronized block/method:
wait()— Causes the current thread to release the lock and wait until another thread callsnotify()/notifyAll()on the same object.notify()— Wakes up one waiting thread on that object's monitor.notifyAll()— Wakes up all threads waiting on that object's monitor (they then compete for the lock).
(b) Producer-Consumer Problem (3)
The producer-consumer problem is a classic synchronization problem involving a shared, bounded buffer:
- The producer generates data and places it into the buffer.
- The consumer removes and uses data from the buffer.
The challenge: the producer must wait when the buffer is full, and the consumer must wait when the buffer is empty, while both access the buffer safely.
Java solution: Use a synchronized shared buffer with wait() and notify(). The producer calls wait() when full and notify() after producing; the consumer calls wait() when empty and notify() after consuming. Alternatively, use a thread-safe BlockingQueue (e.g. ArrayBlockingQueue) whose put()/take() methods handle the blocking automatically.
Write short notes on any two of the following: (3+3)
(a) Layout managers in Swing (FlowLayout, BorderLayout, GridLayout)
(b) Difference between AWT and Swing
(c) Stage, Scene, and Node hierarchy in JavaFX
(Write any two of the following.)
(a) Layout Managers in Swing (3)
A layout manager automatically arranges components inside a container, adapting to size changes.
FlowLayout— Places components left-to-right in a row (like words in a line), wrapping to the next line when full. Default forJPanel.BorderLayout— Divides the container into five regions: NORTH, SOUTH, EAST, WEST, CENTER; each holds one component, with CENTER taking the remaining space. Default forJFrame.GridLayout— Arranges components in a grid of equal-sized cells (rows × columns), each component filling one cell.
(b) Difference between AWT and Swing (3)
| Aspect | AWT | Swing |
|---|---|---|
| Components | Heavyweight (use native OS peers) | Lightweight (pure Java) |
| Look & feel | OS-dependent | Pluggable, consistent across platforms |
| Richness | Basic components | Richer set (JTable, JTree, JTabbedPane) |
| Package | java.awt | javax.swing (classes prefixed J) |
| MVC | No | Follows MVC architecture |
(c) Stage, Scene, and Node Hierarchy in JavaFX (3)
JavaFX GUIs follow a theatre metaphor:
- Stage — The top-level container / window of the application (created by the runtime and passed to
start(Stage)). One application can have multiple stages. - Scene — The container for all visual content displayed on a stage. A stage shows one scene at a time; set with
stage.setScene(scene). - Node — Every visual element (button, label, shape, layout pane) is a
Node. Nodes are organised in a scene graph, a tree whose root node is attached to the scene; parent nodes (layout panes) contain child nodes.
Hierarchy: Stage -> Scene -> root Node -> child Nodes (scene graph).
Frequently asked questions
- Where can I find the BE Computer Engineering (Pokhara University) Advanced Programming with Java (PU, CMP 228) question paper 2078?
- The full BE Computer Engineering (Pokhara University) Advanced Programming with Java (PU, CMP 228) 2078 (regular) question paper is available free on Kekkei. You can read every question online and attempt the paper under timed exam conditions.
- Does the Advanced Programming with Java (PU, CMP 228) 2078 paper come with solutions?
- Yes. Every question on this Advanced Programming with Java (PU, CMP 228) past paper includes a step-by-step solution, plus instant AI feedback when you attempt it on Kekkei.
- How many marks is the BE Computer Engineering (Pokhara University) Advanced Programming with Java (PU, CMP 228) 2078 paper?
- The BE Computer Engineering (Pokhara University) Advanced Programming with Java (PU, CMP 228) 2078 paper carries 100 full marks and is meant to be completed in 180 minutes, across 11 questions.
- Is practising this Advanced Programming with Java (PU, CMP 228) past paper free?
- Yes — reading and attempting this Advanced Programming with Java (PU, CMP 228) past paper on Kekkei is completely free.