Important Questions

CSC419 · Exam intelligence

Advanced Java Programming important questions

From 7 past TU papers: which questions keep coming back, how much they carry, and what is most likely to show up next. Every question links to a model answer.

Most likely in the next examStatistical

Ranked by how often a topic is asked, its marks weight, and whether it is due after skipping the 2081 paper. No guarantees; study the whole syllabus.

1asked 8xavg 7 marks · Web Container, Introduction to Servlets, Life cycle of servlets, The servlet APIs, Writing Servlet Programs, Reading Form Parameters, Processing Forms, Handling HTTP Request and Response
Answer

Explain the life cycle of servlets. [5]

Life Cycle of a Servlet

Introduction

A Servlet is a small Java program that executes on the server side of a Web connection and dynamically extends the functionality of a web server. All servlets must implement the Servlet interface, which defines the life-cycle methods. The servlet life cycle is managed by the Servlet Engine (Container).


Stages of the Servlet Life Cycle

The Servlet Life Cycle has 5 stages in general. Three methods are central to the life cycle: init(), service(), and destroy().


Stage 1: Loading and Instantiation

  • The class loader is responsible for loading the servlet class from the file system or network.
  • After loading, the servlet engine creates an instance of the servlet class.
  • The servlet instance is created only once in the servlet life cycle.
  • The servlet engine can instantiate more than one servlet instance if needed (e.g., for load balancing).

Stage 2: Initialization (init())

  • After instantiation, the servlet container calls the init() method.
  • This method is called only once during the entire life of the servlet.
  • It is used to perform one-time initialization tasks such as opening database connections, loading configuration parameters, etc.
  • Signature:
public void init(ServletConfig config) throws ServletException

Stage 3: Request Handling (service())

  • Once initialized, the servlet is ready to handle client requests.
  • For each incoming request, the servlet container calls the service() method.
  • The service() method determines the type of HTTP request (GET, POST, PUT, DELETE, etc.) and dispatches it to the appropriate handler method (doGet(), doPost(), etc.).
  • This method is called multiple times, once per request.
  • Signature:
public void service(ServletRequest req, ServletResponse res)
    throws ServletException, IOException

Stage 4: Destroying (destroy())

  • When the servlet container decides to remove the servlet (e.g., server shutdown or redeployment), it calls the destroy() method.
  • This method is called only once, at the end of the servlet's life.
  • It is used to perform cleanup tasks such as closing database connections, releasing resources, etc.
  • Signature:
public void destroy()

Stage 5: Garbage Collection

  • After destroy() is called, the servlet instance becomes eligible for garbage collection.
  • The JVM's garbage collector reclaims the memory occupied by the servlet object.

Diagram of Servlet Life Cycle

Client Request
      |
      v
[1. Load & Instantiate Servlet Class]
      |
      v
[2. init()  --> Called ONCE]
      |
      v
[3. service() --> Called per request]
   /    \
doGet() doPost() ...
      |
      v
[4. destroy() --> Called ONCE]
      |
      v
[5. Garbage Collection]

Summary Table

StageMethodCalled
Loading & Instantiation(by class loader)Once
Initializationinit()Once
Request Handlingservice()Per request
Destructiondestroy()Once
Garbage Collection(by JVM)Once

Note: The packages java.x.servlet and java.x.servlet.http provide the interfaces and classes required to implement these life-cycle methods. A server such as Apache Tomcat or GlassFish is needed to run servlets.

2asked 6xavg 7 marks · due (skipped 2081) · Layout Management
Answer

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
3asked 7xavg 6 marks · Servlet vs JSP, JSP Access Model, JSP Syntax
Answer

Write a program in JSP to display the string taken in one page in another page. [5]

JSP Program to Display String from One Page to Another Page

Concept

This program uses two JSP pages:

  • Page 1 (input.jsp): Contains an HTML form with a text field where the user enters a string.
  • Page 2 (display.jsp): Receives the string via HTTP request and displays it.

The string is passed from one page to another using the HTML form's action attribute and retrieved using JSP's built-in request.getParameter() method.


Page 1: input.jsp

<%-- input.jsp : Takes string input from the user --%>
<html>
  <head>
    <title>Input Page</title>
  </head>
  <body>
    <h2>Enter a String</h2>

    <form action="display.jsp" method="post">
      Enter String:
      <input type="text" name="userString" />
        
      <input type="submit" value="Submit" />
    </form>

  </body>
</html>

Explanation:

