Browse papers
A

Section A: Long Answer Questions

Attempt any TWO questions.

3 questions·10 marks each
1long10 marks

Explain GUI programming using Swing. Discuss the component hierarchy and write a program to build a registration form with validation using Swing components.

GUI Programming using Swing

Swing is a part of Java Foundation Classes (JFC) built on top of AWT. Unlike AWT's heavyweight components (which depend on the native OS peer), Swing components are lightweight (written entirely in Java, drawn by the JVM), making them platform-independent and consistent across operating systems. Swing follows the MVC (Model-View-Controller) architecture and provides a rich set of components (buttons, tables, trees, etc.) in the javax.swing package.

Key features: pluggable look-and-feel, lightweight components, MVC architecture, large component set, and it is not thread-safe (GUI updates must run on the Event Dispatch Thread).

Swing Component Hierarchy

All Swing components ultimately derive from AWT classes:

java.lang.Object
  └── java.awt.Component
        └── java.awt.Container
              ├── java.awt.Window
              │     └── java.awt.Frame
              │           └── javax.swing.JFrame   (top-level container)
              └── javax.swing.JComponent           (base of all lightweight components)
                    ├── JButton, JLabel, JTextField, JPasswordField
                    ├── JCheckBox, JRadioButton, JComboBox, JList
                    ├── JPanel, JScrollPane, JTable, JTree ...
  • Top-level containers: JFrame, JDialog, JApplet — these can be displayed independently.
  • Intermediate containers: JPanel, JScrollPane — group other components.
  • Atomic components: JButton, JLabel, JTextField, etc. — JComponent is the parent of all of them.

