CSC419 · TU past paper
Advanced Java Programming 2079 question paper
The complete TU 2079 exam paper for Advanced Java Programming (CSC419), all 11 questions with solved model answers written to the mark scheme.
Tap a question to open its answer.
- 110 marksClass and ObjectHideAnswer
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...
- 210 marksLayout ManagementHideAnswer
Why do we need layout management? Explain any two layout managers with example. Write a simple GUI program that displays 'Hello World' in a text field. The program should display output if user clicks a button.[10]
Layout management is needed to automatically arrange and position GUI components (buttons, text fields, labels, etc.) within a container (like JFrame or JPanel). Without a layout manager, we would have to manually specify the exact pixel...
- 310 marksServlet vs JSP, JSP Access Model, JSP SyntHideAnswer
Define JSP. What are the benefits of using JSP? Create a HTML file with two text fields to first name and last name. Create a JSP file that reads data from the HTML form and display full name.[10]
JSP: Definition, Benefits, and Form Handling
1. Definition of JSP
JavaServer Pages (JSP) is a server-side technology used to create dynamic, platform-independent web pages. JSP allows developers to embed Java code directly into HTML pages using special JSP tags. When a JSP page is requested by a client, the server processes the Java code, generates an HTML response, and sends it back to the browser.
JSP is built on top of Servlet technology. Internally, a JSP page is automatically translated into a Servlet by the JSP engine (container) before execution.
Syntax of JSP Scriptlet:
<% Java code here %>
2. Benefits of Using JSP
Benefit Description Separation of Concerns HTML (presentation) and Java (logic) can be written separately, making code cleaner and easier to maintain. Easy to Use Developers familiar with HTML can embed Java code without writing full Servlet classes. Platform Independent JSP runs on any platform that supports a Java-compatible web server (e.g., Apache Tomcat). Reusability JSP supports JavaBeans and custom tag libraries, promoting code reuse. Automatic Servlet Translation The JSP container automatically converts JSP into a Servlet, so the developer does not need to write boilerplate Servlet code manually. Implicit Objects JSP provides built-in implicit objects such as request,response,out,session, etc., which simplify development.Integration with Java EE JSP integrates easily with JDBC, EJB, and other Java EE technologies for building enterprise applications. Better Maintainability Since HTML and Java are written in the same file with clear separation using tags, updating the UI does not require recompiling Servlet classes.
3. HTML File with Two Text Fields (First Name and Last Name)
File Name:
index.html<!DOCTYPE html> <html> <head> <title>Full Name Form</title> </head> <body> <h2>Enter Your Name</h2> <!-- Form submits data to the JSP file using POST method --> <form action="displayName.jsp" method="post"> <label for="firstName">First Name:</label> <input type="text" id="firstName" name="firstName" placeholder="Enter first name" /> <label for="lastName">Last Name:</label> <input type="text" id="lastName" name="lastName" placeholder="Enter last name" /> <input type="submit" value="Submit" /> </form> </body> </html>Explanation:
- The form uses
method="post"to send data securely. - The
action="displayName.jsp"attribute directs the form data to the JSP file for processing. - Two text fields are created with
name="firstName"andname="lastName", which are used as parameter names in JSP.
4. JSP File that Reads Form Data and Displays Full Name
File Name:
displayName.jsp<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <title>Display Full Name</title> </head> <body> <h2>Full Name Display</h2> <% // Read the form parameters sent from index.html // request is an implicit object in JSP (similar to HttpServletRequest in Servlet) String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); // Combine first name and last name to form the full name String fullName = firstName + " " + lastName; %> <!-- Display the full name in the HTML response --> <p><strong>First Name:</strong> <%= firstName %></p> <p><strong>Last Name:</strong> <%= lastName %></p> <p><strong>Full Name:</strong> <%= fullName %></p> </body> </html>Explanation of Key Elements:
Element Purpose <%@ page ... %>Page directive that sets language and encoding for the JSP page. <% ... %>Scriptlet tag used to write Java code inside JSP. <%= ... %>Expression tag used to output a Java variable value directly into HTML. request.getParameter("firstName")Reads the value of the firstNamefield submitted from the HTML form. This is the same method used in Servlets.request.getParameter("lastName")Reads the value of the lastNamefield submitted from the HTML form.
5. Flow of Execution
User fills index.html | v Browser sends POST request to displayName.jsp | v JSP Container translates JSP to Servlet (internally) | v request.getParameter() reads firstName and lastName | v Full name is constructed and displayed in browser
Summary
- JSP is a server-side technology for building dynamic web pages by embedding Java into HTML.
- It simplifies web development compared to pure Servlets by avoiding excessive
out.println()statements. - The
request.getParameter()implicit method in JSP works exactly like in Servlets to read HTML form data. - The HTML form sends data via POST to the JSP file, which processes and displays the full name.
- The form uses
- 45 marksConcurrencyHideAnswer
What is multithreading? How can you create multithreaded program in Java? Explain. [5]
Multithreading in Java
What is Multithreading?
Multithreading is a feature of Java that allows concurrent execution of two or more parts (threads) of a program to maximize CPU utilization. A thread is a lightweight process that has its own files and stacks but can access shared data from other threads within the same process.
The main advantages of multithreading are:
- Provides simultaneous execution of two or more parts of a program
- Shares the same memory, making it more efficient than separate processes
- Maximizes CPU time utilization
Creating a Multithreaded Program in Java
There are two ways to create a thread in Java:
Method 1: Extending the
ThreadClassA class extends the built-in
Threadclass and overrides itsrun()method.class MyThread extends Thread { public void run() { for (int i = 1; i <= 5; i++) { System.out.println("Thread: " + i); } } } public class MultiThreadDemo { public static void main(String[] args) { MyThread t1 = new MyThread(); // Create thread object MyThread t2 = new MyThread(); // Create another thread object t1.start(); // Start thread 1 (calls run() internally) t2.start(); // Start thread 2 } }Key Points:
start()method is called to begin execution; it internally callsrun()- Do not call
run()directly, as it will not create a new thread
Method 2: Implementing the
RunnableInterfaceA class implements the
Runnableinterface and provides the body of therun()method. This is preferred when the class already extends another class (since Java does not support multiple inheritance).class MyRunnable implements Runnable { public void run() { for (int i = 1; i <= 5; i++) { System.out.println("Runnable Thread: " + i); } } } public class MultiThreadDemo2 { public static void main(String[] args) { MyRunnable obj = new MyRunnable(); Thread t1 = new Thread(obj); // Pass Runnable object to Thread Thread t2 = new Thread(obj); t1.start(); t2.start(); } }
Comparison of Both Methods
Feature Extending ThreadImplementing RunnableInheritance Cannot extend other class Can extend another class Flexibility Less flexible More flexible Preferred Simple programs Real-world programs
Thread Life Cycle
A thread passes through the following states:
- New - Thread object is created
- Runnable -
start()is called - Running - Thread is executing
- Blocked/Waiting - Thread is waiting for a resource
- Terminated - Thread finishes execution
Summary
Multithreading in Java enables multiple tasks to run simultaneously, improving performance and CPU utilization. It can be implemented either by extending the
Threadclass or implementing theRunnableinterface, withRunnablebeing the more flexible and commonly preferred approach. - 55 marksLayout ManagementHideAnswer
What is grid layout? Compare grid layout with grid bag layout. [5]
Grid Layout and Comparison with Grid Bag Layout
Grid Layout
Grid Layout is a layout manager in Java that arranges components in a rectangular grid of rows and columns. Every cell in the grid has the same size, and each component is placed in one cell, filling the entire cell. Components are added to the grid from left to right, top to bottom.
Key characteristics of Grid Layout:
- Divides the container into equal-sized cells
- Each cell holds exactly one component
- All rows have the same height and all columns have the same width
- Components are resized to fill their cell
Syntax:
setLayout(new GridLayout(rows, cols)); // or with gaps: setLayout(new GridLayout(rows, cols, hgap, vgap));Example:
JFrame frame = new JFrame(); frame.setLayout(new GridLayout(2, 3)); // 2 rows, 3 columns frame.add(new JButton("1")); frame.add(new JButton("2")); frame.add(new JButton("3")); frame.setSize(300, 200); frame.setVisible(true);
Comparison: Grid Layout vs Grid Bag Layout
Feature Grid Layout Grid Bag Layout Cell Size All cells are of equal size Rows and columns can have different heights and widths Component Spanning A component occupies exactly one cell A component can span multiple rows and/or columns Flexibility Simple and rigid layout Sophisticated and flexible layout manager Complexity Easy to use and implement More complex; requires GridBagConstraintsobjectComponent Size All components are resized to the same cell size Components can have different sizes and alignments Use Case Suitable for simple, uniform grids (e.g., calculator buttons) Suitable for complex, professional GUI forms Constraints No constraints needed Uses GridBagConstraintsto control placementNote (from notes): GridBagLayout is described as "a sophisticated, flexible layout manager that aligns components to span more than one cell. The rows in the grid can have different heights, and grid columns can have different widths." This is the key advantage over the simpler Grid Layout.
Summary
Grid Layout is best used when all components should be the same size in a uniform grid. Grid Bag Layout is preferred when the GUI requires components of varying sizes, spanning multiple cells, making it more powerful but also more complex to configure.
- 65 marksHandling Action Events, Key Events, Focus HideAnswer
Why do we need event handling? Explain the use of action event with example. [5]
Event handling is needed in Java to make Graphical User Interface (GUI) applications interactive and responsive. Without event handling, a GUI program would simply display components (buttons, text fields, etc.) but would not respond to ...
- 75 marksJDBC Architecture, JDBC Driver Types, JDBCHideAnswer
Explain JDBC driver types. What is scrollable result set? [5]
There are 4 types of JDBC drivers: --- - To use a Type 1 driver, an ODBC driver must be installed and configured on the client machine. - This driver does not directly interact with the database. - It converts JDBC method calls into ODBC...
- 85 marksSample Java ProgramHideAnswer
Write Java program that send messages with each other using TCP socket. [5]
TCP (Transmission Control Protocol) socket programming in Java uses the java.net package. Communication requires two programs: a Server and a Client. --- 1. Create object of ServerSocket class 2. Accept connection from client 3. Get inpu...
- 95 marksIntroduction, JavaFX vs Swing, JavaFX LayoHideAnswer
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
Feature Swing JavaFX Purpose Standard toolkit for Java developers for creating GUI Provides platform support for creating modern desktop applications GUI Components Has a more sophisticated and larger set of GUI components Has decent but comparatively fewer GUI components CSS / XML Support Does NOT support customization using CSS and XML Supports customization using CSS and XML 3D Applications Very difficult to create beautiful 3D applications Can easily create beautiful 3D applications Relationship Acts as a legacy UI component library Has 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
Type Behavior Horizontal FlowPane Arranges nodes in a row and wraps them according to the FlowPane's width Vertical FlowPane Arranges 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
FlowPaneone 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.
- 105 marksServlet vs JSP, JSP Access Model, JSP SyntHideAnswer
Compare JSP with servlet. What are different implicit objects in JSP? [5]
--- Feature Servlet JSP --------- Nature Pure Java code Tag-based approach HTML Writing HTML is written inside Java (Servlet) code Java code is written inside HTML Speed Faster than JSP Slower than Servlet Ease of Coding Writing code is ...
- 115 marksFinal and Static ModifiersHideAnswer
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 (...