ElementPurpose
action="display.jsp"Sends form data to display.jsp
method="post"Sends data via HTTP POST method
name="userString"Name used to retrieve value in next page

Page 2: display.jsp

<%-- display.jsp : Displays the string received from input.jsp --%>
<html>
  <head>
    <title>Display Page</title>
  </head>
  <body>
    <h2>Received String</h2>

    <%
      // Retrieve the string sent from input.jsp
      String str = request.getParameter("userString");

      // Check if string is not null or empty
      if (str != null && !str.isEmpty()) {
    %>
        <p>The string entered is: <strong><%= str %></strong></p>
    <%
      } else {
    %>
        <p>No string was entered.</p>
    <%
      }
    %>

    <a href="input.jsp">Go Back</a>

  </body>
</html>

Explanation:

CodePurpose
request.getParameter("userString")Retrieves the value of the text field named userString from Page 1
<%= str %>JSP expression tag to display the value on the page
Null checkPrevents errors if no input is provided

Output

Page 1 (input.jsp):

Enter a String
Enter String: [  Hello TU  ]   [Submit]

Page 2 (display.jsp) after clicking Submit:

Received String
The string entered is: Hello TU

[Go Back]

Key Points to Remember

  • request is a built-in JSP implicit object of type HttpServletRequest.
  • request.getParameter("name") returns the value as a String.
  • method="post" is preferred over method="get" to avoid showing data in the URL.
  • JSP scriptlet tags <% %> are used for Java code and <%= %> for output expressions.
4asked 6xavg 6 marks · DDL and DML Operations using Java, Prepared Statements, Multiple Results, Scrollable Result Sets, Updateable Result Sets, Row Sets and Cached Row Sets, Transactions, SQL Escapes
Answer

What do you mean by SQL escape? Describe about scrollable and updateable result sets. [5]

SQL Escape and Scrollable/Updateable Result Sets


1. SQL Escape

SQL Escape (also called SQL escape syntax) is a standard JDBC mechanism that allows Java programs to use database-independent SQL syntax for features that differ across database vendors (such as date literals, stored procedure calls, outer joins, scalar functions, etc.).

JDBC translates the escape syntax into the database-specific SQL before sending the query, making the code portable across different databases.

Common SQL Escape Syntax:

PurposeEscape Syntax Example
Date literal{d 'yyyy-mm-dd'}
Time literal{t 'hh:mm:ss'}
Timestamp{ts 'yyyy-mm-dd hh:mm:ss'}
Stored procedure call{call procedureName(params)}
Scalar function{fn functionName(args)}
Outer join{oj table1 LEFT OUTER JOIN table2 ON ...}

Example:

String sql = "SELECT * FROM orders WHERE order_date = {d '2024-01-15'}";
PreparedStatement ps = con.prepareStatement(sql);

Here {d '2024-01-15'} is the escape sequence that JDBC translates to the vendor-specific date format automatically.


2. Scrollable Result Sets

By default, a ResultSet in JDBC is forward-only (can only move forward using next()). A Scrollable Result Set allows the cursor to move in both directions and jump to any row.

Types of Scrollable Result Sets:

TypeConstantDescription
Forward OnlyTYPE_FORWARD_ONLYDefault; cursor moves forward only
Scroll InsensitiveTYPE_SCROLL_INSENSITIVEScrollable; does NOT reflect changes made to DB
Scroll SensitiveTYPE_SCROLL_SENSITIVEScrollable; reflects changes made to DB
rs.next();          // Move to next row
rs.previous();      // Move to previous row
rs.first();         // Move to first row
rs.last();          // Move to last row
rs.absolute(n);     // Move to nth row
rs.relative(n);     // Move n rows from current position

Creating a Scrollable Result Set:

Statement stmt = con.createStatement(
    ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_READ_ONLY
);
ResultSet rs = stmt.executeQuery("SELECT * FROM students");

3. Updateable Result Sets

An Updateable Result Set allows the program to insert, update, or delete rows directly through the ResultSet object without writing separate SQL UPDATE/DELETE statements.

Concurrency Modes:

ModeConstantDescription
Read OnlyCONCUR_READ_ONLYDefault; cannot update through ResultSet
UpdatableCONCUR_UPDATABLEAllows updates through ResultSet

Common Update Methods:

rs.updateString("name", "New Name");   // Update a column value
rs.updateRow();                         // Commit the update to DB
rs.deleteRow();                         // Delete current row
rs.moveToInsertRow();                   // Move to insert buffer
rs.insertRow();                         // Insert the new row

