Browse papers
A

Section A: Long Answer Questions

Attempt any TWO questions.

3 questions·10 marks each
1long10 marks

Describe the Java event handling mechanism with appropriate examples. Write a Swing GUI program that implements a simple calculator with buttons for basic arithmetic operations.

Java Event Handling Mechanism

Java uses the Delegation Event Model. In this model, an event source (e.g. a button) generates an event object when the user interacts with it, and that object is delegated (forwarded) to one or more registered listener objects which handle it.

Key components:

  1. Event – an object that describes a state change (e.g. ActionEvent, MouseEvent, KeyEvent). It is a subclass of java.util.EventObject.
  2. Event Source – the component on which the event occurs (e.g. a JButton).
  3. Event Listener – an object that implements a listener interface (e.g. ActionListener) and contains the handler method (e.g. actionPerformed).
  4. Registration – the source registers a listener via methods like addActionListener(listener). Only registered listeners are notified.

Flow: User acts on source → JVM creates event object → source notifies all registered listeners → listener's callback executes the response.

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        System.out.println("Button clicked!");
    }
});

Swing Calculator Program

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

public class Calculator extends JFrame implements ActionListener {
    private JTextField display;
    private double num1 = 0;
    private String op = "";
    private boolean start = true;

    public Calculator() {
        setTitle("Calculator");
        setSize(300, 350);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        display = new JTextField("0");
        display.setEditable(false);
        display.setHorizontalAlignment(JTextField.RIGHT);
        display.setFont(new Font("Arial", Font.BOLD, 24));
        add(display, BorderLayout.NORTH);

        JPanel panel = new JPanel(new GridLayout(4, 4, 5, 5));
        String[] keys = {
            "7","8","9","/",
            "4","5","6","*",
            "1","2","3","-",
            "0","C","=","+"
        };
        for (String k : keys) {
            JButton b = new JButton(k);
            b.addActionListener(this);
            panel.add(b);
        }
        add(panel, BorderLayout.CENTER);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        if (cmd.matches("[0-9]")) {
            if (start) { display.setText(cmd); start = false; }
            else display.setText(display.getText() + cmd);
        } else if (cmd.equals("C")) {
            display.setText("0"); num1 = 0; op = ""; start = true;
        } else if (cmd.equals("=")) {
            double num2 = Double.parseDouble(display.getText());
            double result = 0;
            switch (op) {
                case "+": result = num1 + num2; break;
                case "-": result = num1 - num2; break;
                case "*": result = num1 * num2; break;
                case "/": result = (num2 != 0) ? num1 / num2 : 0; break;
            }
            display.setText(String.valueOf(result));
            start = true;
        } else { // operator
            num1 = Double.parseDouble(display.getText());
            op = cmd;
            start = true;
        }
    }

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

This program registers ActionListeners on every digit and operator button; clicking a button delegates the ActionEvent to actionPerformed, which performs the requested arithmetic and updates the display.

event-handlingswing
2long10 marks

What is a servlet? Explain the servlet life cycle and develop a servlet-based login application that validates credentials against a database.

What is a Servlet?

A servlet is a server-side Java program (implementing the javax.servlet.Servlet interface, usually by extending HttpServlet) that runs inside a servlet container (e.g. Tomcat) and dynamically generates responses to client requests over HTTP. Servlets are the foundation of Java web applications.

Servlet Life Cycle

The container manages a servlet through three phases:

  1. init(ServletConfig config) – Called once when the servlet is first loaded (or at startup). Used for one-time initialization such as opening a database connection pool.
  2. service(ServletRequest req, ServletResponse res) – Called for every client request. It dispatches to doGet, doPost, etc. based on the HTTP method. Runs in a separate thread per request.
  3. destroy() – Called once before the servlet is unloaded, to release resources.

Loading/instantiation happens before init; garbage collection follows destroy.

Servlet-based Login Application (DB validation)

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        res.setContentType("text/html");
        PrintWriter out = res.getWriter();

        String user = req.getParameter("username");
        String pass = req.getParameter("password");

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/appdb", "root", "secret");

