Browse papers
A

Section A: Long Answer Questions

Attempt any TWO questions.

3 questions·10 marks each
1long10 marks

Compare AWT with Swing. Explain the MVC architecture used in Swing components with a suitable diagram.

AWT vs Swing

FeatureAWT (Abstract Window Toolkit)Swing
Packagejava.awtjavax.swing
Component typeHeavyweight – relies on native OS peersLightweight – drawn in pure Java
Look & FeelPlatform-dependentPluggable Look and Feel (PLAF), consistent across platforms
ComponentsLimited (Button, Label, TextField, etc.)Rich set (JTable, JTree, JTabbedPane, JSlider, etc.)
ArchitectureNo formal MVCBased on MVC
PrefixNo prefixClass names start with J (JButton, JLabel)
Memory/SpeedFaster but OS-dependentSlightly heavier but more flexible
Pluggable renderingNoYes

Swing is built on top of AWT (it still uses the AWT event model and containers like the top-level JFrame).

MVC Architecture in Swing

Swing uses a modified MVC (Model–View–Controller) design, often called the Separable Model Architecture, where the View and Controller are combined into a single UI Delegate because they are tightly coupled.

  • Model – stores the data and state of the component, independent of its appearance. Example: DefaultTableModel for JTable, ButtonModel for JButton.
  • View – renders the model on screen (the visual representation).
  • Controller – handles user input/events and updates the model.

In Swing the View + Controller are merged into the UI Delegate (e.g. BasicButtonUI), which is responsible for both painting the component and handling events. This separation lets the same model drive different look-and-feels.

Diagram (described)

        +-----------+   updates    +-----------+
        |  Model    |<-------------| Controller|
        | (data /   |              | (handles  |
        |  state)   |--- notify -->|  events)  |
        +-----------+              +-----------+
              | provides data            ^
              v                          | user input
        +-----------+                    |
        |   View    |--------------------+
        | (renders) |
        +-----------+

In Swing:  View + Controller  =  UI Delegate (PLAF)

When the model changes, it fires events to registered listeners; the UI delegate (view) repaints; user actions captured by the delegate (controller) update the model again. This loose coupling allows multiple views of the same data and pluggable look-and-feel.

swingmvc
2long10 marks

What is JSP? Explain the JSP life cycle and the different JSP scripting elements with examples.

JSP (JavaServer Pages)

JSP is a server-side technology that allows embedding Java code inside HTML using special tags to build dynamic web pages. A JSP page is automatically translated into a servlet by the web container (e.g. Tomcat) and then compiled and executed. It simplifies separating presentation (HTML) from business logic.

JSP Life Cycle

The container manages a JSP through these phases:

  1. Translation – the .jsp file is converted into a Java servlet source (.java).
  2. Compilation – the servlet source is compiled into a .class file.
  3. Class Loading & Instantiation – the servlet class is loaded and an object is created.
  4. InitializationjspInit() is called once to initialize the page.
  5. Request Processing – for each client request, _jspService(request, response) is invoked (this is auto-generated and cannot be overridden).
  6. DestructionjspDestroy() is called once before the JSP is removed, to release resources.
.jsp --> translate --> .java(servlet) --> compile --> .class
      --> load/instantiate --> jspInit() --> _jspService() [per request] --> jspDestroy()

JSP Scripting Elements

ElementSyntaxPurpose
Scriptlet<% java code %>Executes Java statements during request processing
Expression<%= expression %>Evaluates and outputs the value into the response
Declaration<%! declaration %>Declares methods/variables at class level

Examples:

<%-- Declaration: declares a class-level variable/method --%>
<%! int counter = 0;
    int square(int n){ return n*n; } %>

<%-- Scriptlet: runs Java code --%>
<% counter++;
   String name = request.getParameter("name"); %>

<%-- Expression: prints a value --%>
<p>Hello <%= name %>, this page was hit <%= counter %> times.</p>
<p>Square of 5 = <%= square(5) %></p>
jsp
3long10 marks

Explain socket programming in Java. Write a client-server program using TCP sockets where the server echoes the message sent by the client.

Socket Programming in Java

A socket is an endpoint of a two-way communication link between two programs running over a network, identified by an IP address + port number. Java provides socket classes in the java.net package:

  • ServerSocket – used on the server to listen on a port and accept() incoming connections.
  • Socket – represents a connection endpoint on both client and server; provides getInputStream() / getOutputStream() for data exchange.

TCP sockets give a reliable, connection-oriented, ordered byte stream (handshake before data transfer).

TCP Echo Server

import java.io.*;
import java.net.*;

public class EchoServer {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(5000);
        System.out.println("Server listening on port 5000...");
        Socket socket = server.accept();           // wait for client
        BufferedReader in = new BufferedReader(
            new InputStreamReader(socket.getInputStream()));
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

        String line;
        while ((line = in.readLine()) != null) {
            System.out.println("Received: " + line);
            out.println("Echo: " + line);          // send message back
            if (line.equalsIgnoreCase("bye")) break;
        }
        socket.close();
        server.close();
    }
}

TCP Client

import java.io.*;
import java.net.*;