4. Scrollable AND Updateable Result Set (Combined)

As stated in the notes, to create a scrollable insensitive result set which is also updatable, the statement must be created with both scroll type and updatable concurrency mode:

Statement stmt = con.createStatement(
    ResultSet.TYPE_SCROLL_INSENSITIVE,   // Scrollable
    ResultSet.CONCUR_UPDATABLE           // Updatable
);
ResultSet rs = stmt.executeQuery("SELECT * FROM students");

// Scroll to row 3 and update
rs.absolute(3);
rs.updateString("name", "Ram Sharma");
rs.updateRow();  // Changes saved to database

Summary Table:

FeatureDefault RSScrollable RSUpdateable RSScrollable + Updateable
Forward onlyYesNoYesNo
BidirectionalNoYesNoYes
Update rowsNoNoYesYes

Key Point: A scrollable updatable result set maintains a cursor that can both scroll (move in any direction) and update rows directly in the underlying database table.

5asked 4xavg 6 marks · due (skipped 2081) · Concurrency
Answer

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.

Most repeated questions

Topics asked at least twice, most-asked first.

asked 8xavg 7 marks · 2081, 2078, 2077, 2076, 2075
Answer

Explain the life cycle of servlets. [5]

Life Cycle of a Servlet

Introduction

A Servlet is a small Java program that executes on the server side of a Web connection and dynamically extends the functionality of a web server. All servlets must implement the Servlet interface, which defines the life-cycle methods. The servlet life cycle is managed by the Servlet Engine (Container).


Stages of the Servlet Life Cycle

The Servlet Life Cycle has 5 stages in general. Three methods are central to the life cycle: init(), service(), and destroy().


Stage 1: Loading and Instantiation

  • The class loader is responsible for loading the servlet class from the file system or network.
  • After loading, the servlet engine creates an instance of the servlet class.
  • The servlet instance is created only once in the servlet life cycle.
  • The servlet engine can instantiate more than one servlet instance if needed (e.g., for load balancing).

Stage 2: Initialization (init())

  • After instantiation, the servlet container calls the init() method.
  • This method is called only once during the entire life of the servlet.
  • It is used to perform one-time initialization tasks such as opening database connections, loading configuration parameters, etc.
  • Signature:
public void init(ServletConfig config) throws ServletException

Stage 3: Request Handling (service())

  • Once initialized, the servlet is ready to handle client requests.
  • For each incoming request, the servlet container calls the service() method.
  • The service() method determines the type of HTTP request (GET, POST, PUT, DELETE, etc.) and dispatches it to the appropriate handler method (doGet(), doPost(), etc.).
  • This method is called multiple times, once per request.
  • Signature:
public void service(ServletRequest req, ServletResponse res)
    throws ServletException, IOException

Stage 4: Destroying (destroy())

  • When the servlet container decides to remove the servlet (e.g., server shutdown or redeployment), it calls the destroy() method.
  • This method is called only once, at the end of the servlet's life.
  • It is used to perform cleanup tasks such as closing database connections, releasing resources, etc.
  • Signature:
public void destroy()

Stage 5: Garbage Collection

  • After destroy() is called, the servlet instance becomes eligible for garbage collection.
  • The JVM's garbage collector reclaims the memory occupied by the servlet object.

Diagram of Servlet Life Cycle

Client Request
      |
      v
[1. Load & Instantiate Servlet Class]
      |
      v
[2. init()  --> Called ONCE]
      |
      v
[3. service() --> Called per request]
   /    \
doGet() doPost() ...
      |
      v
[4. destroy() --> Called ONCE]
      |
      v
[5. Garbage Collection]

Summary Table

StageMethodCalled
Loading & Instantiation(by class loader)Once
Initializationinit()Once
Request Handlingservice()Per request
Destructiondestroy()Once
Garbage Collection(by JVM)Once

Note: The packages java.x.servlet and java.x.servlet.http provide the interfaces and classes required to implement these life-cycle methods. A server such as Apache Tomcat or GlassFish is needed to run servlets.

asked 7xavg 6 marks · 2081, 2080, 2079, 2078, 2077
Answer

Write a program in JSP to display the string taken in one page in another page. [5]

JSP Program to Display String from One Page to Another Page

Concept

This program uses two JSP pages:

  • Page 1 (input.jsp): Contains an HTML form with a text field where the user enters a string.
  • Page 2 (display.jsp): Receives the string via HTTP request and displays it.