            // PreparedStatement prevents SQL injection
            PreparedStatement ps = con.prepareStatement(
                "SELECT * FROM users WHERE username=? AND password=?");
            ps.setString(1, user);
            ps.setString(2, pass);
            ResultSet rs = ps.executeQuery();

            if (rs.next()) {
                HttpSession session = req.getSession();
                session.setAttribute("user", user);
                out.println("<h2>Welcome, " + user + "!</h2>");
            } else {
                out.println("<h2>Invalid credentials. Try again.</h2>");
            }
            rs.close(); ps.close(); con.close();
        } catch (Exception e) {
            out.println("Error: " + e.getMessage());
        }
    }
}

The corresponding HTML form posts username and password to this servlet. The servlet uses JDBC with a PreparedStatement to validate the credentials and creates a session on success.

servletjdbc
3long10 marks

Explain distributed programming in Java. Discuss RMI architecture and write a complete RMI program for a remote string-reversal service.

Distributed Programming in Java

Distributed programming means building applications whose components run on different machines (JVMs) connected by a network and cooperate by exchanging data/calls. Java supports it through Sockets, RMI, and CORBA. RMI (Remote Method Invocation) lets a Java object on one JVM invoke methods on an object residing in another JVM as if it were local, hiding the networking details.

RMI Architecture

RMI has three layers between the client and server:

  1. Stub/Skeleton Layer – The stub is a client-side proxy that marshals (serializes) arguments and forwards the call; the skeleton (server side, merged into the stub mechanism since Java 2) unmarshals and invokes the real method.
  2. Remote Reference Layer (RRL) – Handles the semantics of the remote reference (e.g. locating the object).
  3. Transport Layer – Manages the actual TCP/IP connection between JVMs.

The RMI Registry (rmiregistry) is a naming service where the server binds remote objects and the client looks them up.

Complete RMI String-Reversal Program

1. Remote interface

import java.rmi.*;
public interface StringService extends Remote {
    String reverse(String s) throws RemoteException;
}

2. Implementation (server object)

import java.rmi.*;
import java.rmi.server.*;
public class StringServiceImpl extends UnicastRemoteObject
        implements StringService {
    public StringServiceImpl() throws RemoteException { super(); }
    public String reverse(String s) throws RemoteException {
        return new StringBuilder(s).reverse().toString();
    }
}

3. Server (registers object)

import java.rmi.*;
import java.rmi.registry.*;
public class Server {
    public static void main(String[] args) throws Exception {
        LocateRegistry.createRegistry(1099);
        StringService obj = new StringServiceImpl();
        Naming.rebind("rmi://localhost/StringService", obj);
        System.out.println("Server ready.");
    }
}

4. Client (looks up and calls)

import java.rmi.*;
public class Client {
    public static void main(String[] args) throws Exception {
        StringService obj =
            (StringService) Naming.lookup("rmi://localhost/StringService");
        System.out.println("Reversed: " + obj.reverse("HelloWorld"));
    }
}

Run order: compile all, start the server, then run the client. Output: Reversed: dlroWolleH.

rmi
B

Section B: Short Answer Questions

Attempt any EIGHT questions.

9 questions·5 marks each
4short5 marks

Differentiate between AWT and Swing components.

AWT vs Swing

FeatureAWT (java.awt)Swing (javax.swing)
Component typeHeavyweight – each maps to a native OS peerLightweight – drawn entirely in Java (except top-level windows)
Look & FeelPlatform-dependent, fixedPluggable (PLAF); same look on all platforms
Component richnessLimited set (Button, Label, TextField…)Richer set (JTable, JTree, JTabbedPane, JToolBar…)
Performance/MemoryFaster but resource-heavy (native peers)Slightly slower but more flexible
MVCNot based on MVCFollows MVC architecture
NamingNo prefix (Button, Frame)J prefix (JButton, JFrame)

Swing is built on top of AWT and is the preferred toolkit because it is portable, more customizable, and provides advanced components.

swing
5short5 marks

Explain any three Swing layout managers.

Three Swing Layout Managers

