Browse papers
LevelBSc CSIT (TU)
StreamScience
SubjectAdvanced Java Programming (BSc CSIT, CSC409)
Year2082 BS
Exam sessionRegular (annual)
Full marks60
Time allowed180 minutes
Questions12, all with step-by-step solutions
A

Section A: Long Answer Questions

Attempt any TWO questions.

3 questions·10 marks each
1Long answer10 marks

What are the uses of focus and item event? Write a socket program using UDP to create three programs, two of which are clients to a single server. Client1 will send a character to the server process. The server will circularly decrement the letter to the previous letter in the alphabet and send the result to Client2. Then Client2 prints the letter it receives and then all the processes terminate.

Uses of Focus and Item Events

Focus Event (FocusEvent)

A focus event is generated when a component gains or loses keyboard focus (the component that currently receives keyboard input). It is handled with a FocusListener having two callbacks:

  • focusGained(FocusEvent e) — fired when the component becomes the focus owner.
  • focusLost(FocusEvent e) — fired when it loses focus.

Uses: validating a text field when the user tabs away, highlighting the active field, showing/hiding hints, committing edits, or moving the caret automatically.

Item Event (ItemEvent)

An item event is generated when the selection state of an item changes in components like Checkbox, JCheckBox, JRadioButton, Choice, or JComboBox. It is handled with an ItemListener:

  • itemStateChanged(ItemEvent e) — fired when an item is selected or deselected. e.getStateChange() returns ItemEvent.SELECTED or ItemEvent.DESELECTED.

Uses: reacting to a checkbox being ticked, responding to a drop-down selection, enabling/disabling dependent controls, or updating a preview when an option changes.

UDP Socket Program (Server + Two Clients)

DatagramSocket and DatagramPacket are used for connectionless UDP communication. Client1 sends a character to the Server; the server circularly decrements the letter (e.g. A → Z, b → a) and forwards the result to Client2, which prints it. All processes then terminate.

Server.java

import java.net.*;

public class Server {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(5000);   // listens on 5000

        // 1. Receive a character from Client1
        byte[] buf = new byte[1];
        DatagramPacket recv = new DatagramPacket(buf, buf.length);
        socket.receive(recv);
        char ch = (char) buf[0];
        System.out.println("Server received: " + ch);

        // 2. Circularly decrement the letter
        char result;
        if (ch == 'A') result = 'Z';
        else if (ch == 'a') result = 'z';
        else result = (char) (ch - 1);

        // 3. Send result to Client2 (listening on port 6000)
        byte[] out = { (byte) result };
        DatagramPacket send = new DatagramPacket(
            out, out.length, InetAddress.getByName("localhost"), 6000);
        socket.send(send);
        socket.close();            // server terminates
    }
}

Client1.java (sends a character to the server)

import java.net.*;

public class Client1 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket();
        char ch = 'C';                              // character to send
        byte[] data = { (byte) ch };
        DatagramPacket packet = new DatagramPacket(
            data, data.length, InetAddress.getByName("localhost"), 5000);
        socket.send(packet);
        System.out.println("Client1 sent: " + ch);
        socket.close();            // Client1 terminates
    }
}

Client2.java (receives the result from the server and prints it)

import java.net.*;

public class Client2 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(6000);   // listens on 6000
        byte[] buf = new byte[1];
        DatagramPacket recv = new DatagramPacket(buf, buf.length);
        socket.receive(recv);
        System.out.println("Client2 received: " + (char) buf[0]);
        socket.close();            // Client2 terminates
    }
}

Run order: start Server, then Client2 (so it is listening), then Client1. For input C, Client2 prints B; for input A it would print Z (circular wrap-around). All three processes exit after one exchange.

2Long answer10 marks

Write a JavaFX application that creates a ChoiceBox with a list of colors. Display a label that changes its text based on the selected color from the ChoiceBox. Write down steps for writing CORBA programs with a suitable example.

JavaFX ChoiceBox Application