The string is passed from one page to another using the HTML form's action attribute and retrieved using JSP's built-in request.getParameter() method.


Page 1: input.jsp

<%-- input.jsp : Takes string input from the user --%>
<html>
  <head>
    <title>Input Page</title>
  </head>
  <body>
    <h2>Enter a String</h2>

    <form action="display.jsp" method="post">
      Enter String:
      <input type="text" name="userString" />
        
      <input type="submit" value="Submit" />
    </form>

  </body>
</html>

Explanation:

ElementPurpose
action="display.jsp"Sends form data to display.jsp
method="post"Sends data via HTTP POST method
name="userString"Name used to retrieve value in next page

Page 2: display.jsp

<%-- display.jsp : Displays the string received from input.jsp --%>
<html>
  <head>
    <title>Display Page</title>
  </head>
  <body>
    <h2>Received String</h2>

    <%
      // Retrieve the string sent from input.jsp
      String str = request.getParameter("userString");

      // Check if string is not null or empty
      if (str != null && !str.isEmpty()) {
    %>
        <p>The string entered is: <strong><%= str %></strong></p>
    <%
      } else {
    %>
        <p>No string was entered.</p>
    <%
      }
    %>

    <a href="input.jsp">Go Back</a>

  </body>
</html>

Explanation:

CodePurpose
request.getParameter("userString")Retrieves the value of the text field named userString from Page 1
<%= str %>JSP expression tag to display the value on the page
Null checkPrevents errors if no input is provided

Output

Page 1 (input.jsp):

Enter a String
Enter String: [  Hello TU  ]   [Submit]

Page 2 (display.jsp) after clicking Submit:

Received String
The string entered is: Hello TU

[Go Back]

Key Points to Remember

  • request is a built-in JSP implicit object of type HttpServletRequest.
  • request.getParameter("name") returns the value as a String.
  • method="post" is preferred over method="get" to avoid showing data in the URL.
  • JSP scriptlet tags <% %> are used for Java code and <%= %> for output expressions.
asked 6xavg 7 marks · 2080, 2079, 2077, 2076, 2075
Answer

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
asked 6xavg 6 marks · 2081, 2080, 2078, 2077, 2076...
Answer

What do you mean by SQL escape? Describe about scrollable and updateable result sets. [5]

SQL Escape and Scrollable/Updateable Result Sets


1. SQL Escape

SQL Escape (also called SQL escape syntax) is a standard JDBC mechanism that allows Java programs to use database-independent SQL syntax for features that differ across database vendors (such as date literals, stored procedure calls, outer joins, scalar functions, etc.).

JDBC translates the escape syntax into the database-specific SQL before sending the query, making the code portable across different databases.

Common SQL Escape Syntax:

PurposeEscape Syntax Example
Date literal{d 'yyyy-mm-dd'}
Time literal{t 'hh:mm:ss'}
Timestamp{ts 'yyyy-mm-dd hh:mm:ss'}
Stored procedure call{call procedureName(params)}
Scalar function{fn functionName(args)}
Outer join{oj table1 LEFT OUTER JOIN table2 ON ...}

Example:

String sql = "SELECT * FROM orders WHERE order_date = {d '2024-01-15'}";
PreparedStatement ps = con.prepareStatement(sql);

Here {d '2024-01-15'} is the escape sequence that JDBC translates to the vendor-specific date format automatically.


2. Scrollable Result Sets

By default, a ResultSet in JDBC is forward-only (can only move forward using next()). A Scrollable Result Set allows the cursor to move in both directions and jump to any row.

Types of Scrollable Result Sets:

TypeConstantDescription
Forward OnlyTYPE_FORWARD_ONLYDefault; cursor moves forward only
Scroll InsensitiveTYPE_SCROLL_INSENSITIVEScrollable; does NOT reflect changes made to DB
Scroll SensitiveTYPE_SCROLL_SENSITIVEScrollable; reflects changes made to DB
rs.next();          // Move to next row
rs.previous();      // Move to previous row
rs.first();         // Move to first row
rs.last();          // Move to last row
rs.absolute(n);     // Move to nth row
rs.relative(n);     // Move n rows from current position

Creating a Scrollable Result Set:

Statement stmt = con.createStatement(
    ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_READ_ONLY
);
ResultSet rs = stmt.executeQuery("SELECT * FROM students");

3. Updateable Result Sets

