2082

BIT401 · TU past paper

Advanced Java Programming 2082 question paper

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

Past Papers208220812080

Tap a question to open its answer.

  1. 110 marksCustom exception throwingAnswer

    List some features of Java. What are the types of exception? Write a program to take input an integer from the user and if the given integer is negative throw the exception.[10]

    Model Answer: Features of Java, Exception Types, and Exception Handling Program

    Features of Java (3 marks)

    Key features of Java include:

    1. Object-Oriented: Java is purely object-oriented, based on classes and objects. Everything is an object except primitive data types.

    2. Platform Independent: Java follows "Write Once, Run Anywhere" (WORA) principle. Code compiled to bytecode runs on any platform with JVM.

    3. Simple and Familiar: Java syntax is similar to C/C++, making it easy to learn for programmers familiar with these languages.

    4. Secure: Java provides built-in security features like bytecode verification, exception handling, and no pointer arithmetic.

    5. Robust: Strong memory management, automatic garbage collection, and exception handling make Java robust.

    6. Multithreaded: Java supports concurrent programming through built-in threading capabilities.

    7. Dynamic: Java supports dynamic loading of classes at runtime.


    Types of Exceptions (3 marks)

    Exceptions in Java are classified as:

    1. Checked Exceptions

    • Exceptions that must be caught or declared in the method signature
    • Checked at compile time
    • Examples: IOException, SQLException, FileNotFoundException

    2. Unchecked Exceptions

    • Exceptions that need not be caught or declared
    • Checked at runtime
    • Derived from RuntimeException class
    • Examples: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException

    3. Error

    • Serious problems that should not be caught
    • Examples: StackOverflowError, OutOfMemoryError

    Program: Exception Handling for Negative Integer (4 marks)

    import java.util.Scanner;
    
    public class NegativeNumberException {
        
        // Custom exception class
        static class NegativeNumberException extends Exception {
            public NegativeNumberException(String message) {
                super(message);
            }
        }
        
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            
            try {
                System.out.print("Enter an integer: ");
                int number = sc.nextInt();
                
                // Check if number is negative and throw exception
                if (number < 0) {
                    throw new NegativeNumberException("Error: Negative number not allowed!");
                }
                
                System.out.println("You entered: " + number);
                
            } catch (NegativeNumberException e) {
                System.out.println("Exception caught: " + e.getMessage());
            } finally {
                sc.close();
                System.out.println("Program terminated.");
            }
        }
    }
    

    Output Example:

    Enter an integer: -5
    Exception caught: Error: Negative number not allowed!
    Program terminated.
    

    Explanation:

    • A custom exception class NegativeNumberException extends Exception (checked exception)
    • User input is taken using Scanner
    • If the number is negative, the exception is thrown with a message
    • The catch block handles the thrown exception
    • The finally block executes regardless of exception occurrence
  2. 210 marksLayout managersAnswer

    Distinguish between component and containers. What do you mean by keyboard mnemonics and accelerators? Illustrate the concept of Grid layout with an example.[10]

    Model Answer: Components, Containers, Mnemonics, Accelerators, and Grid Layout

    1. Components vs Containers

    Components:

    • Basic building blocks of GUI applications
    • Lightweight objects that represent visual elements
    • Examples: JButton, JLabel, JTextField, JCheckBox, JRadioButton
    • Cannot contain other components
    • Directly display information or accept user input
    • Have their own appearance and behavior

    Containers:

    • Special components that can hold other components
    • Used to organize and manage groups of components
    • Examples: JFrame, JPanel, JDialog, JWindow
    • Provide layout management for contained components
    • Inherit from Component class but add containment capability
    • Manage the positioning and sizing of child components

    Key Distinction: Containers are components that can contain other components, whereas components are atomic UI elements that cannot contain other components.


    2. Keyboard Mnemonics and Accelerators

    Keyboard Mnemonics:

    • Single character shortcuts that activate a button or menu item
    • Accessed by pressing Alt + the mnemonic key
    • Underlined character in the button/menu label
    • Example: In a button labeled "Save", 'S' is the mnemonic
    • User presses Alt+S to activate the button
    • Provides keyboard navigation for accessibility

    Accelerators:

    • Keyboard shortcuts that directly invoke an action without focus requirement
    • Typically use Ctrl key combined with another key
    • Example: Ctrl+S for Save, Ctrl+C for Copy
    • Work globally regardless of which component has focus
    • Faster than mnemonics for experienced users
    • Commonly used in menu items

    Difference: Mnemonics require Alt key and component focus; accelerators work globally with Ctrl (or other modifier) combinations.


    3. Grid Layout with Example

    Grid Layout Concept:

    • Arranges components in a rectangular grid of rows and columns
    • All components are given equal size
    • Components fill the grid cells uniformly
    • Useful for creating uniform button arrays or form layouts

    Constructor:

    GridLayout(int rows, int columns)
    GridLayout(int rows, int columns, int hgap, int vgap)
    

    Where hgap and vgap are horizontal and vertical gaps between components.

    Example Code:

    import javax.swing.*;
    import java.awt.*;
    
    public class GridLayoutExample extends JFrame {
        public GridLayoutExample() {
            setTitle("Grid Layout Demo");
            setSize(300, 300);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
            // Create panel with GridLayout (3 rows, 3 columns)
            JPanel panel = new JPanel(new GridLayout(3, 3, 5, 5));
            
            // Add 9 buttons
            for (int i = 1; i <= 9; i++) {
                JButton btn = new JButton("Button " + i);
                panel.add(btn);
            }
            
            add(panel);
            setVisible(true);
        }
        
        public static void main(String[] args) {
            new GridLayoutExample();
        }
    }
    

    Output: Creates a 3x3 grid of 9 equal-sized buttons with 5-pixel gaps between them.


    Total Answer Length: Appropriate for 10 marks with clear distinctions, definitions, and practical example.

  3. 310 marksJSP implicit objects and their purposesAnswer

    What are the purposes of JSP implicit objects? Describe the methods of writing servlet program with example.[10]

    JSP Implicit Objects and Servlet Programming

    Part 1: Purposes of JSP Implicit Objects

    JSP implicit objects are pre-defined objects automatically available in JSP pages without explicit declaration. Their main purposes are:

    1. Request Handling

    • request object: Captures HTTP request parameters, headers, and cookies sent by the client
    • Purpose: Access form data, query strings, and request metadata

    2. Response Management

    • response object: Sends data back to the client
    • Purpose: Set response headers, cookies, and redirect requests

    3. Session Management

    • session object: Maintains user-specific data across multiple requests
    • Purpose: Store and retrieve user information during a session

    4. Application Scope

    • application object: Shares data across all users and sessions
    • Purpose: Store global application-level information

    5. Page Context

    • pageContext object: Provides access to all page-level objects and attributes
    • Purpose: Manage page scope variables and forward/include requests

    6. Output Stream

    • out object: Writes content to the response stream
    • Purpose: Display dynamic content to the client

    7. Configuration

    • config object: Accesses servlet configuration parameters
    • Purpose: Retrieve initialization parameters

    8. Exception Handling

    • exception object: Handles runtime errors (available in error pages)
    • Purpose: Access error information and stack traces

    Part 2: Methods of Writing Servlet Programs

    Method 1: Extending HttpServlet Class

    This is the standard approach where a servlet extends HttpServlet and overrides doGet() and/or doPost() methods.

    Example:

    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    
    public class HelloServlet extends HttpServlet {
        
        public void doGet(HttpServletRequest request, 
                          HttpServletResponse response) 
                          throws ServletException, IOException {
            
            // Set response content type
            response.setContentType("text/html");
            
            // Get output stream
            PrintWriter out = response.getWriter();
            
            // Write HTML response
            out.println("<html>");
            out.println("<body>");
            out.println("<h1>Hello from Servlet!</h1>");
            out.println("</body>");
            out.println("</html>");
            
            out.close();
        }
        
        public void doPost(HttpServletRequest request, 
                           HttpServletResponse response) 
                           throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    Method 2: Handling Request Parameters

    Servlets can retrieve and process form data submitted by clients.

    Example:

    public void doPost(HttpServletRequest request, 
                       HttpServletResponse response) 
                       throws ServletException, IOException {
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        // Get parameters from request
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        
        out.println("<html><body>");
        out.println("<h2>User Information</h2>");
        out.println("<p>Name: " + name + "</p>");
        out.println("<p>Email: " + email + "</p>");
        out.println("</body></html>");
        
        out.close();
    }
    

    Method 3: Using Session Management

    Servlets can maintain user sessions across multiple requests.

    Example:

    public void doGet(HttpServletRequest request, 
                      HttpServletResponse response) 
                      throws ServletException, IOException {
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        // Get or create session
        HttpSession session = request.getSession();
        
        // Store data in session
        session.setAttribute("username", "john_doe");
        
        // Retrieve data from session
        String user = (String) session.getAttribute("username");
        
        out.println("<html><body>");
        out.println("<p>Welcome: " + user + "</p>");
        out.println("</body></html>");
        
        out.close();
    }
    

    Key Points:

    • doGet(): Handles GET requests (URL parameters)
    • doPost(): Handles POST requests (form data)
    • HttpServletRequest: Provides access to request data
    • HttpServletResponse: Used to send response to client
    • PrintWriter: Output stream for writing response content

    These methods form the foundation of server-side Java web development and are essential for building dynamic web applications.

  4. 45 marksRandom file accessAnswer

    How do you access file randomly? Give an example. [5]

    Random file access (also called direct access or seek access) allows you to read or write data at any position in a file without having to read through all preceding data sequentially. This is in contrast to sequential access where you m...

  5. 55 marksText boxes and text fieldsAnswer

    Design a form that contains two text fields and two buttons with caption 'OK' and 'CANCEL' using AWT. [5]

    Model Answer: AWT Form with Text Fields and Buttons

    Program Code:

    import java.awt.*;
    import java.awt.event.*;
    
    public class SimpleForm extends Frame {
        
        // Declare components
        TextField textField1, textField2;
        Button okButton, cancelButton;
        
        // Constructor
        public SimpleForm() {
            // Set frame properties
            setTitle("Simple Form");
            setSize(300, 200);
            setLayout(new FlowLayout());
            
            // Create and add labels
            add(new Label("Field 1:"));
            
            // Create first text field
            textField1 = new TextField(20);
            add(textField1);
            
            add(new Label("Field 2:"));
            
            // Create second text field
            textField2 = new TextField(20);
            add(textField2);
            
            // Create OK button
            okButton = new Button("OK");
            add(okButton);
            
            // Create CANCEL button
            cancelButton = new Button("CANCEL");
            add(cancelButton);
            
            // Add event listeners
            okButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println("Field 1: " + textField1.getText());
                    System.out.println("Field 2: " + textField2.getText());
                }
            });
            
            cancelButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
                }
            });
            
            // Handle window close
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
            
            setVisible(true);
        }
        
        // Main method
        public static void main(String[] args) {
            new SimpleForm();
        }
    }
    

    Key Components Explained:

    ComponentPurpose
    FrameContainer window for the form
    TextFieldInput fields for user data (2 fields)
    ButtonClickable buttons with captions 'OK' and 'CANCEL'
    FlowLayoutArranges components in a row
    ActionListenerHandles button click events

    Output:

    • Form displays with two text input fields
    • Two buttons labeled "OK" and "CANCEL"
    • OK button prints field values to console
    • CANCEL button closes the application
  6. 65 marksDatabase connection from JSPAnswer

    How do you connect database using JSP? [5]

    • Use Class.forName() to dynamically load the database driver - For MySQL, use com.mysql.jdbc.Driver - For other databases, use appropriate driver class names - Use DriverManager.getConnection() with three parameters: - URL: Connection s...
  7. 75 marksMouse events and keyboard eventsAnswer

    Write a program to illustrate the concept of Mouse Events. [5]

    Event Type Method Description -------------------------------- Mouse Click mouseClicked() Triggered when mouse button is clicked Mouse Press mousePressed() Triggered when mouse button is pressed down Mouse Release mouseReleased() Trigger...

  8. 85 marksJavaFX layoutsAnswer

    Describe any two JavaFX layouts. [5]

    Model Answer: Two JavaFX Layouts

    1. BorderPane Layout

    BorderPane is a layout container that arranges child nodes in five regions: top, bottom, left, right, and center.

    • Structure: The center region occupies the maximum available space, while the other four regions size themselves based on their content
    • Use case: Ideal for creating application layouts with a menu bar at the top, toolbars on sides, and main content in the center
    • Properties: Each region can hold a single node; if multiple nodes are needed, wrap them in another container (e.g., VBox, HBox)
    • Example structure:
      ┌─────────────────────┐
      │       TOP           │
      ├──────┬───────┬──────┤
      │      │       │      │
      │ LEFT │CENTER │RIGHT │
      │      │       │      │
      ├──────┴───────┴──────┤
      │      BOTTOM         │
      └─────────────────────┘
      

    2. GridPane Layout

    GridPane is a layout container that arranges child nodes in a flexible grid of rows and columns.

    • Structure: Nodes are positioned using row and column indices; cells can span multiple rows/columns
    • Flexibility: Rows and columns automatically adjust their size based on content; can set preferred widths/heights
    • Properties: Supports gap spacing between rows and columns, alignment, and padding
    • Use case: Suitable for form layouts, data tables, and any grid-based arrangement of controls
    • Example: A login form with labels in column 0 and text fields in column 1, arranged across multiple rows

    Key Difference: BorderPane provides a fixed five-region layout, while GridPane offers flexible row-column positioning for more complex arrangements.

  9. 95 marksHandling multiple result setsAnswer

    How do you handle multiple results in JDBC? Explain. [5]

    Handling Multiple Results in JDBC

    Answer

    Handling multiple results in JDBC involves managing situations where a single SQL statement execution returns more than one result set. This typically occurs with stored procedures or batch operations. Here's how to handle them:

    1. Using execute() Method

    The execute() method returns a boolean indicating whether the first result is a ResultSet:

    Statement stmt = connection.createStatement();
    boolean isResultSet = stmt.execute(sqlQuery);
    
    if (isResultSet) {
        ResultSet rs = stmt.getResultSet();
        // Process first result set
    } else {
        int updateCount = stmt.getUpdateCount();
        // Process update count
    }
    

    2. Processing Multiple Result Sets

    Use getMoreResults() to move through subsequent result sets:

    Statement stmt = connection.createStatement();
    stmt.execute(sqlQuery);
    
    int resultIndex = 0;
    while (true) {
        ResultSet rs = stmt.getResultSet();
        if (rs != null) {
            // Process current result set
            while (rs.next()) {
                // Handle row data
            }
            resultIndex++;
        }
        
        // Move to next result
        if (!stmt.getMoreResults()) {
            break;
        }
    }
    

    3. Handling Update Counts

    Distinguish between result sets and update counts:

    int result = stmt.getUpdateCount();
    if (result == -1) {
        // No more results
    } else if (result == 0) {
        // Update/Insert/Delete executed
    } else {
        // Number of rows affected
    }
    

    4. Key Methods

    MethodPurpose
    execute()Returns true if result is ResultSet, false if update count
    getResultSet()Retrieves current ResultSet
    getUpdateCount()Gets number of rows affected
    getMoreResults()Moves to next result; returns true if ResultSet exists

    5. Best Practice

    Always close resources properly:

    try {
        // Process multiple results
    } finally {
        if (rs != null) rs.close();
        if (stmt != null) stmt.close();
    }
    

    This approach ensures efficient handling of complex SQL operations returning multiple result sets.

  10. 105 marksTCP socket programming stepsAnswer

    Mention the steps to write the socket program using TCP. [5]

    Model Answer: Steps to Write a Socket Program Using TCP

    Since reference notes are not provided, this answer follows standard TCP socket programming methodology taught in BSc CSIT curricula:

    Server-Side Steps:

    1. Create a Socket

      • Use socket() system call to create a socket with domain (AF_INET), type (SOCK_STREAM), and protocol (0 or IPPROTO_TCP)
    2. Bind the Socket

      • Use bind() to associate the socket with a specific port number and IP address
      • Define server address structure with port and address family
    3. Listen for Connections

      • Use listen() to mark the socket as passive and specify the backlog queue size for pending connections
    4. Accept Client Connection

      • Use accept() to accept incoming client connections
      • Creates a new socket for communication with the connected client
    5. Send/Receive Data

      • Use send() or write() to transmit data to the client
      • Use recv() or read() to receive data from the client
    6. Close the Socket

      • Use close() to terminate the connection and release resources

    Client-Side Steps:

    1. Create a Socket

      • Use socket() with same parameters as server
    2. Connect to Server

      • Use connect() to establish connection to server's IP address and port
    3. Send/Receive Data

      • Use send() or write() to send data to server
      • Use recv() or read() to receive data from server
    4. Close the Socket

      • Use close() to terminate connection

    Key Point: TCP ensures reliable, ordered, connection-oriented communication between client and server.

  11. 115 marksRMI versus CORBA comparisonAnswer

    Differentiate between RMI and CORBA. [5]

    Model Answer: RMI vs CORBA

    Key Differences

    AspectRMICORBA
    LanguageJava-onlyLanguage-independent
    PlatformPlatform-dependentPlatform-independent
    ProtocolJava Remote Method Protocol (JRMP)Internet Inter-ORB Protocol (IIOP)
    ComplexitySimpler to implementMore complex
    PerformanceFaster (optimized for Java)Slower (due to protocol overhead)
    InteroperabilityLimited to Java systemsWorks across different languages and platforms

    Detailed Comparison

    RMI (Remote Method Invocation):

    • Designed specifically for Java-to-Java communication
    • Uses serialization for object marshalling
    • Tightly coupled to Java Virtual Machine (JVM)
    • Easier learning curve for Java developers
    • Better performance within homogeneous Java environments

    CORBA (Common Object Request Broker Architecture):

    • Vendor-neutral, language-neutral standard
    • Supports multiple programming languages (C++, Python, Ada, etc.)
    • Uses Interface Definition Language (IDL) for service definition
    • Provides greater flexibility for heterogeneous systems
    • Suitable for enterprise-wide distributed systems with mixed technologies

    When to Use

    • Use RMI: When building distributed systems entirely in Java
    • Use CORBA: When integrating systems written in different programming languages or across diverse platforms

    Note: This answer is based on standard distributed systems concepts. Refer to your course materials for any institution-specific emphasis.

  12. 125 marksType 0 JDBC driverAnswer

    What is Type 0 JDBC driver? Discuss about UDP. [5]

    Model Answer: Type 0 JDBC Driver and UDP

    Type 0 JDBC Driver

    Type 0 JDBC Driver (also called the JDBC-ODBC Bridge Driver) is a bridge-based driver that acts as a middleware between Java applications and databases through ODBC (Open Database Connectivity).

    Key Characteristics:

    • Architecture: Uses ODBC drivers installed on the client machine to communicate with the database
    • Connection Path: Java Application → JDBC Driver → ODBC Driver → Database
    • Platform Dependency: Requires ODBC drivers to be installed and configured on the client system
    • Performance: Slower due to multiple layers of translation and bridging
    • Usage: Primarily used for legacy systems and when ODBC drivers are already available

    Limitations:

    • Not suitable for web applications (ODBC not available on web servers)
    • Performance overhead from bridge translation
    • Deprecated in modern Java versions (removed from Java 8 onwards)

    UDP (User Datagram Protocol)

    UDP is a connectionless, unreliable transport layer protocol (Layer 4 of OSI model) used for fast data transmission.

    Key Characteristics:

    FeatureDetails
    ConnectionConnectionless - no handshake required
    ReliabilityUnreliable - no guarantee of delivery
    OrderingPackets may arrive out of order
    SpeedFast transmission with minimal overhead
    Header Size8 bytes (smaller than TCP)
    Flow ControlNo flow control mechanism

    Applications:

    • Video/audio streaming
    • Online gaming
    • DNS queries
    • VoIP
    • Real-time applications where speed matters more than reliability

    Advantages:

    • Low latency and overhead
    • Suitable for real-time communication
    • Broadcast and multicast capable

    Disadvantages:

    • No error checking or retransmission
    • No congestion control
    • Packets may be lost or duplicated