A layout manager automatically arranges components in a container.

  1. FlowLayout – Places components in a left-to-right row in the order added; wraps to the next line when the row is full. Default for JPanel. Components keep their preferred size.

    panel.setLayout(new FlowLayout());
    
  2. BorderLayout – Divides the container into five regions: NORTH, SOUTH, EAST, WEST, CENTER. Each region holds one component; CENTER takes all remaining space. Default for JFrame's content pane.

    frame.add(button, BorderLayout.NORTH);
    
  3. GridLayout – Arranges components in a rectangular grid of equal-sized cells (specified rows × columns), filling left-to-right, top-to-bottom. Useful for keypads and forms.

    panel.setLayout(new GridLayout(3, 2));
    

(Others include GridBagLayout, BoxLayout, and CardLayout.)

layout
6short5 marks

What is the use of the ResultSet interface in JDBC?

Use of the ResultSet Interface in JDBC

The java.sql.ResultSet interface represents the table of data returned by executing a SQL SELECT query (via Statement.executeQuery() or PreparedStatement.executeQuery()). It acts as a cursor that initially points before the first row.

Main uses:

  • Iterate over rows using rs.next(), which moves the cursor forward and returns false when no more rows exist.
  • Retrieve column values by index or name using typed getters: rs.getInt("id"), rs.getString(2), rs.getDouble("salary"), etc.
  • Scrollable / updatable result sets (TYPE_SCROLL_INSENSITIVE, CONCUR_UPDATABLE) allow moving in any direction (previous(), first(), last()) and updating rows in place.
  • Provides metadata via getMetaData() (column count, names, types).
ResultSet rs = stmt.executeQuery("SELECT id, name FROM student");
while (rs.next()) {
    System.out.println(rs.getInt("id") + " : " + rs.getString("name"));
}
jdbc
7short5 marks

Explain the structure of an HTTP request and response in servlets.

Structure of HTTP Request and Response in Servlets

HTTP Request (HttpServletRequest)

An HTTP request has three parts, all accessible from the request object:

  1. Request line – method (GET/POST), URL, and HTTP version. Accessed via getMethod(), getRequestURI(), getProtocol().
  2. Header lines – metadata such as Host, User-Agent, Content-Type, cookies. Accessed via getHeader(name), getCookies().
  3. Message body – form data / payload. Accessed via getParameter(name), getParameterValues(), or getInputStream().

HTTP Response (HttpServletResponse)

The response also has three parts, set through the response object:

  1. Status line – HTTP version and status code (e.g. 200 OK, 404). Set via setStatus(code) or sendError().
  2. Header lines – e.g. Content-Type, Content-Length, cookies. Set via setContentType(), setHeader(), addCookie().
  3. Message body – the actual content written using getWriter() (text) or getOutputStream() (binary).
String user = req.getParameter("name");      // read request body
res.setContentType("text/html");             // response header
res.getWriter().println("<h1>Hi " + user + "</h1>"); // response body
servlet
8short5 marks

What is the difference between TCP and UDP socket programming?

TCP vs UDP Socket Programming

AspectTCP Socket ProgrammingUDP Socket Programming
ConnectionConnection-oriented (handshake before data)Connectionless (no handshake)
ReliabilityReliable – guarantees delivery, ordering, no duplicatesUnreliable – no guarantee of delivery or order
Java classesSocket, ServerSocketDatagramSocket, DatagramPacket
Data unitContinuous byte streamIndependent datagrams (packets)
Speed/OverheadSlower, higher overhead (acks, flow control)Faster, lightweight, low overhead
Use casesWeb, email, file transfer, loginStreaming, DNS, online games, VoIP

TCP example (server side):

ServerSocket ss = new ServerSocket(5000);
Socket s = ss.accept();           // blocks until a client connects

UDP example (server side):

DatagramSocket ds = new DatagramSocket(5000);
byte[] buf = new byte[1024];
DatagramPacket p = new DatagramPacket(buf, buf.length);
ds.receive(p);                    // no connection established
socket
9short5 marks

Describe the role of web.xml in a servlet application.

Role of web.xml in a Servlet Application

web.xml is the deployment descriptor of a Java web application, located in the WEB-INF directory. It is an XML file read by the servlet container (e.g. Tomcat) at startup to configure the web application.