An Updateable Result Set allows the program to insert, update, or delete rows directly through the ResultSet object without writing separate SQL UPDATE/DELETE statements.

Concurrency Modes:

ModeConstantDescription
Read OnlyCONCUR_READ_ONLYDefault; cannot update through ResultSet
UpdatableCONCUR_UPDATABLEAllows updates through ResultSet

Common Update Methods:

rs.updateString("name", "New Name");   // Update a column value
rs.updateRow();                         // Commit the update to DB
rs.deleteRow();                         // Delete current row
rs.moveToInsertRow();                   // Move to insert buffer
rs.insertRow();                         // Insert the new row

4. Scrollable AND Updateable Result Set (Combined)

As stated in the notes, to create a scrollable insensitive result set which is also updatable, the statement must be created with both scroll type and updatable concurrency mode:

Statement stmt = con.createStatement(
    ResultSet.TYPE_SCROLL_INSENSITIVE,   // Scrollable
    ResultSet.CONCUR_UPDATABLE           // Updatable
);
ResultSet rs = stmt.executeQuery("SELECT * FROM students");

// Scroll to row 3 and update
rs.absolute(3);
rs.updateString("name", "Ram Sharma");
rs.updateRow();  // Changes saved to database

Summary Table:

FeatureDefault RSScrollable RSUpdateable RSScrollable + Updateable
Forward onlyYesNoYesNo
BidirectionalNoYesNoYes
Update rowsNoNoYesYes

Key Point: A scrollable updatable result set maintains a cursor that can both scroll (move in any direction) and update rows directly in the underlying database table.

asked 4xavg 6 marks · 2080, 2079, 2077, 2075
Answer

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.

asked 4xavg 8 marks · 2081, 2078, 2075
Answer

What are the tasks of sliders and scroll pane? Explain any four types of layout manager.[10]

Tasks of Sliders and Scroll Pane, and Four Types of Layout Manager


Part 1: Tasks of Sliders and Scroll Pane

Sliders

A Slider is a GUI component that allows the user to select a numeric value by sliding a knob (thumb) along a track between a defined minimum and maximum value.

Tasks of Sliders:

  • Allow the user to select a value from a continuous or discrete range of values (e.g., volume control, brightness control).
  • Display the current value visually through the position of the knob on the track.
  • Support both horizontal and vertical orientations.
  • Can display tick marks and tick labels to indicate specific values along the track.
  • Fire ChangeEvent whenever the slider value changes, allowing the program to respond to user interaction.
  • Can be set with a minimum, maximum, and initial (default) value.
  • Support snap-to-ticks feature so the knob snaps to the nearest tick mark.

Example:

JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 50);
slider.setMajorTickSpacing(10);
slider.setPaintTicks(true);
slider.setPaintLabels(true);

Scroll Pane:

"ScrollPane is used to make a scrollable view of a component. When screen size is limited, we use a scroll pane to display a large component."

Tasks of Scroll Pane:

  • Provide a scrollable view of a component that is too large to fit in the available screen area.
  • Automatically display horizontal and/or vertical scroll bars when the content exceeds the visible area.
  • Allow the user to scroll through large content such as large images, long text areas, or large tables.
  • Manage the viewport (the visible portion of the component at any given time).
  • Can be configured to show scroll bars always, never, or only when needed.
  • Wrap components like JTextArea, JTable, JList, or JTree to make them scrollable.

Example:

JTextArea textArea = new JTextArea(5, 30);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

Part 2: Four Types of Layout Manager

A Layout Manager in Java is an object that controls the size and position of components within a container. Java provides several built-in 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, components wrap to the next row.
  • Alignment can be set to LEFT, RIGHT, or CENTER (default is CENTER).
  • Gaps between components can be specified (horizontal and vertical gaps).

Example:

JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));
panel.add(new JButton("Button 3"));

Diagram:

[ Button1 ] [ Button2 ] [ Button3 ]
[ Button4 ] [ Button5 ]

2. BorderLayout

BorderLayout is the default layout manager for JFrame and JDialog. It divides the container into five regions: North, South, East, West, and Center.

Key Features:

  • Each region can hold only one component.
  • The Center region expands to fill all remaining space.
  • North and South regions stretch horizontally.
  • East and West regions stretch vertically.
  • If a region is not used, the Center expands to fill that space.

Example:

JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(new JButton("North"),  BorderLayout.NORTH);
frame.add(new JButton("South"),  BorderLayout.SOUTH);
frame.add(new JButton("East"),   BorderLayout.EAST);
frame.add(new JButton("West"),   BorderLayout.WEST);
frame.add(new JButton("Center"), BorderLayout.CENTER);