ChoiceBox is a JavaFX control that shows a drop-down list of items for single selection. We listen to its selection model with a ChangeListener (or a binding) and update a Label whenever the chosen color changes.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ColorChoiceApp extends Application {
    @Override
    public void start(Stage stage) {
        ChoiceBox<String> choiceBox = new ChoiceBox<>();
        choiceBox.getItems().addAll("Red", "Green", "Blue", "Yellow");
        choiceBox.setValue("Red");

        Label label = new Label("Selected color: Red");

        // Update label whenever the selected color changes
        choiceBox.getSelectionModel().selectedItemProperty().addListener(
            (obs, oldVal, newVal) -> label.setText("Selected color: " + newVal));

        VBox root = new VBox(10, choiceBox, label);
        Scene scene = new Scene(root, 300, 150);
        stage.setTitle("ChoiceBox Demo");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

When the user picks a color from the ChoiceBox, the listener fires and the Label text changes to reflect the selection.

Steps for Writing CORBA Programs

CORBA (Common Object Request Broker Architecture) is a standard from the OMG that lets objects written in different languages on different machines communicate through an ORB (Object Request Broker) using IDL (Interface Definition Language).

Steps:

  1. Define the interface in IDL — declare the remote operations in a language-neutral .idl file.
  2. Compile the IDL with the IDL-to-Java compiler (idlj) to generate the stub (client side), skeleton (server side), and helper/holder classes.
  3. Implement the servant — write a Java class that extends the generated skeleton (...POA) and implements the interface operations.
  4. Write the server — create the ORB, get the POA, instantiate the servant, register/bind its object reference with the Naming Service, and wait for requests.
  5. Write the client — initialize the ORB, look up the object reference from the Naming Service, narrow it to the interface type, and invoke remote methods.
  6. Run — start orbd (the naming/activation daemon), then the server, then the client.

Example IDL — Hello.idl

module HelloApp {
    interface Hello {
        string sayHello();
    };
};

Servant

import HelloApp.*;
class HelloImpl extends HelloPOA {
    public String sayHello() { return "Hello from CORBA server"; }
}

Server (skeleton)

ORB orb = ORB.init(args, null);
POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
rootpoa.the_POAManager().activate();
HelloImpl servant = new HelloImpl();
org.omg.CORBA.Object ref = rootpoa.servant_to_reference(servant);
Hello href = HelloHelper.narrow(ref);
// bind 'href' in the naming service, then orb.run();

Client (skeleton)

ORB orb = ORB.init(args, null);
// resolve "Hello" from naming service into 'helloRef'
Hello helloRef = HelloHelper.narrow(ncRef.resolve_str("Hello"));
System.out.println(helloRef.sayHello());

Thus CORBA achieves language- and platform-independent distributed object communication via IDL and the ORB.

3Long answer10 marks

Discuss about JSP implicit objects. Assume a database with the table TEACHER (ID, Name). Now using JDBC, execute the following SQL query:

  • a. select * from TEACHER;

  • b. insert into TEACHER values (8, 'Ramesh');

  • c. select name from TEACHER where ID = 9;

JSP Implicit Objects

JSP provides nine implicit objects automatically created by the container, so the programmer can use them in scriptlets/expressions without declaring them:

ObjectTypePurpose
requestHttpServletRequestThe current client request; read parameters/headers.
responseHttpServletResponseThe response sent to the client; set headers/cookies.
outJspWriterWrites output to the response stream.
sessionHttpSessionPer-user session for storing attributes.
applicationServletContextApplication-wide shared data for all users.
configServletConfigServlet configuration / init parameters.
pageContextPageContextAccess to all scopes and page attributes.
pageObject (this)Reference to the current JSP page (servlet) instance.
exceptionThrowableThe thrown exception (only in error pages, isErrorPage="true").

These cover the four scopes (page → request → session → application) and let JSP interact with the request/response lifecycle directly.

JDBC Program for the TEACHER Table

Assume table TEACHER(ID, Name). The program loads the driver, connects, then runs the three queries — executeQuery for SELECT and executeUpdate for INSERT.

import java.sql.*;

public class TeacherJDBC {
    public static void main(String[] args) throws Exception {
        String url = "jdbc:mysql://localhost:3306/college";
        Class.forName("com.mysql.cj.jdbc.Driver");
        try (Connection con = DriverManager.getConnection(url, "root", "root");
             Statement st = con.createStatement()) {

            // (a) select * from TEACHER;
            System.out.println("--- All teachers ---");
            ResultSet rs = st.executeQuery("SELECT * FROM TEACHER");
            while (rs.next()) {
                System.out.println(rs.getInt("ID") + "\t" + rs.getString("Name"));
            }

            // (b) insert into TEACHER values (8, 'Ramesh');
            int rows = st.executeUpdate(
                "INSERT INTO TEACHER VALUES (8, 'Ramesh')");
            System.out.println("Inserted rows: " + rows);

            // (c) select name from TEACHER where ID = 9;
            ResultSet rs2 = st.executeQuery(
                "SELECT Name FROM TEACHER WHERE ID = 9");
            if (rs2.next())
                System.out.println("Name with ID 9: " + rs2.getString("Name"));
            else
                System.out.println("No teacher with ID 9");
        }
    }
}

Notes:

  • (a) returns all rows, iterated with rs.next().
  • (b) executeUpdate() returns the number of affected rows (1 on success).
  • (c) a single-row lookup; if (rs2.next()) checks whether a record exists. Using a PreparedStatement would be safer for parameterized queries.
B

Section B: Short Answer Questions

Attempt any EIGHT questions.

9 questions·5 marks each
4Short answer5 marks

Write a program to insert an icon in the frame and when the user presses the up arrow, it will move upward.

Moving an Icon with the Up Arrow Key

We add an ImageIcon to a JLabel, place it in a frame, and register a KeyListener. When the up arrow (KeyEvent.VK_UP) is pressed, we decrease the label's y-coordinate so it moves upward, then repaint.

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

public class MoveIcon extends JFrame implements KeyListener {
    JLabel icon = new JLabel(new ImageIcon("icon.png"));
    int x = 150, y = 200;

    public MoveIcon() {
        setLayout(null);                       // absolute positioning
        icon.setBounds(x, y, 64, 64);
        add(icon);
        addKeyListener(this);
        setTitle("Move Icon (Up Arrow)");
        setSize(400, 350);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
        setFocusable(true);
        requestFocus();                        // frame must hold focus for keys
    }

    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_UP) {
            y -= 10;                           // move upward
            icon.setBounds(x, y, 64, 64);
            repaint();
        }
    }

    public void keyReleased(KeyEvent e) {}
    public void keyTyped(KeyEvent e) {}

    public static void main(String[] args) {
        new MoveIcon();
    }
}