public class EchoClient {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 5000);
        BufferedReader in = new BufferedReader(
            new InputStreamReader(socket.getInputStream()));
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader user = new BufferedReader(
            new InputStreamReader(System.in));

        String msg;
        while ((msg = user.readLine()) != null) {
            out.println(msg);                        // send to server
            System.out.println("Server: " + in.readLine()); // print echo
            if (msg.equalsIgnoreCase("bye")) break;
        }
        socket.close();
    }
}

How to run: start EchoServer first, then EchoClient; whatever the client types is sent to the server, which returns it prefixed with Echo:.

socket
B

Section B: Short Answer Questions

Attempt any EIGHT questions.

9 questions·5 marks each
4short5 marks

Explain adapter classes in Java event handling.

Adapter Classes in Java Event Handling

An adapter class is an abstract class that provides empty (default) implementations of all the methods of a corresponding event-listener interface. They exist in java.awt.event and javax.swing.event.

Purpose: Many listener interfaces (e.g. WindowListener, MouseListener, KeyListener) declare multiple methods. If a class implements the interface directly, it must implement all methods even if it needs only one. Adapter classes solve this by letting you extend the adapter and override only the method(s) you actually need, avoiding empty stub methods.

Examples of adapters: WindowAdapter, MouseAdapter, KeyAdapter, FocusAdapter, MouseMotionAdapter.

frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {  // override only this
        System.exit(0);
    }
});

Here WindowListener has 7 methods, but using WindowAdapter we override just windowClosing(). Adapters are commonly used as anonymous inner classes.

event-handling
5short5 marks

What is the use of the JTable component? Explain.

JTable Component

JTable (in javax.swing) is a Swing component used to display and edit two-dimensional data in a tabular form of rows and columns, such as records from a database.

Uses / Features:

  • Presents data in a grid of rows and columns with column headers.
  • Supports editing of cells, selection of rows/cells, and sorting.
  • Follows MVC: data is held in a TableModel (commonly DefaultTableModel), separating data from display.
  • Typically placed inside a JScrollPane so column headers show and the table scrolls.
  • Supports custom cell renderers and editors.

Example:

String[] cols = {"ID", "Name", "Marks"};
Object[][] data = {
    {1, "Ram", 85},
    {2, "Sita", 90}
};
JTable table = new JTable(data, cols);
JScrollPane sp = new JScrollPane(table); // adds scrolling + header
frame.add(sp);

Thus JTable is ideal for showing structured records (e.g. query results, reports) in a GUI.

swing
6short5 marks

Discuss the steps involved in connecting to a database using JDBC.

Steps to Connect to a Database using JDBC

JDBC (Java Database Connectivity) provides a standard API to interact with relational databases. The standard steps are:

  1. Import the JDBC packageimport java.sql.*;
  2. Load / register the driverClass.forName("com.mysql.cj.jdbc.Driver"); (optional since JDBC 4.0 with auto-loading).
  3. Establish the connection – obtain a Connection from DriverManager:
    Connection con = DriverManager.getConnection(
        "jdbc:mysql://localhost:3306/college", "root", "password");
    
  4. Create a statementStatement st = con.createStatement(); (or PreparedStatement for parameterized queries).
  5. Execute the query
    • executeQuery() for SELECT → returns a ResultSet.
    • executeUpdate() for INSERT/UPDATE/DELETE → returns affected row count.
    ResultSet rs = st.executeQuery("SELECT * FROM student");
    
  6. Process the ResultSet
    while (rs.next()) {
        System.out.println(rs.getInt("id") + " " + rs.getString("name"));
    }
    
  7. Close the connections – release resources: rs.close(); st.close(); con.close();

These steps move data between the Java application and the database through the JDBC driver.

jdbc
7short5 marks

What is a cookie? How is it used for session management?

Cookie

A cookie is a small piece of information (a name–value pair) that a server sends to the client browser, which stores it and sends it back with subsequent requests to the same server. In Java servlets it is represented by the javax.servlet.http.Cookie class.

Use in Session Management

HTTP is stateless – it does not remember a client between requests. Cookies provide one way to maintain state/session by storing a unique identifier on the client.

Mechanism:

  1. On the first request, the server creates a cookie (e.g. a session id or user data) and adds it to the response:
    Cookie c = new Cookie("user", "ram");
    c.setMaxAge(3600);            // lives 1 hour
    response.addCookie(c);
    
  2. The browser stores the cookie and automatically sends it back with every later request to that server.
  3. The server reads it to recognize the returning client:
    Cookie[] cookies = request.getCookies();
    for (Cookie ck : cookies)
        if (ck.getName().equals("user"))
            name = ck.getValue();
    