Main roles:

  • Servlet declaration & mapping – registers each servlet (<servlet>) and maps it to a URL pattern (<servlet-mapping>), so requests are routed to the right servlet.
  • Initialization parameters – defines <init-param> (per-servlet) and <context-param> (application-wide).
  • Welcome files – specifies default pages via <welcome-file-list>.
  • Filters and listeners – registers <filter> and <listener> components.
  • Session config & error pages – sets session timeout and <error-page> mappings.
  • Security constraints – defines roles and protected resources.
<servlet>
  <servlet-name>login</servlet-name>
  <servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>login</servlet-name>
  <url-pattern>/login</url-pattern>
</servlet-mapping>

In modern (Servlet 3.0+) apps, much of this can instead be done with annotations like @WebServlet, making web.xml optional.

servlet
10short5 marks

Explain scriptlets, expressions, and declarations in JSP.

Scriptlets, Expressions, and Declarations in JSP

JSP scripting elements embed Java code in HTML pages.

  1. Scriptlet <% ... %> – Contains arbitrary Java statements that are placed inside the generated servlet's _jspService() method. Used for logic such as loops and conditionals.

    <% for (int i = 1; i <= 3; i++) { %>
        <p>Line <%= i %></p>
    <% } %>
    
  2. Expression <%= ... %> – Evaluates a single Java expression, converts it to a String, and writes it directly to the output. No semicolon is used.

    <p>Today is <%= new java.util.Date() %></p>
    
  3. Declaration <%! ... %> – Declares instance variables and methods at the class level of the generated servlet (outside _jspService()). Used to define fields/methods reused across the page.

    <%! int counter = 0;
        int square(int x) { return x * x; } %>
    

Summary: scriptlets → statements (method body); expressions → inline output; declarations → class-level members.

jsp
11short5 marks

What is the purpose of the rebind() method in RMI?

Purpose of the rebind() Method in RMI

rebind() (from java.rmi.Naming or java.rmi.registry.Registry) binds a remote object to a name in the RMI registry, so that clients can later locate it using Naming.lookup().

Naming.rebind("rmi://localhost/StringService", remoteObj);

Key points:

  • It associates a logical name (URL) with a remote object reference in the registry's naming service.
  • Unlike bind(), which throws an AlreadyBoundException if the name is already in use, rebind() silently replaces any existing binding for that name. This makes it safe to restart the server without unbinding first.
  • It is called on the server side during setup, before clients perform a lookup.

Thus rebind() is preferred over bind() in most server programs because it avoids errors on re-registration.

rmi
12short5 marks

Write short notes on exception handling in JDBC.

Exception Handling in JDBC

JDBC operations can fail (driver missing, bad SQL, connection lost), so they must be wrapped in exception handling.

Key exceptions:

  • SQLException – The principal checked exception thrown by almost all JDBC methods (connection, statement, result-set operations). It carries useful diagnostics: getMessage(), getErrorCode() (vendor code), and getSQLState() (XOPEN/SQL:2003 state code).
  • ClassNotFoundException – Thrown by Class.forName() if the JDBC driver class is not on the classpath.
  • Chained exceptions – Multiple errors can be traversed via getNextException().

Best practices:

  • Use try-catch-finally (or try-with-resources) to guarantee that Connection, Statement, and ResultSet are closed even when an error occurs, preventing resource leaks.
  • Combine with transaction handling: call rollback() in the catch block and commit() on success.
try (Connection con = DriverManager.getConnection(url, u, p);
     PreparedStatement ps = con.prepareStatement(sql)) {
    ps.executeUpdate();
} catch (SQLException e) {
    System.out.println("State: " + e.getSQLState()
        + ", Code: " + e.getErrorCode() + ", " + e.getMessage());
}

Try-with-resources auto-closes the resources, so an explicit finally block is no longer needed.

jdbc

Frequently asked questions

Where can I find the BSc CSIT (TU) Advanced Java Programming (BSc CSIT, CSC409) question paper 2080?
The full BSc CSIT (TU) Advanced Java Programming (BSc CSIT, CSC409) 2080 (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) 2080 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) 2080 paper?
The BSc CSIT (TU) Advanced Java Programming (BSc CSIT, CSC409) 2080 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.