How it works: the icon is shown via a JLabel with an ImageIcon. With a null layout we control its exact position using setBounds(). Each up-arrow press decrements y by 10 pixels and repaints, so the icon visibly moves up the frame.

5Short answer5 marks

How do you handle HTTP request and response using JSP? Illustrate with an example.

Handling HTTP Request and Response in JSP

JSP handles HTTP using the implicit objects request (HttpServletRequest) and response (HttpServletResponse).

  • Request handling: read form data and query parameters with request.getParameter("name"), headers with request.getHeader(...), and the HTTP method with request.getMethod(). Because a JSP is compiled into a servlet, both doGet and doPost submissions reach the same page.
  • Response handling: the implicit out object writes the HTML body; response can set the content type (response.setContentType(...)), add cookies, send redirects (response.sendRedirect(...)), or set status codes.

Example

form.html — sends data to the JSP via POST:

<form action="welcome.jsp" method="post">
    Name: <input type="text" name="username">
    <input type="submit" value="Submit">
</form>

welcome.jsp — reads the request and builds the response:

<%@ page contentType="text/html" %>
<html>
<body>
<%
    String name = request.getParameter("username");   // read request
    if (name == null || name.trim().isEmpty()) {
        out.println("<h3>Please enter a name.</h3>");  // write response
    } else {
        out.println("<h2>Welcome, " + name + "!</h2>");
        out.println("<p>Request method: " + request.getMethod() + "</p>");
    }
%>
</body>
</html>

When the form is submitted, the JSP reads username from the request and dynamically generates the response HTML using out, demonstrating the full request-response cycle.

6Short answer5 marks

Describe the life cycle of a servlet.

Servlet Life Cycle

The life cycle of a servlet is managed by the web container (e.g., Tomcat) and consists of three main phases controlled by methods of the Servlet interface.

   Class loaded & instantiated
             │
             ▼
     init(ServletConfig)      ← called ONCE
             │
             ▼
   service(req, res)          ← called for EVERY request
     (→ doGet / doPost ...)
             │
             ▼
        destroy()             ← called ONCE before unload

1. Loading and Instantiation The container loads the servlet class and creates a single instance (usually on the first request, or at startup if load-on-startup is set).

2. Initialization — init(ServletConfig config) Called once right after instantiation. Used for one-time setup such as opening database connections or reading init parameters. The servlet is now ready to serve requests.