Registration Form with Validation

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class RegistrationForm extends JFrame implements ActionListener {
    JTextField nameField = new JTextField(15);
    JTextField emailField = new JTextField(15);
    JPasswordField passField = new JPasswordField(15);
    JButton submit = new JButton("Register");
    JLabel message = new JLabel("");

    public RegistrationForm() {
        setLayout(new GridLayout(5, 2, 5, 5));
        add(new JLabel("Name:"));     add(nameField);
        add(new JLabel("Email:"));    add(emailField);
        add(new JLabel("Password:")); add(passField);
        add(submit);                  add(message);
        submit.addActionListener(this);
        setTitle("Registration");
        setSize(350, 200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        String name = nameField.getText().trim();
        String email = emailField.getText().trim();
        String pass = new String(passField.getPassword());
        if (name.isEmpty() || email.isEmpty() || pass.isEmpty()) {
            message.setText("All fields are required");
        } else if (!email.matches("^[\\w.]+@[\\w.]+\\.[a-z]{2,}$")) {
            message.setText("Invalid email");
        } else if (pass.length() < 6) {
            message.setText("Password must be 6+ chars");
        } else {
            message.setText("Registration successful!");
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(RegistrationForm::new);
    }
}

The form uses a GridLayout, captures user input, and validates for empty fields, a valid email pattern (regex), and minimum password length before reporting success.

swinggui
2long10 marks

What is JDBC? Explain the JDBC API in detail and write a program that performs insert, update, and delete operations on a database table.

What is JDBC?

JDBC (Java Database Connectivity) is a Java API that enables Java programs to connect to and execute operations on relational databases in a database-independent manner. It provides a standard set of interfaces (in java.sql and javax.sql) so the same code can work with different databases by swapping the driver.

JDBC API in Detail

The core interfaces/classes of the JDBC API are:

ComponentPurpose
DriverManagerManages drivers and establishes a connection via getConnection().
DriverThe database-specific driver implementation.
ConnectionRepresents a session with the database; used to create statements and manage transactions.
StatementExecutes static SQL queries.
PreparedStatementExecutes pre-compiled, parameterized SQL (prevents SQL injection).
CallableStatementExecutes stored procedures.
ResultSetHolds the rows returned by a query; navigated with next().
SQLExceptionHandles database access errors.

Standard steps to use JDBC: (1) load/register the driver, (2) establish a Connection, (3) create a Statement/PreparedStatement, (4) execute the SQL (executeQuery for SELECT, executeUpdate for INSERT/UPDATE/DELETE), (5) process the ResultSet, (6) close the resources.

Program: Insert, Update, and Delete

import java.sql.*;

public class CrudDemo {
    public static void main(String[] args) throws Exception {
        String url = "jdbc:mysql://localhost:3306/college";
        String user = "root", pass = "root";

        Class.forName("com.mysql.cj.jdbc.Driver");           // 1. load driver
        try (Connection con = DriverManager.getConnection(url, user, pass)) {  // 2. connect

            // INSERT
            PreparedStatement ins = con.prepareStatement(
                "INSERT INTO student(id, name) VALUES (?, ?)");
            ins.setInt(1, 101);
            ins.setString(2, "Ram");
            System.out.println("Inserted: " + ins.executeUpdate());

            // UPDATE
            PreparedStatement upd = con.prepareStatement(
                "UPDATE student SET name = ? WHERE id = ?");
            upd.setString(1, "Ram Bahadur");
            upd.setInt(2, 101);
            System.out.println("Updated: " + upd.executeUpdate());

            // DELETE
            PreparedStatement del = con.prepareStatement(
                "DELETE FROM student WHERE id = ?");
            del.setInt(1, 101);
            System.out.println("Deleted: " + del.executeUpdate());
        }
    }
}

executeUpdate() returns the number of affected rows; using PreparedStatement parameterizes values and protects against SQL injection.

jdbcdatabase
3long10 marks

Explain Servlet and JSP technology. Differentiate between them and develop a JSP-based MVC application skeleton with a servlet controller.

Servlet Technology

A Servlet is a server-side Java class that runs inside a web container (e.g., Tomcat) and handles HTTP requests/responses dynamically. It extends HttpServlet and overrides doGet()/doPost(). Servlets are robust and well-suited for control logic but mixing HTML inside out.println() is tedious.

JSP Technology

JSP (JavaServer Pages) lets you embed Java code in HTML using tags (<% %>, <%= %>, EL ${}). A JSP is automatically translated into a servlet by the container at first request. JSP is best for presentation (view).

Differences

AspectServletJSP
NatureJava class with embedded HTMLHTML page with embedded Java
Best forBusiness logic / controllerPresentation / view
ModificationRecompile requiredAuto-recompiled on change
Coding effortMore for HTML outputLess, designer-friendly
ExecutionRuns directlyTranslated to a servlet first

JSP-based MVC Application Skeleton

In the MVC pattern (Model 2): the Servlet acts as Controller, JavaBeans/POJOs as Model, and JSP as View.

Model — User.java

public class User {
    private String name;
    public User(String name) { this.name = name; }
    public String getName() { return name; }
}

Controller — ControllerServlet.java

@WebServlet("/greet")
public class ControllerServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        String name = req.getParameter("name");
        User user = new User(name);                 // build model
        req.setAttribute("user", user);             // store in request scope
        RequestDispatcher rd = req.getRequestDispatcher("result.jsp");
        rd.forward(req, res);                       // forward to view
    }
}

View — result.jsp

<html><body>
  <h2>Welcome, ${user.name}!</h2>
</body></html>

The browser submits a form to /greet; the servlet (controller) creates the model and forwards to the JSP (view), achieving clean separation of concerns.

servletjspmvc
B

Section B: Short Answer Questions

Attempt any EIGHT questions.

9 questions·5 marks each
4short5 marks

What is the delegation event model? List its components.

The delegation event model is the event-handling mechanism used in Java (AWT/Swing) where an event generated by a source is delegated to one or more registered listener objects, which contain the logic to handle it. The source notifies listeners only if they have registered with it, making event handling efficient and modular.

Components:

  1. Event Source — the object (e.g., a JButton) that generates an event.
  2. Event Object — encapsulates information about the event (e.g., ActionEvent, MouseEvent), subclass of java.util.EventObject.
  3. Event Listener — an object that implements a listener interface (e.g., ActionListener) and is registered with the source (via addActionListener()) to receive and handle the event through its callback method (e.g., actionPerformed()).
event-handling
5short5 marks

Explain the JList and JComboBox components.

JList

JList is a Swing component that displays a list of items from which the user can select one or more (single or multiple selection mode). It does not provide its own scrolling, so it is usually placed inside a JScrollPane. Selection is read with getSelectedValue() / getSelectedValuesList(), and changes are tracked with a ListSelectionListener.

String[] items = {"Java", "C++", "Python"};
JList<String> list = new JList<>(items);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
add(new JScrollPane(list));