Thus cookies let the server track logged-in users, shopping carts, and preferences across requests. (The container's HttpSession itself often uses a JSESSIONID cookie under the hood.)

servletcookie
8short5 marks

Differentiate between GenericServlet and HttpServlet.

GenericServlet vs HttpServlet

AspectGenericServletHttpServlet
Packagejavax.servletjavax.servlet.http
ProtocolProtocol-independent (any protocol)HTTP-specific
Class typeAbstract class implementing Servlet & ServletConfigAbstract class extends GenericServlet
Key methodMust override service(ServletRequest, ServletResponse)Provides service() that dispatches to doGet(), doPost(), doPut(), doDelete(), etc.
Request/ResponseServletRequest / ServletResponseHttpServletRequest / HttpServletResponse
UsageRarely used directly; generic servicesStandard choice for web applications

Summary: GenericServlet defines a protocol-independent servlet where you implement a single service() method, whereas HttpServlet is its subclass specialized for HTTP, offering convenient doGet()/doPost() handler methods. In practice almost all web servlets extend HttpServlet.

servlet
9short5 marks

Explain the role of the stub and skeleton in RMI.

Role of Stub and Skeleton in RMI

RMI (Remote Method Invocation) lets a Java program invoke methods on an object located in another JVM. The stub and skeleton are the proxy objects that make a remote call look like a local one by handling communication and marshalling (serialization of parameters/return values).

Stub (client side)

  • A proxy for the remote object that resides on the client.
  • When the client calls a remote method, the stub marshals (packs/serializes) the parameters, initiates a connection, and sends the request to the server JVM.
  • It then unmarshals the result returned by the server and gives it back to the client.
  • Makes the remote call transparent — client treats it like a local object.

Skeleton (server side)

  • A server-side entity that receives the request from the stub.
  • It unmarshals the incoming parameters, invokes the actual method on the real remote object, and marshals the return value to send back to the stub.
Client ---> Stub --(marshal/network)--> Skeleton ---> Remote Object
Client <--- Stub <--(unmarshal/network)-- Skeleton <--- (result)

Note: Since Java 2 SDK 1.2 (and especially from Java 5), the skeleton is no longer required — the server side uses generic reflective dispatch — but conceptually the stub/skeleton model explains how RMI communication works.

rmi
10short5 marks

What are JSP directives? List and explain.

JSP Directives

JSP directives are messages that give instructions to the JSP container about how to translate and process the page. They affect the overall structure of the generated servlet, not the response output directly. General syntax:

<%@ directiveName attribute="value" %>

There are three JSP directives:

1. page directive

Defines page-level attributes such as language, imports, content type, error handling, buffering, and session.

<%@ page language="java" import="java.util.*"
         contentType="text/html" errorPage="error.jsp" %>

Common attributes: import, contentType, errorPage, isErrorPage, session, buffer, isThreadSafe.

2. include directive

Includes the content of another file (static include) at translation time — the included file's content is merged into the JSP before compilation.

<%@ include file="header.jsp" %>

3. taglib directive

Declares a custom tag library (or JSTL) so its tags can be used in the page.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

These let developers configure the page, reuse content, and use custom/JSTL tags.

jsp
11short5 marks

Write a Java program using RMI to find the product of two numbers.

RMI Program to Find Product of Two Numbers

An RMI application has four parts: the remote interface, the implementation, the server, and the client.

1. Remote Interface

import java.rmi.*;
public interface Product extends Remote {
    int multiply(int a, int b) throws RemoteException;
}

2. Implementation Class

import java.rmi.*;
import java.rmi.server.*;
public class ProductImpl extends UnicastRemoteObject implements Product {
    public ProductImpl() throws RemoteException { super(); }
    public int multiply(int a, int b) throws RemoteException {
        return a * b;
    }
}

3. Server

import java.rmi.*;
import java.rmi.registry.*;
public class ProductServer {
    public static void main(String[] args) throws Exception {
        Product stub = new ProductImpl();
        Registry reg = LocateRegistry.createRegistry(1099);
        reg.rebind("ProductService", stub);
        System.out.println("Server ready...");
    }
}

4. Client

import java.rmi.*;
import java.rmi.registry.*;
public class ProductClient {
    public static void main(String[] args) throws Exception {
        Registry reg = LocateRegistry.getRegistry("localhost", 1099);
        Product p = (Product) reg.lookup("ProductService");
        System.out.println("Product = " + p.multiply(6, 7)); // 42
    }
}

Steps to run: compile all files → start rmiregistry (or create it in code as above) → run ProductServer → run ProductClient, which prints Product = 42.

rmi
12short5 marks

What is the difference between doGet() and doPost() methods?

doGet() vs doPost()

Both are methods of HttpServlet that handle client requests, but they correspond to different HTTP methods.

AspectdoGet()doPost()
HTTP methodHandles GET requestsHandles POST requests
Data locationParameters appended to the URL (query string)Parameters sent in the request body
VisibilityData visible in URL/address barData hidden from URL
Data sizeLimited (URL length limit)Practically unlimited
Bookmark/CacheCan be bookmarked and cachedCannot be bookmarked/cached
SecurityLess secure (data exposed)More secure for sensitive data (e.g. passwords)
IdempotencyShould be idempotent / read-onlyUsed to modify server state (insert/update)
protected void doGet(HttpServletRequest req, HttpServletResponse res) { ... }
protected void doPost(HttpServletRequest req, HttpServletResponse res) { ... }

Summary: Use doGet() for retrieving data (small, visible parameters) and doPost() for submitting large or sensitive data that changes server state.

servlet

Frequently asked questions

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