3. Request Handling — service(ServletRequest, ServletResponse) Called for every client request. The container creates request/response objects and (for HttpServlet) dispatches to doGet(), doPost(), etc. based on the HTTP method. Because there is a single instance, the container handles concurrent requests using multiple threads.

4. Destruction — destroy() Called once before the servlet is removed from service (server shutdown or reload). Used to release resources (close connections, save state). After this, the instance becomes eligible for garbage collection.

Thus init() and destroy() run once each, while service() runs once per request.

7Short answer5 marks

Write a program to input the name of faculty and throw an exception if that input is not "CSIT".

Throwing a Custom Exception for Faculty Input

We define a custom checked exception and throw it when the entered faculty name is not exactly "CSIT".

import java.util.Scanner;

// Custom exception class
class InvalidFacultyException extends Exception {
    public InvalidFacultyException(String msg) {
        super(msg);
    }
}

public class FacultyCheck {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter faculty name: ");
        String faculty = sc.nextLine().trim();

        try {
            if (!faculty.equals("CSIT")) {
                throw new InvalidFacultyException(
                    "Invalid faculty: " + faculty + " (expected CSIT)");
            }
            System.out.println("Valid faculty: " + faculty);
        } catch (InvalidFacultyException e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
    }
}

Explanation:

  • InvalidFacultyException extends Exception, making it a user-defined (custom) exception.
  • The input is compared with "CSIT" using equals(). If it differs, the program throws the custom exception with the throw keyword.
  • The try-catch block catches it and prints the message; otherwise it confirms the faculty is valid.

Sample run: input BCAException caught: Invalid faculty: BCA (expected CSIT); input CSITValid faculty: CSIT.

8Short answer5 marks

Write a program to design a layout of a simple calculator. (Arithmetic operation not required.)

Calculator Layout (Design Only)

We build the visual layout of a calculator using Swing: a display JTextField at the top and a grid of JButtons below. No arithmetic logic is required — only the layout.

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

public class CalculatorLayout extends JFrame {
    public CalculatorLayout() {
        setTitle("Calculator");
        setLayout(new BorderLayout(5, 5));

        // Display
        JTextField display = new JTextField();
        display.setHorizontalAlignment(JTextField.RIGHT);
        display.setFont(new Font("Arial", Font.BOLD, 20));
        add(display, BorderLayout.NORTH);

        // Button grid (4 x 4)
        JPanel panel = new JPanel(new GridLayout(4, 4, 5, 5));
        String[] buttons = {
            "7", "8", "9", "/",
            "4", "5", "6", "*",
            "1", "2", "3", "-",
            "0", ".", "=", "+"
        };
        for (String b : buttons) {
            panel.add(new JButton(b));
        }
        add(panel, BorderLayout.CENTER);

        setSize(300, 350);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        new CalculatorLayout();
    }
}

Layout explanation:

  • A BorderLayout places the display (JTextField) at the top (NORTH).
  • A JPanel with a GridLayout(4,4) holds the 16 buttons (digits, decimal point, operators, and =) arranged in 4 rows and 4 columns with gaps.

This produces a clean calculator UI; arithmetic could later be added via an ActionListener.

9Short answer5 marks

What is a package? Differentiate between method overloading and overriding.

What is a Package?

A package in Java is a namespace that groups related classes and interfaces together. It is essentially a folder/directory that organizes types logically.

Benefits: avoids naming conflicts (fully qualified names), provides access control (protected/default visibility), and makes code reusable and easier to maintain. A package is declared at the top of a file with the package keyword and used elsewhere via import.

package com.college.utils;   // declaration
public class Helper { }
import com.college.utils.Helper;   // usage

Built-in packages include java.lang, java.util, java.io, etc.

Method Overloading vs Method Overriding

AspectMethod OverloadingMethod Overriding
DefinitionSame method name with different parameter lists in the same classSubclass redefines a method with the same signature as the superclass
PolymorphismCompile-time (static) polymorphismRun-time (dynamic) polymorphism
InheritanceNot requiredRequired (relationship between super- and subclass)
ParametersMust differ (number/type/order)Must be identical
Return typeCan differSame or covariant
BindingResolved at compile timeResolved at run time

Overloading example:

int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }

Overriding example:

class Animal { void sound() { System.out.println("Animal"); } }
class Dog extends Animal { void sound() { System.out.println("Bark"); } }
10Short answer5 marks

Write a program to demonstrate the concept of internal frame.

Internal Frame (JInternalFrame)