Diagram:

+---------------------------+
|          NORTH            |
+------+------------+-------+
| WEST |   CENTER   | EAST  |
+------+------------+-------+
|          SOUTH            |
+---------------------------+

3. GridLayout

GridLayout arranges components in a rectangular grid of rows and columns. Every cell in the grid is of equal size, and each component fills its cell completely.

Key Features:

  • Components are placed row by row, left to right, top to bottom.
  • All cells have the same width and height.
  • The number of rows and columns is specified at creation.
  • Horizontal and vertical gaps between cells can be set.

Example:

JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2, 5, 5)); // 3 rows, 2 cols
panel.add(new JButton("1"));
panel.add(new JButton("2"));
panel.add(new JButton("3"));
panel.add(new JButton("4"));
panel.add(new JButton("5"));
panel.add(new JButton("6"));

Diagram:

+--------+--------+
|   1    |   2    |
+--------+--------+
|   3    |   4    |
+--------+--------+
|   5    |   6    |
+--------+--------+

4. GridBagLayout:

"GridBagLayout is a sophisticated, flexible layout manager that aligns components vertically, horizontally, or along their baseline, without requiring that the components be of the same size."

Key Features:

  • Components are placed on a grid of rows and columns, but unlike GridLayout, cells can span multiple rows/columns and can be of different sizes.
  • Each component's placement and sizing is controlled by a GridBagConstraints object (gridx, gridy, gridwidth, gridheight, weightx, weighty, fill, anchor, insets).
  • It is the most flexible but also the most complex layout manager in the AWT/Swing family.

Example:

JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();

gbc.gridx = 0; gbc.gridy = 0;
panel.add(new JButton("Button 1"), gbc);

gbc.gridx = 1; gbc.gridy = 0;
panel.add(new JButton("Button 2"), gbc);
asked 4xavg 6 marks · 2081, 2080, 2077, 2076
Answer

Assume that a text file named 'ONE.TXT' contains a paragraph of text. Write a program to copy the word that starts with vowel from 'ONE.TXT' to another file 'TWO.TXT'. [5]

Copying Words Starting with Vowels from ONE.TXT to TWO.TXT

Approach

  • Read the content of ONE.TXT word by word
  • Check if each word starts with a vowel (a, e, i, o, u -- both uppercase and lowercase)
  • If yes, write that word to TWO.TXT

Java Program

import java.io.*;

public class CopyVowelWords {

    public static void main(String[] args) {

        // Declare file reader and writer references
        BufferedReader br = null;
        BufferedWriter bw = null;

        try {
            // Open ONE.TXT for reading
            br = new BufferedReader(new FileReader("ONE.TXT"));

            // Open TWO.TXT for writing
            bw = new BufferedWriter(new FileWriter("TWO.TXT"));

            String line;

            // Read file line by line
            while ((line = br.readLine()) != null) {

                // Split each line into words by spaces/punctuation
                String[] words = line.split("[\\s.,;:!?]+");

                for (String word : words) {

                    // Check if word is non-empty
                    if (word.length() > 0) {

                        // Get the first character of the word
                        char firstChar = word.charAt(0);

                        // Check if first character is a vowel
                        if (firstChar == 'a' || firstChar == 'e' ||
                            firstChar == 'i' || firstChar == 'o' ||
                            firstChar == 'u' || firstChar == 'A' ||
                            firstChar == 'E' || firstChar == 'I' ||
                            firstChar == 'O' || firstChar == 'U') {

                            // Write the vowel-starting word to TWO.TXT
                            bw.write(word);
                            bw.newLine();
                        }
                    }
                }
            }

            System.out.println("Words starting with vowels copied to TWO.TXT successfully.");

        } catch (FileNotFoundException e) {
            System.out.println("File ONE.TXT not found: " + e.getMessage());

        } catch (IOException e) {
            System.out.println("IO Error occurred: " + e.getMessage());

        } finally {
            // Close streams in finally block to ensure they always close
            try {
                if (br != null) br.close();
                if (bw != null) bw.close();
            } catch (IOException e) {
                System.out.println("Error closing files: " + e.getMessage());
            }
        }
    }
}

Sample Input (ONE.TXT)

An apple is a fruit. Orange and mango are tasty.
Every student enjoys learning.

Sample Output (TWO.TXT)

An
apple
is
a
Orange
and
are
Every
enjoys