JComboBox

JComboBox is a drop-down list that combines a button/text field with a list. The user can select only one item at a time, and it can optionally be made editable. It fires an ActionEvent/ItemEvent on selection, and the chosen item is fetched with getSelectedItem().

String[] items = {"Java", "C++", "Python"};
JComboBox<String> combo = new JComboBox<>(items);
add(combo);

Key difference: JList shows multiple items at once and supports multiple selection; JComboBox shows one item with a drop-down and allows only single selection while saving screen space.

swing
6short5 marks

What are the steps to load a JDBC driver?

Steps to Load a JDBC Driver

  1. Add the driver JAR to the classpath so the driver class is available at runtime (e.g., mysql-connector-j.jar).

  2. Load/register the driver class using Class.forName(), which loads the class and its static initializer registers it with DriverManager:

Class.forName("com.mysql.cj.jdbc.Driver");

(Since JDBC 4.0, drivers on the classpath are auto-loaded via the Service Provider mechanism, so this line is often optional.)

  1. Establish the connection through DriverManager, which selects the appropriate registered driver based on the JDBC URL:
Connection con = DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/college", "root", "root");

Thus the typical sequence is: add driver to classpath → register with Class.forName() → obtain a Connection from DriverManager.

jdbc
7short5 marks

Differentiate between cookies and HttpSession.

Cookies vs HttpSession

AspectCookieHttpSession
Storage locationOn the client (browser)On the server
Data type storedOnly text/String key-value pairsAny Java object (as attributes)
SecurityLess secure (visible/editable by client)More secure (data stays on server)
CapacityLimited (~4 KB per cookie)Practically large (server memory)
DependencyIndependent of sessionOften uses a cookie (JSESSIONID) or URL rewriting to track the session
LifetimeCan persist after browser closes (setMaxAge)Ends on timeout, invalidate(), or browser close

Cookie example: response.addCookie(new Cookie("user", "Ram"));

Session example: HttpSession s = request.getSession(); s.setAttribute("user", userObj);

In short, cookies store small text data on the client, whereas HttpSession stores arbitrary objects on the server and is more secure, typically identifying the client via a JSESSIONID cookie.

servletsession
8short5 marks

What is a proxy server? How is it relevant to socket programming?

Proxy Server

A proxy server is an intermediary server that sits between a client and a destination server. The client sends its request to the proxy, which forwards it to the target server, receives the response, and relays it back to the client. Thus the proxy acts on behalf of the client (or server).

Common purposes: caching frequently requested content (faster access, reduced bandwidth), filtering/blocking content, providing anonymity by hiding the client's real IP, load balancing, and enforcing security policies (firewall).

Relevance to Socket Programming

In Java socket programming, a client normally opens a Socket directly to the destination host and port. When a proxy is involved:

  • The client opens a socket to the proxy instead of directly to the target server, and the proxy maintains its own socket connection to the actual server — effectively two socket connections bridged by the proxy.
  • A proxy can itself be implemented as a socket program: it uses a ServerSocket to accept client connections and a Socket to connect onward to the real server, copying byte streams between the two in both directions.
  • Java applications can route socket traffic through a proxy using the java.net.Proxy class (e.g., new Proxy(Proxy.Type.SOCKS, addr)) or system properties like socksProxyHost.

Hence a proxy is highly relevant: it is both a use case of, and an intermediary within, socket-level communication.

socket
9short5 marks

Explain marshalling and unmarshalling in RMI.

Marshalling and Unmarshalling in RMI

In Java RMI (Remote Method Invocation), a method call is made on a remote object that lives in a different JVM, so the arguments and return values must be transmitted across the network as a byte stream.

Marshalling is the process of converting (packing) the method parameters and objects into a serialized byte stream so they can be transmitted over the network. On the client side, the stub marshals the call's arguments; on the server side, the skeleton marshals the return value. It relies on Java serialization (objects must implement Serializable; remote references use the Remote interface).

Unmarshalling is the reverse process of reconstructing (unpacking) the original objects/parameters from the received byte stream. On the server side, the skeleton unmarshals the incoming arguments before invoking the actual method; on the client side, the stub unmarshals the returned result.