A JInternalFrame is a lightweight, frame-like component that can be placed inside another window to provide a window-within-a-window. It is used to build MDI (Multiple Document Interface) applications and is hosted inside a JDesktopPane. Internal frames can be moved, resized, iconified, maximized, and closed — all within the parent frame.

import javax.swing.*;

public class InternalFrameDemo extends JFrame {
    public InternalFrameDemo() {
        JDesktopPane desktop = new JDesktopPane();   // container for internal frames
        setContentPane(desktop);

        // Create an internal frame
        JInternalFrame internal = new JInternalFrame(
            "Internal Frame", true, true, true, true);  // resizable, closable, maximizable, iconifiable
        internal.setSize(250, 150);
        internal.setLocation(30, 30);
        internal.add(new JLabel("  This is an internal frame"));
        internal.setVisible(true);
        desktop.add(internal);

        setTitle("JInternalFrame Demo");
        setSize(450, 350);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        new InternalFrameDemo();
    }
}

Explanation:

  • A JDesktopPane is set as the content pane to act as the desktop that holds internal frames.
  • The JInternalFrame constructor flags (resizable, closable, maximizable, iconifiable) enable the usual window controls.
  • The frame is added to the desktop pane and made visible, appearing as a draggable sub-window inside the main frame.
11Short answer5 marks

Write a program to create a class MOVIE with attributes name and genre. Write the movies with genre comedy on COM.DAT file.

MOVIE Class — Writing Comedy Movies to COM.DAT

We create a serializable Movie class with name and genre, then write every movie whose genre is "comedy" to the file COM.DAT using object serialization.

import java.io.*;
import java.util.*;

class Movie implements Serializable {
    String name;
    String genre;
    Movie(String name, String genre) {
        this.name = name;
        this.genre = genre;
    }
}

public class MovieWriter {
    public static void main(String[] args) throws IOException {
        // Sample list of movies
        List<Movie> movies = new ArrayList<>();
        movies.add(new Movie("Hangover", "comedy"));
        movies.add(new Movie("Inception", "thriller"));
        movies.add(new Movie("Mr. Bean", "comedy"));

        try (ObjectOutputStream oos =
                 new ObjectOutputStream(new FileOutputStream("COM.DAT"))) {
            for (Movie m : movies) {
                if (m.genre.equalsIgnoreCase("comedy")) {   // filter comedy
                    oos.writeObject(m);
                    System.out.println("Written: " + m.name);
                }
            }
        }
        System.out.println("Comedy movies saved to COM.DAT");
    }
}

Explanation:

  • Movie implements Serializable so its objects can be written to a file.
  • The program iterates over the movie list and, for each movie with genre "comedy", writes the object to COM.DAT via ObjectOutputStream.writeObject().
  • try-with-resources ensures the stream is closed automatically. (The objects can later be read back with ObjectInputStream.readObject().)
12Short answer5 marks

Do we still need Java Applet? Justify. Give the hierarchy of Swing class.

Do We Still Need Java Applets? Justification

No, Java applets are essentially obsolete and no longer needed. They were deprecated in Java 9 and removed in Java 11.

Justification:

  • Browser support ended: modern browsers removed the NPAPI plug-in that applets required, so they can no longer run in browsers.
  • Security risks: applets ran with browser plug-ins that were a frequent source of vulnerabilities.
  • Better alternatives exist: rich client-side functionality is now delivered by HTML5, JavaScript, CSS; for Java GUIs, JavaFX and Java Web Start / desktop apps are used; for server-side dynamic content, Servlets and JSP are standard.

So while applets were historically important for browser-based Java GUIs, today there is no practical need for them.

Hierarchy of Swing Classes

All Swing components ultimately extend AWT base classes:

java.lang.Object
  └── java.awt.Component
        └── java.awt.Container
              ├── java.awt.Window
              │     └── java.awt.Frame
              │           └── javax.swing.JFrame      (top-level container)
              ├── javax.swing.JWindow
              ├── javax.swing.JDialog
              └── javax.swing.JComponent               (base of lightweight components)
                    ├── JButton, JLabel, JTextField
                    ├── JCheckBox, JRadioButton, JComboBox, JList
                    ├── JPanel, JScrollPane, JTable, JTree ...
  • JComponent is the superclass of almost all Swing components (everything except the top-level containers).
  • Top-level containers (JFrame, JDialog, JApplet, JWindow) descend directly from AWT Window/Frame, not from JComponent.

Frequently asked questions

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