Key Points

ConceptDetail
FileReaderReads characters from ONE.TXT
BufferedReaderReads line by line efficiently
FileWriterWrites characters to TWO.TXT
BufferedWriterWrites output efficiently
split("[\\s.,;:!?]+")Splits line into individual words
charAt(0)Gets the first character of each word
finally blockEnsures streams are always closed
asked 3xavg 7 marks · 2079, 2076, 2075
Answer

Explain feature of object-oriented programming. Create a class Distance with private variables feet of type integer and inches of type floating point. Use suitable constructor, and methods for adding and comparing two distance objects. [Hint: 1 feet = 12 inches][10]

--- OOP is a programming paradigm that organizes software as a collection of objects combining data and behaviour. The key features are: - A class is a blueprint or template that defines attributes (data) and methods (behaviour). - An ob...

asked 3xavg 5 marks · 2080, 2079, 2078
Answer

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 -----------------...

asked 3xavg 7 marks · 2077, 2076, 2075
Answer

What is the significance of stub and skeleton in RMI? Create a RMI application such that a client sends an Integer number to the server and the server return the factorial value of that integer. Give a clear specification for every step.[10]

--- RMI (Remote Method Invocation) is a Java API that provides a mechanism to create distributed applications. It allows an object in one JVM to invoke methods on an object running in another JVM. The two key objects that enable this rem...

asked 3xavg 7 marks · 2081, 2079, 2076
Answer

Describe any two types of events. [5]

In Java, an event is an object that describes a state change in a source. Events are generated when a user interacts with GUI components such as clicking a button, pressing a key, moving the mouse, etc. Java uses the Delegation Event Mod...

asked 3xavg 5 marks · 2081, 2080, 2078
Answer

How do you write an IDL file and generate the stub and skeleton code for CORBA implementation? Explain. [5]

Writing IDL File and Generating Stub/Skeleton Code for CORBA Implementation

What is IDL in CORBA?

CORBA (Common Object Request Broker Architecture) uses Interface Definition Language (IDL) to separate the interface from the implementation. IDL is language-neutral, meaning the same IDL file can be used to generate code in Java, C++, Python, or any other supported language. This is a key advantage of CORBA over RMI, which is Java-specific.


Steps to Write an IDL File and Generate Stub/Skeleton

Step 1: Write the IDL File

An IDL file defines the interface (methods/operations) that the remote object will expose. It does not contain any implementation logic.

Syntax/Structure of an IDL file:

module ModuleName {
    interface InterfaceName {
        returnType methodName(in paramType paramName);
    };
};

Example: Hello.idl

module HelloApp {
    interface Hello {
        string sayHello();
        oneway void shutdown();
    };
};
  • module acts like a Java package (namespace).
  • interface declares the remote methods.
  • in means the parameter is passed from client to server.
  • oneway means the method is asynchronous (no return value, no blocking).
  • string is an IDL primitive type (maps to java.lang.String in Java).

Step 2: Compile the IDL File to Generate Stub and Skeleton

Use the idlj compiler (IDL-to-Java compiler) that comes with the JDK.

Command:

idlj -fall Hello.idl
  • -fall flag generates both client-side stub and server-side skeleton.
  • -fclient generates only the client stub.
  • -fserver generates only the server skeleton.

Step 3: Files Generated by idlj

After running the command, the following files are generated inside the HelloApp folder:

Generated FilePurpose
_HelloStub.javaClient-side stub - acts as proxy for the client
HelloOperations.javaInterface containing method signatures
Hello.javaJava interface extending CORBA Object
HelloHelper.javaHelper class for narrowing object references
HelloHolder.javaHolder class for out/inout parameters
HelloPOA.javaServer-side skeleton (Portable Object Adapter)

Step 4: Implement the Server (using the Skeleton)

import HelloApp.*;
import org.omg.CORBA.*;
import org.omg.PortableServer.*;

public class HelloImpl extends HelloPOA {
    public String sayHello() {
        return "Hello from CORBA Server!";
    }
    public void shutdown() {
        // shutdown logic
    }
}
  • The server class extends HelloPOA (the generated skeleton).

Step 5: Implement the Client (using the Stub)

import HelloApp.*;
import org.omg.CORBA.*;
import org.omg.CosNaming.*;