Flow: Client → stub marshals args → network → server skeleton unmarshals args → method executes → skeleton marshals result → network → client stub unmarshals result.

Together, marshalling/unmarshalling make remote method calls appear local to the programmer by handling object serialization transparently.

rmi
10short5 marks

What are the JSP implicit objects available for scope handling?

JSP Implicit Objects for Scope Handling

JSP provides nine implicit objects; four of them correspond to the four attribute scopes used to store and share data, from narrowest to widest:

  1. pageContext (page scope) — attributes available only within the current JSP page. pageContext.setAttribute(...).
  2. request (request scope) — attributes shared across all components handling a single client request (e.g., a servlet forwarding to a JSP). Type: HttpServletRequest.
  3. session (session scope) — attributes that persist across multiple requests from the same user/session. Type: HttpSession.
  4. application (application scope) — attributes shared by all users of the entire web application (the ServletContext). Type: ServletContext.

Data is stored/retrieved with setAttribute() / getAttribute(). The pageContext object can also access the other scopes via pageContext.getAttribute(name, scope).

Scope order (increasing visibility): page → request → session → application.

jsp
11short5 marks

Explain batch processing in JDBC.

Batch Processing in JDBC

Batch processing allows grouping multiple SQL statements (typically INSERT/UPDATE/DELETE) into a single batch and sending them to the database in one network round trip, instead of executing each individually. This dramatically improves performance when many similar operations are required.

Key methods:

  • addBatch(sql) — adds an SQL statement (Statement) or the current parameter set (PreparedStatement) to the batch.
  • executeBatch() — submits the whole batch for execution; returns an int[] of update counts.
  • clearBatch() — clears the accumulated batch.

Example with PreparedStatement:

con.setAutoCommit(false);
PreparedStatement ps = con.prepareStatement(
    "INSERT INTO student(id, name) VALUES (?, ?)");
for (int i = 1; i <= 100; i++) {
    ps.setInt(1, i);
    ps.setString(2, "Student" + i);
    ps.addBatch();           // add to batch
}
int[] counts = ps.executeBatch();   // execute all at once
con.commit();

Advantages: fewer database round trips, better performance, and (with setAutoCommit(false) + commit()) atomic execution of the group. executeBatch() returns an array of affected-row counts for each statement; failures throw a BatchUpdateException.

jdbc
12short5 marks

Write short notes on the ServerSocket class.

ServerSocket Class

The java.net.ServerSocket class implements the server side of a TCP connection. It listens on a specified port for incoming client connection requests and creates a Socket for each accepted client, enabling two-way communication.

Constructor: ServerSocket(int port) — binds the server to the given port (the port a client must connect to).

Important methods:

  • accept() — blocks until a client connects, then returns a Socket for communicating with that client.
  • close() — closes the server socket.
  • getInetAddress(), getLocalPort() — return binding information.
  • setSoTimeout(int ms) — sets a timeout for accept().

Typical usage:

ServerSocket server = new ServerSocket(5000);
System.out.println("Waiting for client...");
Socket client = server.accept();          // blocks until a client connects
BufferedReader in = new BufferedReader(
    new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
out.println("Hello from server");
server.close();

Thus ServerSocket is the entry point for building TCP server applications; accept() is the heart of the class, returning a connected Socket per client (often handled in a separate thread for concurrent clients).

socket

Frequently asked questions

Where can I find the BSc CSIT (TU) Advanced Java Programming (BSc CSIT, CSC409) question paper 2081?
The full BSc CSIT (TU) Advanced Java Programming (BSc CSIT, CSC409) 2081 (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 Java Programming (BSc CSIT, CSC409) 2081 paper come with solutions?
Yes. Every question on this Advanced Java Programming (BSc CSIT, CSC409) past paper includes a step-by-step solution, plus instant AI feedback when you attempt it on Kekkei.
How many marks is the BSc CSIT (TU) Advanced Java Programming (BSc CSIT, CSC409) 2081 paper?
The BSc CSIT (TU) Advanced Java Programming (BSc CSIT, CSC409) 2081 paper carries 60 full marks and is meant to be completed in 180 minutes, across 12 questions.
Is practising this Advanced Java Programming (BSc CSIT, CSC409) past paper free?
Yes — reading and attempting this Advanced Java Programming (BSc CSIT, CSC409) past paper on Kekkei is completely free.