BSc CSIT (TU) Science Advanced Java Programming (BSc CSIT, CSC409) Question Paper 2074 Nepal
This is the official BSc CSIT (TU) (Science stream) Advanced Java Programming (BSc CSIT, CSC409) question paper for 2074, as set in the regular annual examination. It carries 60 full marks and a time allowance of 180 minutes, across 12 questions. On Kekkei you can attempt this Advanced Java Programming (BSc CSIT, CSC409) past paper online with a timer, get instant AI feedback and step-by-step solutions, and track the topics where you lose marks — completely free. Whether you are revising for your BSc CSIT (TU) Advanced Java Programming (BSc CSIT, CSC409) exam or solving previous years' question papers, this 2074 paper is a great way to practise under real exam conditions.
Section A: Long Answer Questions
Attempt any TWO questions.
What is Swing? Explain the benefits of using Swing components over AWT. Write a GUI program using Swing components to find the sum and difference of two numbers.
What is Swing?
Swing is a part of the Java Foundation Classes (JFC) that provides a rich set of GUI components for building desktop applications. It resides in the javax.swing package. Swing components are lightweight (written entirely in Java, not relying on the native OS peer) and are built on top of AWT.
Benefits of Swing over AWT
| Feature | AWT | Swing |
|---|---|---|
| Component weight | Heavyweight (uses native OS peers) | Lightweight (pure Java) |
| Look & Feel | Platform-dependent | Pluggable Look & Feel (PLAF) |
| Component richness | Limited (Button, Label, etc.) | Rich (JTable, JTree, JTabbedPane, etc.) |
| MVC support | No | Follows MVC architecture |
| Portability | Less consistent across OS | Consistent appearance everywhere |
- Lightweight components consume fewer resources and render faster.
- Pluggable Look and Feel lets the same program appear as Metal, Windows, Motif, etc.
- MVC architecture separates data, view and controller for flexibility.
- Richer component set and built-in support for tooltips, icons, double buffering (no flickering).
Swing GUI Program: Sum and Difference of Two Numbers
import javax.swing.*;
import java.awt.event.*;
public class SumDiff extends JFrame implements ActionListener {
JTextField t1, t2;
JButton sumBtn, diffBtn;
JLabel result;
SumDiff() {
setTitle("Sum and Difference");
setLayout(null);
t1 = new JTextField(); t1.setBounds(120, 20, 120, 25);
t2 = new JTextField(); t2.setBounds(120, 60, 120, 25);
sumBtn = new JButton("Sum"); sumBtn.setBounds(40, 110, 80, 30);
diffBtn = new JButton("Difference"); diffBtn.setBounds(140, 110, 110, 30);
result = new JLabel("Result: "); result.setBounds(40, 160, 250, 25);
add(new JLabel("Number 1:")).setBounds(20, 20, 90, 25);
add(new JLabel("Number 2:")).setBounds(20, 60, 90, 25);
add(t1); add(t2); add(sumBtn); add(diffBtn); add(result);
sumBtn.addActionListener(this);
diffBtn.addActionListener(this);
setSize(300, 240);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
double a = Double.parseDouble(t1.getText());
double b = Double.parseDouble(t2.getText());
if (e.getSource() == sumBtn)
result.setText("Result: " + (a + b));
else
result.setText("Result: " + (a - b));
}
public static void main(String[] args) {
new SumDiff();
}
}
The program reads two numbers from the text fields and displays their sum or difference in a label when the corresponding button is clicked.
Explain the life cycle of a servlet in detail. Create a simple servlet that reads and displays the data (username and password) submitted from an HTML form.
Servlet Life Cycle
A servlet's life cycle is managed by the servlet container (web server) and consists of the following phases, controlled by three main methods of the javax.servlet.Servlet interface:
- Loading and Instantiation — When the first request arrives (or at startup if
load-on-startupis set), the container loads the servlet class and creates a single instance using the no-arg constructor. - Initialization —
init(ServletConfig config)— Called once immediately after instantiation. Used to perform one-time setup such as opening database connections or reading configuration parameters. - Request Handling —
service(ServletRequest req, ServletResponse res)— Called for every client request. The container creates new request/response objects and (typically) a new thread. For HTTP servlets,service()dispatches todoGet(),doPost(), etc. based on the HTTP method. - Destruction —
destroy()— Called once before the servlet is removed from service (e.g. server shutdown). Used to release resources.
After destroy(), the instance is eligible for garbage collection.
Load class -> instantiate -> init() -> service() ... service() -> destroy()
Servlet Reading HTML Form Data
HTML form (login.html):
<form action="LoginServlet" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
Servlet (LoginServlet.java):
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String user = req.getParameter("username");
String pass = req.getParameter("password");
out.println("<html><body>");
out.println("<h3>Submitted Data</h3>");
out.println("Username: " + user + "<br>");
out.println("Password: " + pass);
out.println("</body></html>");
out.close();
}
}
The servlet uses request.getParameter() to read the form fields and writes them back to the response.
What is JDBC? Discuss the different types of JDBC drivers. Write a program to connect to a database and insert a record using JDBC.
What is JDBC?
JDBC (Java Database Connectivity) is a standard Java API (in the java.sql and javax.sql packages) that allows Java programs to connect to and interact with relational databases in a database-independent way. It defines interfaces such as Driver, Connection, Statement, PreparedStatement and ResultSet.
Types of JDBC Drivers
- Type 1 — JDBC-ODBC Bridge Driver: Translates JDBC calls into ODBC calls. Requires ODBC on the client; platform-dependent and now deprecated.
- Type 2 — Native-API Driver: Converts JDBC calls into native database library (C/C++) calls. Faster than Type 1 but requires native client libraries on each machine.
- Type 3 — Network Protocol Driver (Middleware): Sends JDBC calls to a middleware server using a database-independent net protocol; the middleware then talks to the database. Fully written in Java, flexible.
- Type 4 — Thin Driver (Pure Java): Converts JDBC calls directly into the database's native network protocol. 100% Java, platform-independent, and the most commonly used (e.g. MySQL Connector/J).
Steps to Use JDBC
- Load/register the driver
- Establish a
Connection - Create a
Statement/PreparedStatement - Execute the query
- Process the result and close resources
Program: Insert a Record
import java.sql.*;
public class InsertRecord {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/college";
String user = "root", pass = "password";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, pass);
String sql = "INSERT INTO student(id, name) VALUES(?, ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 101);
ps.setString(2, "Ram");
int rows = ps.executeUpdate();
System.out.println(rows + " record inserted.");
ps.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The program loads the driver, opens a connection, uses a PreparedStatement to insert a record, and closes the resources.
Section B: Short Answer Questions
Attempt any EIGHT questions.
Discuss any three event classes in Java with examples.
Event classes in Java (in java.awt.event) encapsulate information about a particular user action. Three common ones:
ActionEvent— Generated when a button is clicked, a menu item is selected, or Enter is pressed in a text field.button.addActionListener(e -> System.out.println("Clicked"));MouseEvent— Generated by mouse actions such as press, release, click, enter, exit, drag and move. Provides coordinates viagetX(),getY().comp.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { System.out.println("At " + e.getX() + "," + e.getY()); } });KeyEvent— Generated when a key is pressed, released or typed. Provides the key viagetKeyCode()/getKeyChar().field.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { System.out.println("Key: " + e.getKeyChar()); } });
Others include ItemEvent, WindowEvent, FocusEvent and TextEvent.
What is a layout manager? Explain BorderLayout and FlowLayout.
Layout Manager
A layout manager is an object that automatically arranges (sizes and positions) the components inside a container. It frees the programmer from setting absolute coordinates and ensures the GUI adapts when the container is resized. It is set with setLayout(). Common managers: FlowLayout, BorderLayout, GridLayout, GridBagLayout, CardLayout, BoxLayout.
BorderLayout
- Default layout for
JFrame/Window. Divides the container into five regions:NORTH,SOUTH,EAST,WEST, andCENTER. - Each region holds one component; the
CENTERexpands to take remaining space.
setLayout(new BorderLayout());
add(new JButton("Top"), BorderLayout.NORTH);
add(new JButton("Middle"), BorderLayout.CENTER);
FlowLayout
- Default layout for
JPanel/Applet. Arranges components in a left-to-right row, wrapping to the next line when the current row is full. - Respects each component's preferred size; supports alignment (LEFT, CENTER, RIGHT).
setLayout(new FlowLayout(FlowLayout.LEFT));
add(new JButton("A"));
add(new JButton("B"));
What is a socket? Differentiate between TCP socket and UDP socket.
What is a Socket?
A socket is one endpoint of a two-way communication link between two programs running on a network. It is identified by an IP address + port number and lets applications send and receive data. In Java, sockets are provided by the java.net package (Socket, ServerSocket, DatagramSocket).
TCP Socket vs UDP Socket
| Aspect | TCP Socket | UDP Socket |
|---|---|---|
| Connection | Connection-oriented (handshake before data) | Connectionless (no handshake) |
| Reliability | Reliable; guarantees delivery & order | Unreliable; packets may be lost/reordered |
| Java classes | Socket, ServerSocket | DatagramSocket, DatagramPacket |
| Data unit | Continuous byte stream | Independent datagrams |
| Speed/Overhead | Slower, higher overhead | Faster, low overhead |
| Use cases | HTTP, FTP, email | Video streaming, DNS, online games |
TCP is used where accuracy matters; UDP where speed matters and occasional loss is acceptable.
Explain the delegation event model in Java.
Delegation Event Model
The delegation event model (introduced in JDK 1.1) is the modern approach to event handling in Java. In this model, an event generated by a source is sent (delegated) to one or more registered listener objects that handle it. It is based on three elements:
- Event Source — The component (e.g. a
JButton) that generates an event when the user interacts with it. - Event Object — An object (e.g.
ActionEvent) that encapsulates information about the event and is passed to the listener. - Event Listener — An object that implements a listener interface (e.g.
ActionListener) and contains the handling code (e.g.actionPerformed).
Working: A listener registers with a source using an addXxxListener() method. When the event occurs, the source creates an event object and calls the appropriate method on every registered listener.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button pressed");
}
});
Advantages: clean separation of GUI and logic; events are sent only to interested listeners (efficient, unlike the old inheritance-based model where events were propagated through the component hierarchy).
What is RMI? Explain the RMI architecture layers.
What is RMI?
RMI (Remote Method Invocation) is a Java API that allows an object running in one JVM to invoke methods of an object running in another JVM (possibly on a different machine), as if it were a local call. It enables distributed application development in Java and is found in the java.rmi package. RMI uses stubs and skeletons plus object serialization to pass parameters and return values.
RMI Architecture Layers
- Stub and Skeleton Layer:
- The stub is a client-side proxy for the remote object; it forwards (marshals) the method call to the server.
- The skeleton is the server-side entity that receives (unmarshals) the call and invokes the actual remote object. (Skeletons are not required from Java 1.2 onward.)
- Remote Reference Layer (RRL): Handles the semantics of the remote reference — interpreting and managing references between client and server (e.g. unicast point-to-point connections), independent of the stub/skeleton.
- Transport Layer: The lowest layer; responsible for setting up connections, managing them, and transferring the actual bytes over the network (typically using TCP/IP). It also tracks active remote objects.
A separate RMI Registry (rmiregistry) acts as a naming service where the server binds remote objects and the client looks them up.
Write short notes on JavaBeans.
JavaBeans
A JavaBean is a reusable software component written in Java that follows specific conventions, allowing it to be manipulated visually in a builder tool (IDE). Beans are the foundation of component-based development in Java.
Rules / Conventions for a JavaBean class:
- It must be public and have a public no-argument constructor.
- Its properties are exposed through getter and setter methods (
getX()/setX(), andisX()for boolean). - It should be serializable (implement
java.io.Serializable) so its state can be saved/restored.
Features of JavaBeans:
- Properties — named attributes accessed via getters/setters.
- Events — beans can fire events to notify other components.
- Persistence — a bean's state can be stored and restored through serialization.
- Introspection — tools can analyze a bean's properties, methods and events at design time.
Example:
public class Student implements java.io.Serializable {
private String name;
public Student() {}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
How do you handle exceptions in JDBC? Explain with an example.
Exception Handling in JDBC
Most JDBC methods throw a checked exception java.sql.SQLException (a subclass of Exception), so JDBC code must be enclosed in a try-catch-finally block (or use try-with-resources). SQLException provides useful diagnostic methods:
getMessage()— human-readable descriptiongetErrorCode()— vendor-specific error codegetSQLState()— standard SQLSTATE code
Resources (Connection, Statement, ResultSet) should always be closed in a finally block (or via try-with-resources) to avoid leaks.
Example:
import java.sql.*;
public class JdbcException {
public static void main(String[] args) {
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "pass");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM student");
while (rs.next())
System.out.println(rs.getString("name"));
} catch (SQLException e) {
System.out.println("SQL Error: " + e.getMessage());
System.out.println("Code: " + e.getErrorCode());
System.out.println("State: " + e.getSQLState());
} catch (ClassNotFoundException e) {
System.out.println("Driver not found: " + e.getMessage());
} finally {
try { if (con != null) con.close(); }
catch (SQLException e) { e.printStackTrace(); }
}
}
}
What is a session in servlets? How is session tracking done?
Session in Servlets
HTTP is a stateless protocol — it does not remember a client across multiple requests. A session is a mechanism that lets the server maintain state (a conversation) with a single user across several requests for a period of time. In servlets it is represented by the HttpSession object, obtained with request.getSession().
HttpSession session = request.getSession();
session.setAttribute("user", username);
String u = (String) session.getAttribute("user");
Session Tracking Techniques
- Cookies — A small piece of data (e.g. the session ID,
JSESSIONID) stored on the client and sent back with each request. Simple but can be disabled by the user. - URL Rewriting — The session ID is appended to every URL (e.g.
page?jsessionid=ABC). Works even when cookies are disabled. - Hidden Form Fields — The session data is stored in
<input type="hidden">fields submitted with each form. - HttpSession API — The servlet container automatically manages a session object (using a cookie or URL rewriting underneath); the preferred, high-level technique.
Sessions can be invalidated with session.invalidate() or expire after a timeout.
Differentiate between Statement and PreparedStatement.
Statement vs PreparedStatement
| Aspect | Statement | PreparedStatement |
|---|---|---|
| Query type | For static SQL with no parameters | For parameterized (precompiled) SQL |
| Compilation | Compiled each time it is executed | Compiled (prepared) once, reused many times |
| Performance | Slower for repeated execution | Faster for repeated execution |
| Parameters | Built by string concatenation | Uses ? placeholders set via setXxx() |
| SQL Injection | Vulnerable | Prevents SQL injection (parameters are escaped) |
| Readability | Less readable for dynamic values | Cleaner and safer |
Statement example:
Statement st = con.createStatement();
st.executeUpdate("INSERT INTO student VALUES(1, 'Ram')");
PreparedStatement example:
PreparedStatement ps = con.prepareStatement(
"INSERT INTO student VALUES(?, ?)");
ps.setInt(1, 1);
ps.setString(2, "Ram");
ps.executeUpdate();
PreparedStatement (a sub-interface of Statement) is preferred when the same query runs repeatedly with different values, for better performance and security.
Frequently asked questions
- Where can I find the BSc CSIT (TU) Advanced Java Programming (BSc CSIT, CSC409) question paper 2074?
- The full BSc CSIT (TU) Advanced Java Programming (BSc CSIT, CSC409) 2074 (regular) question paper is available free on Kekkei. You can read every question online and attempt the paper under timed exam conditions.
- Does the Advanced Java Programming (BSc CSIT, CSC409) 2074 paper come with solutions?
- Yes. Every question on this Advanced Java Programming (BSc CSIT, CSC409) past paper includes a step-by-step solution, plus instant AI feedback when you attempt it on Kekkei.
- How many marks is the BSc CSIT (TU) Advanced Java Programming (BSc CSIT, CSC409) 2074 paper?
- The BSc CSIT (TU) Advanced Java Programming (BSc CSIT, CSC409) 2074 paper carries 60 full marks and is meant to be completed in 180 minutes, across 12 questions.
- Is practising this Advanced Java Programming (BSc CSIT, CSC409) past paper free?
- Yes — reading and attempting this Advanced Java Programming (BSc CSIT, CSC409) past paper on Kekkei is completely free.