public class HelloClient {
    public static void main(String[] args) throws Exception {
        ORB orb = ORB.init(args, null);
        // Locate the remote object and invoke method
        Hello helloRef = HelloHelper.narrow(
            orb.string_to_object("corbaname::localhost#Hello")
        );
        System.out.println(helloRef.sayHello());
    }
}
  • The client uses HelloHelper.narrow() to get a reference to the remote object.
  • The stub (_HelloStub) handles all network communication transparently.

Summary Diagram

Hello.idl
    |
    | idlj -fall Hello.idl
    |
    +---> _HelloStub.java   (Client Stub)
    +---> HelloPOA.java     (Server Skeleton)
    +---> Hello.java, HelloHelper.java, etc.
    
Client uses Stub --> ORB --> Skeleton --> Server Implementation

Key Points to Remember

  • IDL is language-independent; it only defines the interface, not the implementation.
  • The stub resides on the client side and acts as a local proxy.
  • The skeleton resides on the server side and delegates calls to the actual object.
  • CORBA passes objects by reference (unlike RMI which can pass by value or reference).
  • The ORB (Object Request Broker) handles all communication between stub and skeleton.
asked 2xavg 5 marks · 2079, 2078
Answer

What is JavaFX? Compare it with swing. Explain FlowPane layout of JavaFX. [5]

JavaFX: Definition, Comparison with Swing, and FlowPane Layout


1. What is JavaFX?

JavaFX is a modern Java platform that provides support for creating rich desktop applications. It offers a wide range of features including support for 2D and 3D graphics, CSS-based styling, and XML-based UI design (using FXML). JavaFX was introduced as a successor to Swing for building graphical user interfaces in Java.


2. Comparison: JavaFX vs Swing

FeatureSwingJavaFX
PurposeStandard toolkit for Java developers for creating GUIProvides platform support for creating modern desktop applications
GUI ComponentsHas a more sophisticated and larger set of GUI componentsHas decent but comparatively fewer GUI components
CSS / XML SupportDoes NOT support customization using CSS and XMLSupports customization using CSS and XML
3D ApplicationsVery difficult to create beautiful 3D applicationsCan easily create beautiful 3D applications
RelationshipActs as a legacy UI component libraryHas several components built over Swing

3. FlowPane Layout in JavaFX

JavaFX provides the following built-in layout panes:

  • FlowPane, HBox, VBox, BorderPane, GridPane

Definition

FlowPane is a layout pane in JavaFX that organizes nodes in a flow that wraps at the FlowPane's boundary.

Types of FlowPane

TypeBehavior
Horizontal FlowPaneArranges nodes in a row and wraps them according to the FlowPane's width
Vertical FlowPaneArranges nodes in a column and wraps them according to the FlowPane's height

Key Points

  • Nodes are placed one after another (horizontally or vertically).
  • When the available space runs out, nodes wrap to the next row or column automatically.
  • This is similar in concept to Java AWT's FlowLayout, but designed specifically for JavaFX.

Example Code

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;

public class FlowPaneExample extends Application {
    @Override
    public void start(Stage primaryStage) {
        FlowPane flowPane = new FlowPane();

        // Adding buttons to FlowPane
        flowPane.getChildren().add(new Button("Button 1"));
        flowPane.getChildren().add(new Button("Button 2"));
        flowPane.getChildren().add(new Button("Button 3"));

        Scene scene = new Scene(flowPane, 300, 200);
        primaryStage.setTitle("FlowPane Example");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

How it Works

  • Buttons are added to the FlowPane one after another.
  • When the width of the pane is exceeded, the remaining buttons wrap to the next line automatically.
  • This makes FlowPane very useful for dynamic, resizable UIs.

Summary: JavaFX is a modern GUI framework for Java that improves upon Swing with CSS/XML support and 3D capabilities. FlowPane is one of its core layout managers that arranges nodes in a flowing, wrapping manner either horizontally or vertically.

asked 2xavg 5 marks · 2079, 2075
Answer

Write short notes on: a. Final class b. Result set [2.5+2.5]

--- The final modifier in Java is used for finalizing the implementations of classes, methods, and variables. A final class is a class that is declared using the final keyword. Once a class is declared as final, it cannot be subclassed (...

asked 2xavg 8 marks · 2077, 2076
Answer

When does the finally block is mandatory in while handling exception? Describe with a suitable scenario. [5]

The finally block in Java is a block that always executes regardless of whether an exception occurs or not. It is used to place important cleanup code such as closing connections, releasing resources, or closing files. --- The finally bl...

Study every one of these with model answers, flashcards, and MCQs.

Open CSC419 study modes