CSC419 · TU past paper
Advanced Java Programming 2075 question paper
The complete TU 2075 exam paper for Advanced Java Programming (CSC419), all 13 questions with solved model answers written to the mark scheme.
Tap a question to open its answer.
- 110 marksGUI ControlsHideAnswer
Design a GUI form using swing with a text field, a text label for displaying the input message 'Input any String', and three buttons with caption CheckPalindrome, Reverse, FindVowels. Write a complete program for above scenario and for checking palindrome in first button, reverse it after clicking second button and extract the vowels from it after clicking third button.[10]
--- Input String Button Clicked Output Displayed --------- madam CheckPalindrome "madam" is a Palindrome hello CheckPalindrome "hello" is NOT a Palindrome hello Reverse Reversed String: olleh hello FindVowels Vowels in "hello": e o (Coun...
- 210 marksCreating Exception ClassHideAnswer
Why do we need to handle the exception? Distinguish error and exception. Write a program to demonstrate your own exception class.[10]
Exception handling is needed for the following reasons: 1. To maintain normal program flow: Without handling, an exception causes the program to terminate abruptly. Handling allows the rest of the code to continue executing. 2. To avoid ...
- 310 marksWeb Container, Introduction to Servlets, LHideAnswer
Describe the process to deploy the servlet. Write a program to a JSP web form to take input of a student and submit it to second JSP file which may simply print the values of form submission.[10]
--- There are six steps to write and deploy a Servlet program (using Apache Tomcat server): --- Create the required folder structure inside the Tomcat webapps directory: - WEB-INF/classes/ contains compiled .class files - WEB-INF/web.xml...
- 45 marksNumericalArraysHideAnswer
An array is called balanced if it's even numbered elements (a[0], a[2], etc) are even and its odd numbered elements (a[1], a[3], etc) are Odd. Write a function named isBalanced that accepts an array of integers and returns 1 if the array is balanced otherwise it returns 0. [5]
This is a programming problem, not a numerical one. The requirements are: - Even-indexed elements (a[0], a[2], a[4], ...) must be even. - Odd-indexed elements (a[1], a[3], a[5], ...) must be odd. - Function name: isBalanced - Input: an a...
- 55 marksWeb Container, Introduction to Servlets, LHideAnswer
Explain the significance of cookies and sessions with suitable example. [5]
A cookie is a small piece of data (key-value pair) stored on the client's browser by the web server. It is used to remember information about the user across multiple HTTP requests, since HTTP is a stateless protocol. - Remembers user pr...
- 65 marksClass and ObjectHideAnswer
Define the chain of constructor. What is the purpose of private constructor? [5]
--- Constructor chaining is the process of calling one constructor from another constructor within the same class or from a parent class. This creates a "chain" of constructor calls that executes in sequence. Constructor chaining is achi...
- 75 marksIntroduction of RMI, Architecture of RMI, HideAnswer
Describe the process to run the RMI application. [5]
Remote Method Invocation (RMI) is a Java API that allows an object running in one Java Virtual Machine (JVM) to invoke methods on an object running in another JVM, possibly on a different machine. It enables distributed computing in Java...
- 85 marksDDL and DML Operations using Java, PrepareHideAnswer
How prepared statements are different with statement? List the types of JDBC driver. [5]
Prepared Statements vs Statement & JDBC Driver Types
Part 1: Difference Between PreparedStatement and Statement
Feature Statement PreparedStatement Definition Used to execute simple, static SQL queries Used to execute precompiled, parameterized SQL queries SQL Compilation SQL is compiled every time it is executed SQL is compiled only once and reused Parameters Does not support parameters; query is hardcoded Supports ?placeholders for dynamic parametersPerformance Slower for repeated execution Faster for repeated execution due to precompilation SQL Injection More vulnerable to SQL injection attacks More secure; prevents SQL injection Usage Suitable for queries executed once Suitable for queries executed multiple times with different values Example of Statement:
Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE id = 1");Example of PreparedStatement:
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM users WHERE id = ?"); pstmt.setInt(1, 1); ResultSet rs = pstmt.executeQuery();
Part 2: Types of JDBC Drivers
There are 4 types of JDBC drivers:
Type 1: JDBC-ODBC Bridge Driver
- Converts JDBC method calls into ODBC method calls.
- Requires an ODBC driver to be installed and configured on the client machine.
- Does not directly interact with the database.
- Can connect to any type of database.
- Least efficient due to multiple layers of conversion.
Type 2: Native-API Driver
- Written partially in Java and partially in native code.
- Converts JDBC method calls into native calls of the database API.
- The Native-API of the specific database must be installed on the client system before use.
- Faster than Type 1 but still requires native installation.
Type 3: Net Pure Java Driver (Network Protocol Driver)
- Fully written in Java.
- The JDBC driver on the client machine uses a socket to communicate with middleware at the server.
- Client database access requests are sent through the network to the middleware, which then communicates with the database.
- No client-side database installation required.
Type 4: Pure Java Driver (Thin Driver)
- Fully written in Java, hence it is a portable driver.
- Interacts directly with the database without any middleware or native library.
- No client-side or server-side installation required.
- Most commonly used driver in modern applications.
Summary: Type 4 (Pure Java Driver) is the most preferred driver due to its portability, direct database interaction, and no dependency on native libraries.
- 95 marksConcurrencyHideAnswer
Write down the life cycle of thread. Write a program to execute multiple threads in priority base. [5]
State Description -------------------- New Thread object is created but start() is not yet called Runnable Thread is ready to run; waiting for CPU scheduling Running Thread is currently executing its run() method Blocked/Waiting Thread i...
- 105 marksFinal and Static ModifiersHideAnswer
When do we use final method and final class? Differentiate between function overloading and function overriding. [5]
--- A final method is a method declared with the final keyword. It cannot be overridden by any subclass. When to use: - When you want to prevent a subclass from changing the implementation of a method. - When the method contains critical...
- 115 marksHideAnswer
Give any two differences between class and bean. Write the steps to create JAR files. [5]
Aspect Class Bean --------- Definition A class is a general-purpose blueprint/template that defines properties and behaviors (methods) of objects. It does not follow any specific naming convention or design pattern. A Bean is a special t...
- 125 marksHideAnswer
What is a socket? Write client and server programs in which a server program accepts a radius of a circle from the client program. Computes area, sends the computed area to the client program, and displays it by client program. [5]
Socket Programming: Circle Area Computation
What is a Socket?
A socket is an endpoint for communication between two machines over a network. It provides a mechanism for two programs (client and server) to communicate with each other using standard input/output streams. In Java, the
Socketclass (client side) andServerSocketclass (server side) from thejava.netpackage are used to establish TCP-based socket communication.
Steps for Writing Server Program:
- Create an object of
ServerSocketclass - Accept the connection from the client
- Get input and output streams from the client
- Read/Write data to the socket
- Close streams and socket
Steps for Writing Client Program:
- Open a socket
- Open input and output streams to the socket
- Read from and write to the socket streams
- Close the socket
Server Program
import java.net.*; import java.io.*; public class CircleServer { public static void main(String args[]) throws IOException { // Step 1: Create ServerSocket on port 1254 ServerSocket ss = new ServerSocket(1254); System.out.println("Server is waiting for client..."); // Step 2: Accept connection from client Socket cs = ss.accept(); System.out.println("Client connected."); // Step 3: Get input and output streams Scanner ins = new Scanner(cs.getInputStream()); PrintWriter outs = new PrintWriter(cs.getOutputStream(), true); // Step 4: Read radius sent by client double radius = ins.nextDouble(); System.out.println("Radius received from client: " + radius); // Step 5: Compute area of circle double area = Math.PI * radius * radius; System.out.println("Computed Area: " + area); // Step 6: Send computed area back to client outs.println(area); // Step 7: Close streams and socket ins.close(); outs.close(); cs.close(); ss.close(); } }
Client Program
import java.net.*; import java.io.*; import java.util.*; public class CircleClient { public static void main(String args[]) throws IOException { // Step 1: Open a socket and connect to server at localhost, port 1254 Socket cs = new Socket("localhost", 1254); // Step 2: Open input and output streams Scanner ins = new Scanner(cs.getInputStream()); PrintWriter outs = new PrintWriter(cs.getOutputStream(), true); // Step 3: Read radius from user Scanner userInput = new Scanner(System.in); System.out.print("Enter radius of circle: "); double radius = userInput.nextDouble(); // Step 4: Send radius to server outs.println(radius); // Step 5: Receive computed area from server double area = ins.nextDouble(); // Step 6: Display the area System.out.println("Area of circle received from Server: " + area); // Step 7: Close streams and socket ins.close(); outs.close(); cs.close(); } }
Sample Output
-- Server Side -- Server is waiting for client... Client connected. Radius received from client: 7.0 Computed Area: 153.93804002589985 -- Client Side -- Enter radius of circle: 7 Area of circle received from Server: 153.93804002589985
Summary of Communication Flow
Client Server | | |--- sends radius (7.0) ------> | | | computes area = π * r² |<-- receives area (153.93) --- | | | displays area displays areaNote: Both programs use
port 1254for communication. The server must be started before the client. The formula used is Area = π × r² computed usingMath.PIin Java. - Create an object of
- 135 marksLayout ManagementHideAnswer
Write short notes on: a. Grid Layout b. Ragged Array [2.5+2.5]
Short Notes
a. Grid Layout
GridPane (Grid Layout in JavaFX) is a layout manager that arranges nodes in a flexible grid of rows and columns. It allows multiple nodes to be placed in multiple rows and columns within a single container.
Key Features:
- Nodes can be placed in any cell of the grid by specifying the column index and row index.
- The grid is flexible -- rows can have different heights and columns can have different widths.
- A more advanced form, GridBagLayout, is a sophisticated and flexible layout manager that allows components to span more than one cell.
- It is useful for creating form-like interfaces where labels and input fields are aligned in rows and columns.
Example Usage (JavaFX GridPane):
GridPane grid = new GridPane(); grid.add(new Label("Name:"), 0, 0); // column 0, row 0 grid.add(new TextField(), 1, 0); // column 1, row 0 grid.add(new Label("Email:"), 0, 1); // column 0, row 1 grid.add(new TextField(), 1, 1); // column 1, row 1This creates a structured, tabular arrangement of UI components.
b. Ragged Array
A ragged array (also called a jagged array) is a multidimensional array in Java where each row can have a different number of columns. Unlike a regular 2D array where all rows have the same length, a ragged array allows rows of varying sizes.
Key Features:
- In Java, a 2D array is essentially an array of arrays, so each row can be independently sized.
- This saves memory when rows do not need equal lengths.
- Each row is a separate one-dimensional array object.
Declaration and Initialization:
int[][] ragged = new int[3][]; // 3 rows, columns not yet defined ragged[0] = new int[2]; // row 0 has 2 columns ragged[1] = new int[4]; // row 1 has 4 columns ragged[2] = new int[3]; // row 2 has 3 columnsVisual Representation:
Row 0: [ ][ ] Row 1: [ ][ ][ ][ ] Row 2: [ ][ ][ ]Example with values:
int[][] ragged = { {1, 2}, {3, 4, 5, 6}, {7, 8, 9} };Ragged arrays are particularly useful in applications like triangular matrices or storing data of unequal lengths, where allocating equal-sized rows would waste memory.