2080

CSC419 · TU past paper

Advanced Java Programming 2080 question paper

The complete TU 2080 exam paper for Advanced Java Programming (CSC419), all 12 questions with solved model answers written to the mark scheme.

Tap a question to open its answer.

  1. 110 marksConcurrencyAnswer

    Why do we need to synchronize the thread? Justify with an example. An array with an odd number of elements is said to be centered if all elements (except the middle one) are strictly greater than the value of the middle element. Note that only arrays with an odd number of elements have a middle element. Write a function that accepts an integer array and returns 1 if it is a centered array, otherwise it returns 0.[10]

    Thread Synchronization and Centered Array


    Part 1: Why Do We Need to Synchronize Threads? (with Example)

    What is Thread Synchronization?

    Thread synchronization is the mechanism that ensures that two or more concurrent threads do not simultaneously execute a critical section (a segment of code that accesses shared resources). Without synchronization, multiple threads accessing and modifying shared data can produce inconsistent or incorrect results, a situation known as a race condition.


    Why Do We Need Synchronization?

    When multiple threads share a common resource (such as a variable, file, or object), the following problems can occur without synchronization:

    ProblemDescription
    Race ConditionTwo threads read/write shared data simultaneously, causing unpredictable results
    Data InconsistencyShared data gets corrupted because updates from one thread overwrite another
    Thread InterferenceOperations of one thread interfere with operations of another thread

    Synchronization solves these problems by allowing only one thread at a time to access the critical section using the synchronized keyword in Java.


    Example: Without Synchronization (Problem)

    class Counter {
        int count = 0;
    
        // No synchronization - PROBLEM
        public void increment() {
            count++;
        }
    }
    
    class MyThread extends Thread {
        Counter c;
    
        MyThread(Counter c) {
            this.c = c;
        }
    
        public void run() {
            for (int i = 0; i < 1000; i++) {
                c.increment();
            }
        }
    }
    
    public class WithoutSync {
        public static void main(String[] args) throws InterruptedException {
            Counter c = new Counter();
    
            MyThread t1 = new MyThread(c);
            MyThread t2 = new MyThread(c);
    
            t1.start();
            t2.start();
    
            t1.join();
            t2.join();
    
            // Expected: 2000, but actual result is unpredictable (e.g., 1768, 1854...)
            System.out.println("Count: " + c.count);
        }
    }
    

    Problem: Both t1 and t2 access count++ simultaneously. The operation count++ is not atomic - it involves three steps:

    1. Read the value of count
    2. Increment it
    3. Write it back

    Two threads can read the same value before either writes back, causing lost updates.


    Example: With Synchronization (Solution)

    class Counter {
        int count = 0;
    
        // Synchronized method - only one thread can execute at a time
        public synchronized void increment() {
            count++;
        }
    }
    
    class MyThread extends Thread {
        Counter c;
    
        MyThread(Counter c) {
            this.c = c;
        }
    
        public void run() {
            for (int i = 0; i < 1000; i++) {
                c.increment();
            }
        }
    }
    
    public class WithSync {
        public static void main(String[] args) throws InterruptedException {
            Counter c = new Counter();
    
            MyThread t1 = new MyThread(c);
            MyThread t2 = new MyThread(c);
    
            t1.start();
            t2.start();
    
            t1.join();
            t2.join();
    
            // Always prints: Count: 2000 (correct and consistent)
            System.out.println("Count: " + c.count);
        }
    }
    

    How it works:

    • The synchronized keyword places a lock (monitor) on the object.
    • When t1 enters increment(), it acquires the lock.
    • t2 must wait until t1 releases the lock before it can enter.
    • This guarantees mutual exclusion and data consistency.

    Summary of Synchronization Benefits

    • Prevents race conditions
    • Ensures data consistency across threads
    • Provides mutual exclusion for critical sections
    • Enables safe communication between threads

    Part 2: Centered Array Function

    Problem Definition

    An array with an odd number of elements is centered if:

    • All elements except the middle one are strictly greater than the middle element.

    Return: 1 if centered, 0 otherwise.


    Logic / Algorithm

    Step 1: Check if the array length is odd.
            If even, return 0 (no middle element exists).
    
    Step 2: Find the middle index = length / 2
    
    Step 3: Get the middle element = array[middleIndex]
    
    Step 4: Loop through all elements except the middle one.
            If any element is <= middle element, return 0.
    
    Step 5: If all elements pass the check, return 1.
    

    Java Implementation

    public class CenteredArray {
    
        // Function to check if array is centered
        public static int isCentered(int[] arr) {
    
            int n = arr.length;
    
            // Step 1: Check if number of elements is odd
            if (n % 2 == 0) {
                return 0; // Even number of elements, no middle element
            }
    
            // Step 2: Find the middle index and middle element
            int midIndex = n / 2;
            int midValue = arr[midIndex];
    
            // Step 3: Check all elements except the middle one
            for (int i = 0; i < n; i++) {
                if (i != midIndex) {
                    // Every other element must be STRICTLY GREATER than middle
                    if (arr[i] <= midValue) {
                        return 0; // Not centered
                    }
                }
            }
    
            // Step 4: All conditions satisfied
            return 1;
        }
    
        // Main method to test
        public static void main(String[] args) {
    
            int[] arr1 = {3, 5, 1, 4, 2}; // middle = arr[2] = 1, all others > 1
            int[] arr2 = {5, 3, 4, 2, 6}; // middle = arr[2] = 4, but 3 <= 4, not strictly greater, so not centered
    
            System.out.println("Array 1 result: " + isCentered(arr1)); // Expected: 1 (centered)
            System.out.println("Array 2 result: " + isCentered(arr2)); // Expected: 0 (not centered)
        }
    }
    

    Dry Run

    Array 1 = {3, 5, 1, 4, 2}: length = 5 (odd), midIndex = 2, midValue = 1. Checking the remaining elements: 3 > 1, 5 > 1, 4 > 1, 2 > 1, all strictly greater, so the function returns 1.

    Array 2 = {5, 3, 4, 2, 6}: length = 5 (odd), midIndex = 2, midValue = 4. Checking the remaining elements in order: 5 > 4 passes, but 3 > 4 fails (3 <= 4), so the function immediately returns 0.


    Conclusion

    Thread synchronization is needed whenever multiple threads share mutable state, because without it, interleaved reads and writes to the same variable produce race conditions and lost updates, as shown by the count++ example above. The isCentered function above solves the array problem in a single pass: it rejects even-length arrays immediately, then checks every non-middle element against the middle value, returning 0 the moment any element fails the strictly-greater-than condition, and 1 only if every element passes.

  2. 210 marksServlet vs JSP, JSP Access Model, JSP SyntAnswer

    How does JSP differ from Servlet and show the life cycle of Servlet? How do you create and read the cookies and session using JSP? Illustrate with an example.[10]

    --- Feature Servlet JSP (JavaServer Pages) --------- Nature Java class that generates HTML HTML page that embeds Java code Extension .java (compiled to .class) .jsp (auto-compiled by container) Writing Style HTML written inside out.print...

  3. 310 marksLayout ManagementAnswer

    Describe any two types of Layout manager. Using swing components, design a form with three buttons with captions 'RED,' 'BLUE,' and 'GREEN,' respectively. Then write a program to handle the event such that when the user clicks the button, the color of that button will be the same as its caption.[10]

    Layout Managers and Swing Event Handling

    Part 1: Two Types of Layout Managers

    1. FlowLayout

    FlowLayout is the default layout manager for JPanel. It arranges components in a left-to-right flow, much like lines of text in a paragraph. When one row is filled, it starts a new row.

    Key features:

    • Components are placed in a row from left to right
    • When the row is full, a new row begins
    • Components retain their preferred size
    • Alignment can be set to LEFT, RIGHT, or CENTER (default is CENTER)

    Example:

    setLayout(new FlowLayout());
    

    2. BorderLayout

    BorderLayout is the default layout manager for JFrame. It divides the container into five regions:

    RegionConstant
    TopBorderLayout.NORTH
    BottomBorderLayout.SOUTH
    LeftBorderLayout.WEST
    RightBorderLayout.EAST
    CenterBorderLayout.CENTER

    Key features:

    • Only one component can be placed in each region
    • The CENTER region takes up all remaining space
    • NORTH and SOUTH stretch horizontally
    • EAST and WEST stretch vertically

    Example:

    setLayout(new BorderLayout());
    add(button, BorderLayout.NORTH);
    

    Part 2: Swing Program - Button Color Change on Click

    Program Description

    When the user clicks the RED, BLUE, or GREEN button, the background color of that button changes to match its caption color.


    Complete Java Program

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class ColorButtons extends JFrame implements ActionListener {
    
        // Declare three buttons
        JButton b1, b2, b3;
    
        // Constructor
        ColorButtons() {
            // Set title of the window
            setTitle("Color Button Demo");
    
            // Set layout manager
            setLayout(new FlowLayout());
    
            // Initialize buttons with captions
            b1 = new JButton("RED");
            b2 = new JButton("BLUE");
            b3 = new JButton("GREEN");
    
            // Add action listeners to each button
            b1.addActionListener(this);
            b2.addActionListener(this);
            b3.addActionListener(this);
    
            // Add buttons to the frame
            add(b1);
            add(b2);
            add(b3);
    
            // Frame settings
            setSize(400, 150);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
        }
    
        // Event handling method
        @Override
        public void actionPerformed(ActionEvent e) {
    
            // Check which button was clicked and change its background color
            if (e.getSource() == b1) {
                b1.setBackground(Color.RED);
            }
            else if (e.getSource() == b2) {
                b2.setBackground(Color.BLUE);
            }
            else if (e.getSource() == b3) {
                b3.setBackground(Color.GREEN);
            }
        }
    
        // Main method
        public static void main(String[] args) {
            new ColorButtons();
        }
    }
    

    Output / Form Design

    +------------------------------------------+
    |        Color Button Demo                 |
    +------------------------------------------+
    |                                          |
    |   [ RED ]     [ BLUE ]     [ GREEN ]     |
    |                                          |
    +------------------------------------------+
    
    • Clicking RED button --> button background turns Red
    • Clicking BLUE button --> button background turns Blue
    • Clicking GREEN button --> button background turns Green

    Key Points Explained

    ConceptDescription
    JFrameMain window container
    JButtonClickable button component
    ActionListenerInterface to handle button click events
    actionPerformed()Method called automatically when a button is clicked
    e.getSource()Returns the object (button) that triggered the event
    setBackground(Color.RED)Sets the background color of the button
    FlowLayoutArranges buttons in a row from left to right
  4. 45 marksIntroduction to CORBA, RMI vs CORBA, ArchiAnswer

    List the steps to create an RMI application. Differentiate between RMI and CORBA. [5]

    RMI Application Creation Steps and RMI vs CORBA


    Steps to Create an RMI Application

    RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed applications in Java, allowing an object to invoke methods on an object running in another JVM. The following steps are required:

    Step 1: Define the Remote Interface

    • Create an interface that extends java.rmi.Remote
    • Declare all methods that can be invoked remotely
    • Each method must throw java.rmi.RemoteException
    public interface MyRemote extends Remote {
        public String sayHello() throws RemoteException;
    }
    

    Step 2: Implement the Remote Interface

    • Create a class that implements the remote interface
    • Extend UnicastRemoteObject
    • Implement all declared remote methods
    public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote {
        public String sayHello() throws RemoteException {
            return "Hello from Server!";
        }
    }
    

    Step 3: Generate Stub and Skeleton

    • As noted in the reference, RMI uses two objects: stub and skeleton for remote communication
    • Stub: Client-side proxy that forwards calls to the remote object
    • Skeleton: Server-side object that receives calls and passes them to the actual object
    • Use rmic compiler to generate these: rmic MyRemoteImpl

    Step 4: Start the RMI Registry

    • Start the RMI registry service (acts as a naming service)
    • Run: rmiregistry (default port 1099)

    Step 5: Register the Remote Object (Server Side)

    • Bind the remote object to the RMI registry using Naming.rebind()
    MyRemote obj = new MyRemoteImpl();
    Naming.rebind("MyRemoteService", obj);
    

    Step 6: Write and Run the Client

    • Look up the remote object from the registry using Naming.lookup()
    • Invoke remote methods through the stub
    MyRemote obj = (MyRemote) Naming.lookup("rmi://localhost/MyRemoteService");
    System.out.println(obj.sayHello());
    

    Difference Between RMI and CORBA

    FeatureRMICORBA
    Full FormRemote Method InvocationCommon Object Request Broker Architecture
    LanguageJava only (Java-specific)Language independent (C++, Java, Python, etc.)
    PlatformJava Virtual Machine (JVM) dependentPlatform and language independent
    ProtocolUses JRMP (Java Remote Method Protocol)Uses IIOP (Internet Inter-ORB Protocol)
    Ease of UseSimple and easy to implementComplex to implement and configure
    Object BrokerRMI Registry acts as brokerObject Request Broker (ORB) is used
    Interface DefinitionDefined using Java interfacesDefined using IDL (Interface Definition Language)
    PerformanceFaster within Java environmentRelatively slower due to overhead
    InteroperabilityLimited to Java applications onlyHigh interoperability across languages and platforms
    StandardJava standard (Sun/Oracle)Industry standard by OMG (Object Management Group)

    Summary

    RMI is simpler and best suited for pure Java distributed applications, while CORBA is more powerful and suitable for heterogeneous, multi-language distributed systems requiring high interoperability.

  5. 55 marksJavaFX UI ControlsAnswer

    Write a JavaFX application with components, buttons, text fields, and labels, arranged in a VBox or HBox layout. [5]

    JavaFX is a modern Java GUI framework. It uses a Scene Graph model where UI elements (nodes) are arranged inside layout panes. Key classes used here: Class Purpose ------ Label Displays static text TextField Accepts user text input Butto...

  6. 65 marksDDL and DML Operations using Java, PrepareAnswer

    Assume a table MOVIE(id, title, genre). Now, using JDBC, perform the following queries; a. Add any three records to the MOVIE table. b. Using a prepared statement, update the genre to 'Comedy' having the title 'Jatra'. [5]

    --- --- Step Method Used Purpose ---------------------------- Load driver Class.forName() Registers MySQL JDBC driver Connect DriverManager.getConnection() Opens DB connection Insert records stmt.executeUpdate() Returns number of rows af...

  7. 75 marksOption Dialogs, Creating Dialogs, File ChoAnswer

    When do we need an internal frame? How do you create a table using Swing? [5]

    An Internal Frame (JInternalFrame) is needed in the following situations: - When we want to create a Multiple Document Interface (MDI) application, where several windows (documents) exist inside a single main window. - When we need a lig...

  8. 85 marksServlet vs JSP, JSP Access Model, JSP SyntAnswer

    What do you mean by JSP implicit objects? Discuss Java Mail API. [5]

    JSP Implicit Objects and Java Mail API


    Part 1: JSP Implicit Objects

    JSP implicit objects are pre-defined objects that the JSP container automatically makes available to every JSP page without requiring the developer to explicitly declare or instantiate them. These objects can be used directly inside JSP scriptlets and expressions.

    Note: Unlike Servlets, JSP has implicit objects while Servlet does not.

    The commonly used JSP implicit objects are:

    ObjectTypeDescription
    requestHttpServletRequestRepresents the client HTTP request
    responseHttpServletResponseRepresents the HTTP response to the client
    outJspWriterUsed to write output to the response
    sessionHttpSessionManages session data for a user
    applicationServletContextShared data across the entire application
    configServletConfigServlet configuration information
    pageContextPageContextProvides access to all JSP namespaces
    pageObjectRefers to the current JSP page instance (like this)
    exceptionThrowableAvailable in error pages to handle exceptions

    These objects simplify JSP development by removing the need for boilerplate code.


    Part 2: Java Mail API

    Definition

    The JavaMail API is an API used to compose, write, and read electronic messages (emails). It provides a protocol-independent and platform-independent framework for sending and receiving emails.

    Core Packages

    • java.mail
    • java.mail.activation

    Setup Requirements

    • For J2EE 1.3 (Enterprise Edition): No additional setup required.
    • For J2SE 1.1+ (Standard Edition): Must download and install:
      • JavaMail API
      • Java Activation Framework

    Sending an Email (3 Steps)

    Step 1: Get the Session Object Stores all host information such as host name, username, password, etc.

    Properties properties = new Properties();
    Session session = Session.getDefaultInstance(properties, null);
    

    Step 2: Compose the Message MimeMessage class is mostly used for composing the email.

    MimeMessage message = new MimeMessage(session);
    

    Step 3: Send the Message Transport class provides the method to send the message.

    Transport.send(message);
    

    Receiving an Email (Steps)

    1. Get the session object.
    2. Create the POP3 store object and connect with the POP server.
    3. Create the folder object and open it.
    4. Retrieve the messages from the folder into an array and print them.
    5. Close the store and folder objects.

    Summary

    FeatureDetail
    PurposeSend and receive emails
    NatureProtocol-independent, Platform-independent
    Key ClassesSession, MimeMessage, Transport
    Protocol Used (Receive)POP3
    Core Packagejava.mail
  9. 95 marksJDBC Architecture, JDBC Driver Types, JDBCAnswer

    Describe the role of Result Sets. What is wrong in the following code?

    public class Point {
    int p;
    public void setP(int p) {
    p = p;
    }
    }
    

    [5]

    --- A Result Set in Java (specifically java.sql.ResultSet) represents the result of a database query. It acts as a cursor that points to the data returned from executing a SQL SELECT statement via JDBC. Role Description -----------------...

  10. 105 marksAnswer

    Write a TCP client-server system in which the client program sends two integers to a server program, which returns the greatest among them. [5]

    Using TCP Socket Programming in Java: - Server: Creates ServerSocket, accepts connection, reads data from client, processes, sends response - Client: Opens Socket, sends data to server, reads response --- --- --- --- Side Steps ---------...

  11. 115 marksNumericalWorking with FilesAnswer

    Suppose that 9 integers are written in a file named 'magic.txt' in the arrangement of 3 x 3 separated by space. Write a program to check whether the integers in all rows, all columns, and both diagonals sum to the same constant or not. [5]

    STEP 1 - EXTRACT: Given Data

    • Input file: magic.txt
    • Contains 9 integers arranged as a $3 \times 3$ grid, separated by spaces.
    • Task: Verify whether all 3 rows, all 3 columns, and both diagonals sum to the same constant (magic square check).

    No specific numeric values are given for the integers in the question; the file contents are supplied at runtime. This is a programming problem, so no numeric computation is required unless sample data is chosen for demonstration.


    STEP 2 - SOLVE: Model Answer

    Approach

    1. Read the 9 integers from magic.txt into a $3 \times 3$ array.
    2. Compute the target constant using the sum of the first row.
    3. Compare every row sum, every column sum, and both diagonal sums against this constant.
    4. Report whether it is a magic square.

    Java Program

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    
    public class MagicSquareChecker {
        public static void main(String[] args) {
            int[][] m = new int[3][3];
    
            // Step 1: Read 9 integers from magic.txt
            try (Scanner sc = new Scanner(new File("magic.txt"))) {
                for (int i = 0; i < 3; i++)
                    for (int j = 0; j < 3; j++)
                        if (sc.hasNextInt())
                            m[i][j] = sc.nextInt();
            } catch (FileNotFoundException e) {
                System.out.println("File not found: " + e.getMessage());
                return;
            }
    
            // Display the matrix
            System.out.println("Matrix read from magic.txt:");
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 3; j++)
                    System.out.print(m[i][j] + "\t");
                System.out.println();
            }
    
            // Step 2: Target constant = sum of first row
            int constant = m[0][0] + m[0][1] + m[0][2];
            boolean isMagic = true;
    
            // Step 3: Check all rows
            for (int i = 0; i < 3; i++) {
                int rowSum = m[i][0] + m[i][1] + m[i][2];
                if (rowSum != constant) isMagic = false;
            }
    
            // Check all columns
            for (int j = 0; j < 3; j++) {
                int colSum = m[0][j] + m[1][j] + m[2][j];
                if (colSum != constant) isMagic = false;
            }
    
            // Check main diagonal
            int diag1 = m[0][0] + m[1][1] + m[2][2];
            if (diag1 != constant) isMagic = false;
    
            // Check anti-diagonal
            int diag2 = m[0][2] + m[1][1] + m[2][0];
            if (diag2 != constant) isMagic = false;
    
            // Step 4: Final result
            if (isMagic)
                System.out.println("All rows, columns and diagonals sum to "
                                   + constant + ". It IS a Magic Square.");
            else
                System.out.println("The sums are NOT all equal. It is NOT a Magic Square.");
        }
    }
    

    Sample magic.txt

    2 7 6
    9 5 1
    4 3 8
    

    Verification of Sums (for the sample)

    Rows:

    • $2+7+6 = 15$
    • $9+5+1 = 15$
    • $4+3+8 = 15$

    Columns:

    • $2+9+4 = 15$
    • $7+5+3 = 15$
    • $6+1+8 = 15$

    Diagonals:

    • Main: $2+5+8 = 15$
    • Anti: $6+5+4 = 15$

    All eight sums equal $15$, the magic constant.

    Sample Output

    Matrix read from magic.txt:
    2    7    6
    9    5    1
    4    3    8
    All rows, columns and diagonals sum to 15. It IS a Magic Square.
    

    Key Points

    CheckFormula
    Row $i$$m[i][0]+m[i][1]+m[i][2]$
    Column $j$$m[0][j]+m[1][j]+m[2][j]$
    Main diagonal$m[0][0]+m[1][1]+m[2][2]$
    Anti-diagonal$m[0][2]+m[1][1]+m[2][0]$

    The program is logically correct: it reads from the file, catches FileNotFoundException, and compares all eight sums to the first-row constant. The sample result gives a magic constant of $15$.

  12. 125 marksMenu, Menu Item, Icons in Menu Items, ChecAnswer

    Write a program to create a menu named 'File' with menu items 'New', 'Save,' and 'Exit'. [5]

    In Java Swing, menus are created using: - JMenuBar - the menu bar that holds menus - JMenu - a single menu (e.g., "File") - JMenuItem - individual items inside a menu (e.g., "New", "Save", "Exit") - ActionListener - to handle click event...