Chapter 3
Advanced Java Programming
TU BCA past exam questions
Past questions and answers
58 questions set from this chapter, 2 of them more than once. Most repeated first.
- Asked 2 times
- 2023 · 5 marks
- 2026 · 1+4 marks
What is KeyEvent? Explain with a proper example.
Answer
KeyEvent
A KeyEvent (package java.awt.event) is generated when the user presses, releases or types a key while a component has the keyboard focus. It is handled by a class implementing KeyListener, registered with addKeyListener().
Methods of KeyListener:
keyPressed(KeyEvent e): a key is pressed (works for all keys, including Shift, arrows and function keys)keyReleased(KeyEvent e): a key is releasedkeyTyped(KeyEvent e): a Unicode character is typed (not for action keys)
Useful KeyEvent methods: getKeyChar() returns the character, getKeyCode() returns the virtual key code (such as VK_ENTER), and isShiftDown() checks a modifier.
Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyDemo extends JFrame implements KeyListener {
JTextField tf = new JTextField(15);
JLabel lbl = new JLabel("Press a key");
KeyDemo() {
setLayout(new FlowLayout());
add(tf);
add(lbl);
tf.addKeyListener(this);
setSize(300, 120);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void keyPressed(KeyEvent e) { lbl.setText("Pressed code: " + e.getKeyCode()); }
public void keyReleased(KeyEvent e) { lbl.setText("Released: " + KeyEvent.getKeyText(e.getKeyCode())); }
public void keyTyped(KeyEvent e) { System.out.println("Typed: " + e.getKeyChar()); }
public static void main(String[] args) { new KeyDemo(); }
}
Typing in the text field fires the three methods in order: keyPressed, keyTyped, keyReleased, and the label shows the key information.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- Asked 2 times
- 2023 · 5 marks
- 2026 · 5 marks
Explain RMI architecture in Java in detail.
Answer
RMI architecture
RMI lets a client JVM invoke methods on an object in a server JVM. The architecture has three layers between the client and server applications, plus the registry.
Client app -> Stub ----------------\ /---- Skeleton -> Remote object
Remote Reference Layer <== Transport ==> Remote Reference Layer
-
Stub and Skeleton layer (proxy layer)
- The stub is a client-side proxy that implements the same remote interface. When the client calls a method, the stub marshals (serializes) the method identifier and arguments and passes them down.
- The skeleton is the server-side counterpart. It unmarshals the arguments, invokes the actual method on the remote object, then marshals the result or exception and returns it. (From Java 2 onward, skeletons are not required; the dispatch is done by the runtime.)
-
Remote Reference Layer (RRL)
- Handles the semantics of the invocation: it interprets the reference to the remote object, supports unicast point-to-point calls, and manages the connection to the server object. It also takes part in distributed garbage collection.
-
Transport Layer
- Sets up and manages the network connection (TCP/IP using the JRMP protocol), tracks remote objects and routes the stream of bytes between the two JVMs.
-
RMI Registry (naming service)
- The server binds its remote object under a name (
Naming.rebindorRegistry.rebind). The client looks up the name (Naming.lookup,registry.lookup) and receives the stub. It listens on port 1099 by default.
- The server binds its remote object under a name (
Working steps
- The server creates the remote object and registers it in the registry.
- The client contacts the registry and obtains the stub.
- The client calls a method on the stub.
- The stub marshals the request and sends it through the RRL and transport layer.
- The server side unmarshals, runs the method and returns the marshalled result.
- The client stub unmarshals the result and gives it to the client.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
Explain different scripting elements of JSP with examples.
Similar questions: Explain different scripting elements used in JSP. (2026)
Answer
JSP (JavaServer Pages) scripting elements let Java code be embedded in an HTML page. There are three kinds, plus comments.
1. Scriptlet <% code %> : Java statements placed in the _jspService() method.
<% int a = 5, b = 3; out.println(a + b); %>
2. Declaration <%! declaration %> : declares variables and methods at class level, outside _jspService().
<%! int count = 0;
int square(int n) { return n * n; } %>
3. Expression <%= expression %> : the value of the expression is converted to a string and written to the output.
Square of 4 is <%= square(4) %>
4. Comments <%-- comment --%> : a JSP comment that is not sent to the client.
Related, but not scripting: directives <%@ page ... %> and actions <jsp:include ... />. Implicit objects such as request, response, out, session are available inside scriptlets and expressions.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2026 · 5 marks
Explain different scripting elements used in JSP.
Similar questions: Explain different scripting elements of JSP with (2021)
Answer
Scripting elements let Java code be embedded in a JSP page. There are three types, plus comments.
1. Declaration <%! ... %> declares variables and methods at class level. They go into the generated servlet class, outside _jspService().
<%! int count = 0;
int square(int n) { return n * n; } %>
2. Scriptlet <% ... %> holds Java statements that are placed inside _jspService() and run on every request.
<% String name = request.getParameter("name");
out.println("Hello " + name); %>
3. Expression <%= ... %> evaluates a Java expression and prints the result to the output. No semicolon is used.
Today is <%= new java.util.Date() %>
4. Comment <%-- ... --%> is a JSP comment, ignored by the container and not sent to the client.
Directives (<%@ page ... %>, <%@ include ... %>) and actions (<jsp:include>, <jsp:useBean>) are separate JSP elements, not scripting elements.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
Why do we need a top-level container like JFrame to write Java programs with GUI? How can we display two-dimensional objects in Java?
Answer
Need for a top-level container
Swing components such as buttons and text fields cannot exist alone; they must be placed inside a container hierarchy whose root is a heavyweight top-level container: JFrame, JDialog or JApplet. The reasons:
- It has a native window supplied by the operating system, with title bar, borders and close/minimise buttons, and the lightweight components are drawn inside it.
- It provides a content pane to which components are added (
frame.add(...)orgetContentPane().add(...)). - It connects the GUI to the event dispatching system and window events (e.g.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)).
Displaying two-dimensional objects
Extend a component such as JPanel, override paintComponent(Graphics g), cast g to Graphics2D and draw shapes from java.awt.geom (Line2D, Rectangle2D, Ellipse2D, Arc2D) or Graphics methods (drawLine, drawRect, drawOval, fillRect), then add the panel to the frame.
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class Shapes extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLUE);
g2.draw(new Rectangle2D.Double(20, 20, 100, 60));
g2.setColor(Color.RED);
g2.fill(new Ellipse2D.Double(150, 20, 80, 60));
}
public static void main(String[] a) {
JFrame f = new JFrame("2D Shapes");
f.add(new Shapes());
f.setSize(300, 150);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
Explain JTextField and JTextArea components of the Java Swing library.
Answer
JTextField
A lightweight component that allows editing of a single line of text. Common constructors: JTextField(), JTextField(int columns), JTextField(String text, int columns).
Useful methods: getText(), setText(String), setEditable(boolean), setColumns(int), selectAll(), addActionListener(...) (fires when Enter is pressed).
JTextField name = new JTextField(15);
name.setText("Ram");
String s = name.getText();
JTextArea
A component for displaying and editing multiple lines of plain text. Constructors: JTextArea(), JTextArea(int rows, int cols), JTextArea(String text, int rows, int cols).
Useful methods: append(String), insert(String, int), setText, getText, setLineWrap(boolean), setWrapStyleWord(boolean), setEditable(boolean). It does not scroll itself, so it is normally placed in a JScrollPane.
JTextArea area = new JTextArea(5, 20);
area.setLineWrap(true);
area.append("Hello\nWorld");
JScrollPane sp = new JScrollPane(area);
Difference: JTextField is for one line and generates ActionEvent; JTextArea is for many lines and Enter simply adds a new line. Both belong to JTextComponent and share methods such as getText, setText, copy, paste, getSelectedText.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
How do you execute SQL statements using JDBC? Explain with an example.
Answer
Steps to execute SQL statements using JDBC
- Load the driver (optional in JDBC 4+):
Class.forName("com.mysql.cj.jdbc.Driver"); - Create a connection:
DriverManager.getConnection(url, user, password). - Create a statement:
Statement,PreparedStatementorCallableStatement. - Execute the SQL:
executeQuery()for SELECT (returns aResultSet);executeUpdate()for INSERT, UPDATE, DELETE and DDL (returns the number of rows affected);execute()for either. - Process the results with the
ResultSet(next(),getXxx()). - Close the resultset, statement and connection (try-with-resources).
Example
import java.sql.*;
public class JdbcDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/college";
try (Connection con = DriverManager.getConnection(url, "root", "password");
Statement st = con.createStatement()) {
int n = st.executeUpdate(
"INSERT INTO student(id, name) VALUES (1, 'Sita')");
System.out.println(n + " row inserted");
ResultSet rs = st.executeQuery("SELECT id, name FROM student");
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
Compare result set with row set. Explain a prepared statement with an example.
Answer
ResultSet versus RowSet
| ResultSet | RowSet |
|---|---|
Part of java.sql; obtained from a Statement execution | Part of javax.sql; extends ResultSet |
| Needs an open connection while in use (connected) | Can be disconnected (CachedRowSet) and work offline |
| By default forward-only and not updatable | Scrollable and updatable by default |
| Not serializable | Can be serialized and sent over a network |
| Not a JavaBean | A JavaBean; supports properties and event listeners |
| Created by the driver | Can be configured with url, username, command, and execute itself |
Prepared statement
A PreparedStatement is a precompiled SQL statement with ? placeholders for parameters. It is parsed and compiled once and can be run many times with different values. Advantages: faster for repeated execution, prevents SQL injection, and handles data types and quoting automatically.
String sql = "INSERT INTO student(id, name) VALUES (?, ?)";
try (Connection con = DriverManager.getConnection(url, user, pwd);
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, 2);
ps.setString(2, "Hari");
int rows = ps.executeUpdate();
System.out.println(rows + " row inserted");
} catch (SQLException e) {
e.printStackTrace();
}
The parameter index starts from 1, and setInt, setString, etc. bind the values before executeUpdate() or executeQuery().
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
How do you set and get Cookie in Servlet? Explain using a suitable Java program.
Answer
A cookie is a small piece of text (name-value pair) that the server sends to the browser, which returns it in later requests; it is used to maintain state (user preferences, session tracking) over stateless HTTP. In servlets the class javax.servlet.http.Cookie (jakarta.servlet.http.Cookie in newer versions) is used.
Setting a cookie: create a Cookie object, optionally set its maximum age, and add it to the response with response.addCookie(cookie).
Getting cookies: request.getCookies() returns an array of cookies (or null); loop over it and use getName() and getValue().
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// set a cookie
Cookie c = new Cookie("user", "Ram");
c.setMaxAge(60 * 60); // one hour
response.addCookie(c);
// get cookies sent by the browser
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie ck : cookies) {
out.println(ck.getName() + " = " + ck.getValue() + "<br>");
}
}
}
}
On the first request no cookie is received; later requests show user = Ram as long as it has not expired.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 5 marks
Write short notes on (Any Two):
a) Java web frameworks
b) CORBA
c) Bean bound property
Answer
(a) Java web frameworks
A web framework supplies a ready-made structure and libraries for building web applications, usually following the MVC pattern (Model, View, Controller), so that developers concentrate on business logic rather than request handling, routing, and so on.
Examples: Spring MVC / Spring Boot (dependency injection, REST, security), JSF (component-based UI), Struts (action-based MVC), Hibernate (ORM, persistence), Play, Vaadin.
Benefits: less boilerplate, clean separation of presentation and logic, built-in security, validation, templating and database integration, faster development and easier maintenance.
(b) CORBA
The Common Object Request Broker Architecture, from the OMG, is a standard that lets objects written in different languages on different machines communicate.
- Interfaces are written in IDL (Interface Definition Language) and compiled into language-specific stubs (client side) and skeletons (server side).
- The ORB (Object Request Broker) locates objects and delivers requests and replies.
- IIOP is the standard protocol between ORBs.
- A naming service helps clients find objects.
It is language- and platform-independent, unlike Java RMI which is Java-only. Java provided CORBA support via org.omg.CORBA (removed from Java 11).
(c) Bean bound property
A bound property of a JavaBean notifies other objects when its value changes. The bean keeps a PropertyChangeSupport and provides addPropertyChangeListener and removePropertyChangeListener. In the setter it calls firePropertyChange(name, oldValue, newValue). Interested listeners implement PropertyChangeListener.propertyChange(PropertyChangeEvent e).
public class Person {
private String name;
private PropertyChangeSupport pcs = new PropertyChangeSupport(this);
public void addPropertyChangeListener(PropertyChangeListener l) { pcs.addPropertyChangeListener(l); }
public void removePropertyChangeListener(PropertyChangeListener l) { pcs.removePropertyChangeListener(l); }
public void setName(String n) {
String old = name; name = n;
pcs.firePropertyChange("name", old, n);
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 10 marks
Write a GUI application to find the sum and difference of two integer numbers. Use two text fields for input and a third text field for output. Your program should display the sum if the user presses the mouse and the difference if the user releases the mouse.
Answer
The program uses MouseListener: mousePressed shows the sum, mouseReleased shows the difference. The mouse listener is attached to the frame's content panel.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SumDiff extends JFrame implements MouseListener {
private JTextField t1 = new JTextField(8);
private JTextField t2 = new JTextField(8);
private JTextField result = new JTextField(8);
public SumDiff() {
super("Sum and Difference");
setLayout(new FlowLayout());
add(new JLabel("First:")); add(t1);
add(new JLabel("Second:")); add(t2);
add(new JLabel("Result:")); add(result);
result.setEditable(false);
// listener on the frame, text fields and content pane
addMouseListener(this);
getContentPane().addMouseListener(this);
t1.addMouseListener(this);
t2.addMouseListener(this);
result.addMouseListener(this);
setSize(260, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private int[] read() {
try {
return new int[]{Integer.parseInt(t1.getText().trim()),
Integer.parseInt(t2.getText().trim())};
} catch (NumberFormatException e) {
result.setText("Invalid");
return null;
}
}
public void mousePressed(MouseEvent e) {
int[] v = read();
if (v != null) result.setText(String.valueOf(v[0] + v[1]));
}
public void mouseReleased(MouseEvent e) {
int[] v = read();
if (v != null) result.setText(String.valueOf(v[0] - v[1]));
}
public void mouseClicked(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public static void main(String[] args) {
SwingUtilities.invokeLater(SumDiff::new);
}
}
When the user presses the mouse, mousePressed reads the two inputs and writes in the third field. On releasing, mouseReleased writes . For inputs 8 and 3, press shows 11 and release shows 5.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 10 marks
What is a bean design pattern? Explain simple, Boolean, and indexed property design patterns with suitable examples in detail.
Answer
Bean design patterns
A JavaBean is a reusable Java class that follows conventions: a public no-argument constructor, private properties accessed via public getter and setter methods, and (usually) Serializable. Design patterns are the naming conventions for these methods; the builder tool or the Introspector uses them to discover properties, events and methods automatically, without extra description.
1. Simple property
A single value with a getter and a setter.
public T getXxx()
public void setXxx(T value)
If only the getter exists the property is read-only; if only the setter, write-only.
private int age;
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
2. Boolean property
A property of type boolean. The getter may use is (preferred) or get.
public boolean isXxx()
public void setXxx(boolean value)
private boolean married;
public boolean isMarried() { return married; }
public void setMarried(boolean m) { married = m; }
3. Indexed property
A property that is an array; elements are accessed by index, and the whole array too.
public T getXxx(int index)
public void setXxx(int index, T value)
public T[] getXxx()
public void setXxx(T[] values)
private int[] marks = new int[5];
public int getMarks(int i) { return marks[i]; }
public void setMarks(int i, int v) { marks[i] = v; }
public int[] getMarks() { return marks; }
public void setMarks(int[] m) { marks = m; }
These patterns allow property sheets to be generated, and tools to read and set properties through reflection.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2021 · 10 marks
Define RMI. What is stub and parameter marshalling? Write a client/server application using RMI to find the product of two numbers.
Answer
RMI
Remote Method Invocation (RMI) is a Java mechanism that lets an object in one JVM invoke methods on an object in another JVM (possibly on another machine), as if it were local. It is Java's object-oriented counterpart of RPC.
Stub
The stub is the client-side proxy of the remote object. It implements the same remote interface; when the client calls a method, the stub marshals the parameters, sends the call over the network to the server (skeleton/runtime), waits for the result, unmarshals and returns it. (Since Java 5 stubs are generated dynamically.)
Parameter marshalling
Marshalling is the process of converting parameters (and return values) into a byte stream for transmission: primitives are copied, local objects are serialized (so must implement Serializable), and remote objects are passed as stubs. The receiver unmarshals to rebuild them.
Application: product of two numbers
Remote interface Product.java
import java.rmi.*;
public interface Product extends Remote {
int multiply(int a, int b) throws RemoteException;
}
Implementation ProductImpl.java
import java.rmi.*;
import java.rmi.server.*;
public class ProductImpl extends UnicastRemoteObject implements Product {
public ProductImpl() throws RemoteException { super(); }
public int multiply(int a, int b) throws RemoteException { return a * b; }
}
Server Server.java
import java.rmi.registry.*;
public class Server {
public static void main(String[] args) throws Exception {
Registry reg = LocateRegistry.createRegistry(1099);
reg.rebind("ProductService", new ProductImpl());
System.out.println("Server ready");
}
}
Client Client.java
import java.rmi.registry.*;
public class Client {
public static void main(String[] args) throws Exception {
Registry reg = LocateRegistry.getRegistry("localhost", 1099);
Product p = (Product) reg.lookup("ProductService");
System.out.println("Product = " + p.multiply(6, 7));
}
}
Compile all files, run Server, then Client. The client prints Product = 42.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 5 marks
Why do we use Panels while creating GUI applications in Java? Explain the components of the event handling model in Java.
Answer
Why panels are used
A JPanel (or AWT Panel) is a lightweight, invisible container that holds and groups components inside a window.
- It helps to organise the GUI: related components (e.g. a form, a button bar) are placed in separate panels.
- Each panel can have its own layout manager, so complex layouts are made by nesting panels, e.g. a
BorderLayoutframe with aGridLayoutpanel in the centre and aFlowLayoutpanel at the bottom. - A panel can be treated as a unit: shown, hidden, moved, or reused.
- It is used as a drawing surface by overriding
paintComponent.
Components of the event handling model (delegation model)
- Event source: the component that generates the event (button, text field, window).
- Event object: an object of an event class (
ActionEvent,MouseEvent,KeyEvent,WindowEvent) that holds details about the event; the root class isjava.util.EventObject. - Event listener: an object implementing a listener interface (
ActionListener,MouseListener) with the handler methods that respond to the event.
The listener is registered with the source (button.addActionListener(listener)). When the event occurs, the source creates the event object and calls the listener's handler method (actionPerformed(ActionEvent e)), passing the event. Event handling is thus delegated to listeners, separating the GUI from application logic.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 5 marks
What are adapter classes? What is the benefit of using adapter classes in Java while creating events in GUI programs? Explain with an example.
Answer
Adapter classes
A listener interface such as MouseListener or WindowListener has several methods, and a class implementing it must define all of them. An adapter class is a class (in java.awt.event) that implements the listener interface with empty bodies for every method. The programmer extends the adapter and overrides only the methods needed.
Examples: MouseAdapter, KeyAdapter, WindowAdapter, FocusAdapter, MouseMotionAdapter.
Benefits
- Less code: no need to write empty methods for events that are not used.
- Cleaner, more readable programs.
- Works well with anonymous inner classes.
Limitation: Java has single inheritance, so a class that already extends another class (e.g. JFrame) cannot also extend an adapter directly; an inner or anonymous class is used instead.
Example
import java.awt.event.*;
import javax.swing.*;
public class AdapterDemo extends JFrame {
public AdapterDemo() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.out.println("Closing window");
System.exit(0);
}
});
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args) { new AdapterDemo(); }
}
Only windowClosing is written; the other six WindowListener methods are inherited as empty methods.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 5 marks
How the data can be accessed through a resultset object? Explain forward only, scroll-insensitive and scroll-sensitive resultsets.
Answer
Accessing data through a ResultSet
A ResultSet holds the rows returned by a query. It maintains a cursor, initially before the first row. next() moves it to the next row and returns false when no more rows remain. Column values are read with getXxx() methods by column name or index (starting at 1): getInt("id"), getString(2), getDouble(...).
ResultSet rs = st.executeQuery("SELECT id, name FROM student");
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString("name"));
}
The type is chosen when creating the statement: con.createStatement(type, concurrency).
Types
- Forward-only (
TYPE_FORWARD_ONLY): the default; the cursor moves only forward usingnext(). It is fastest and uses the least memory. - Scroll-insensitive (
TYPE_SCROLL_INSENSITIVE): the cursor can move forward, backward or to absolute positions (previous(),first(),last(),absolute(n),relative(n)). It does not reflect changes made to the database by others after the result set was created; it shows a snapshot. - Scroll-sensitive (
TYPE_SCROLL_SENSITIVE): also scrollable, and it does reflect changes made to the underlying data by other transactions while the result set is open (to the extent the driver supports it).
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
Concurrency may be CONCUR_READ_ONLY or CONCUR_UPDATABLE.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 5 marks
What is a Javabean? Explain different types of properties in Javabeans.
Answer
JavaBean
A JavaBean is a reusable software component written in Java that can be manipulated visually in a builder tool. A class is a bean if it:
- has a public no-argument constructor,
- exposes its state through private properties with public getter and setter methods,
- is
Serializable, so that its state can be saved and restored, - optionally supports events and listeners.
Types of properties
- Simple property: one value with
getXxx()andsetXxx(value), e.g.getName(),setName(String). - Boolean property: a
booleanvalue read withisXxx()and written withsetXxx(boolean). - Indexed property: an array of values, accessed per element with
getXxx(int i)andsetXxx(int i, T v), or as a whole array. - Bound property: notifies registered
PropertyChangeListeners when it changes, usingPropertyChangeSupport.firePropertyChange(...). - Constrained property: listeners (
VetoableChangeListener) may veto a change by throwingPropertyVetoExceptionfromvetoableChange(...); the setter declares that it throws this exception.
Read-only and write-only properties are those with only a getter or only a setter respectively.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 5 marks
What are the differences between servlets and Java applications? Explain different methods used for handling cookies in Java.
Answer
Servlets versus Java applications
| Servlet | Java application |
|---|---|
| Runs inside a web server or servlet container (Tomcat) in the JVM of the server | Runs standalone in its own JVM on the user's machine |
No main(); the container calls init(), service() (doGet, doPost) and destroy() | Execution starts from public static void main(String[] args) |
Extends HttpServlet and responds to HTTP requests | Plain class, no specific base class |
| Accessed by a client (browser) through a URL | Run from the command line or launched directly |
| Container manages lifecycle, threads (one thread per request), sessions and security | The programmer manages everything |
| Output is HTML or other content sent to the client | Output is to console or GUI |
Needs deployment (web.xml or annotations) | No deployment needed |
Methods for handling cookies
Class Cookie (javax.servlet.http.Cookie):
new Cookie(String name, String value): constructor.getName(),getValue(),setValue(String): read or change content.setMaxAge(int seconds)/getMaxAge(): lifetime;0deletes the cookie, a negative value lasts for the browser session.setPath(String),setDomain(String): scope of the cookie.setSecure(boolean),setHttpOnly(boolean): security attributes.
Request and response:
response.addCookie(Cookie c): sends a cookie to the browser.request.getCookies(): returns the array of cookies sent by the browser (ornull).
Cookie c = new Cookie("user", "Sita");
c.setMaxAge(3600);
response.addCookie(c);
Cookie[] all = request.getCookies();
if (all != null)
for (Cookie k : all)
out.println(k.getName() + "=" + k.getValue());
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 5 marks
What are marshalling and unmarshalling of arguments in RMI? Differentiate between CORBA and RMI.
Answer
Marshalling and unmarshalling in RMI
When a client calls a method on a remote object, the arguments live in the client JVM, while the method runs in the server JVM. They cannot be passed by memory address, so they must be converted into a byte stream that can travel over the network.
- Marshalling is the process of converting the method name, the arguments (and, on return, the result or exception) into a standard byte-stream format. The client-side stub does this using object serialization (
ObjectOutputStream). Primitive values are written by value and objects must implementjava.io.Serializable. Remote objects are passed as stubs (by reference). - Unmarshalling is the reverse: the server-side skeleton/dispatch layer reads the byte stream (
ObjectInputStream) and rebuilds the arguments as Java objects so the real method can be invoked. The same happens on the client for the returned value.
Flow: client calls stub, stub marshals the arguments, they travel through the Remote Reference Layer and Transport Layer, the server unmarshals them, runs the method, then marshals the result back, and the client stub unmarshals it.
Difference between CORBA and RMI
| Basis | RMI | CORBA |
|---|---|---|
| Language | Java only (Java to Java) | Language independent (Java, C++, Python, etc.) |
| Interface definition | Java interface extending Remote | IDL (Interface Definition Language) |
| Protocol | JRMP (or IIOP with RMI-IIOP) | IIOP (GIOP) |
| Object passing | Pass by value (serializable) or remote reference | Mostly by reference; by value needs special support |
| Middleware | Registry (rmiregistry) for naming | ORB with Naming Service |
| Complexity | Simple, built into the JDK | More complex, needs an ORB and IDL compiler |
| Garbage collection | Distributed garbage collection | No automatic distributed GC |
| Platform | Homogeneous (JVM) systems | Heterogeneous systems |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 5 marks
Write short notes on (Any Two): a) 2D shapes in swing b) MouseEvent and MouseListener c) Session tracking
Answer
(a) 2D shapes in Swing
Swing draws shapes by overriding paintComponent(Graphics g) of a JPanel. Casting the Graphics to Graphics2D gives access to the Java 2D API (package java.awt.geom), whose shape classes include Line2D, Rectangle2D, Ellipse2D, RoundRectangle2D, Arc2D and Polygon.
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class ShapePanel extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLUE);
g2.draw(new Rectangle2D.Double(20, 20, 100, 60));
g2.setColor(Color.RED);
g2.fill(new Ellipse2D.Double(150, 20, 80, 60));
g2.draw(new Line2D.Double(20, 120, 230, 120));
}
public static void main(String[] a) {
JFrame f = new JFrame("Shapes");
f.add(new ShapePanel());
f.setSize(300, 200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
draw() outlines a shape, fill() paints its interior, and setStroke(), setPaint() and setRenderingHint() control line width, colour/gradient and anti-aliasing.
(b) MouseEvent and MouseListener
A MouseEvent is generated when the user presses, releases, clicks, enters, exits, moves or drags the mouse over a component. It gives getX(), getY(), getButton() and getClickCount().
The MouseListener interface has five methods:
mouseClicked(MouseEvent e): button pressed and releasedmousePressed(MouseEvent e): button pressedmouseReleased(MouseEvent e): button releasedmouseEntered(MouseEvent e): pointer enters the componentmouseExited(MouseEvent e): pointer leaves the component
A component registers with addMouseListener(listener). Movement and dragging are handled by MouseMotionListener. MouseAdapter can be extended when only some methods are needed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 10 marks
Why do we need to use Layout managers while creating GUI application in Java? Explain the key interfaces required to develop any database application using Java. Also, write a program to display the records from the table Students who have got distinction and have a major subject Data science. Assume that the Student table is in the database College and contains the columns Rollno, Name, Level, Division and Major.
Answer
Need for layout managers
A GUI must look correct on different screen sizes, resolutions, fonts and operating systems. Fixed pixel positions break when the window is resized. A layout manager automatically sizes and positions the components inside a container according to a rule, so the programmer need not compute coordinates. It also adapts to resizing and to platform differences. Examples are FlowLayout, BorderLayout, GridLayout, CardLayout and GridBagLayout.
Key interfaces/classes for a JDBC database application
Driver: implemented by the vendor driver, which connects to the database.DriverManager(class): loads drivers and creates connections.Connection: a session with the database. It creates statements and controls transactions (commit(),rollback(),close()).Statement: executes static SQL.PreparedStatement: executes precompiled, parameterized SQL.CallableStatement: calls stored procedures.ResultSet: the table of rows returned by a query. It is traversed withnext()and read withgetXxx().ResultSetMetaDataandDatabaseMetaData: information about columns and about the database.SQLException: error handling.
Program (distinction students whose major is Data Science):
import java.sql.*;
public class DistinctionStudents {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/College";
String sql = "SELECT Rollno, Name, Level, Division, Major FROM Students "
+ "WHERE Division = ? AND Major = ?";
try (Connection con = DriverManager.getConnection(url, "root", "password");
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setString(1, "Distinction");
ps.setString(2, "Data Science");
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getInt("Rollno") + "\t" + rs.getString("Name") + "\t"
+ rs.getString("Level") + "\t" + rs.getString("Division") + "\t"
+ rs.getString("Major"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
The program connects to the College database, filters on Division = 'Distinction' and Major = 'Data Science', and prints every matching row.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 10 marks
Differentiate between declaration and expression tags used in JSP. Also create a JSP page that contains three textboxes to input three numbers and a button. It should display the greatest number among three numbers when the button is clicked.
Answer
Declaration tag vs expression tag
| Basis | Declaration tag <%! ... %> | Expression tag <%= ... %> |
|---|---|---|
| Purpose | Declares variables and methods at class level | Evaluates one expression and outputs its value |
| Code placed in | Class body of the generated servlet (outside _jspService) | Inside _jspService, as an argument to out.print() |
| Semicolon | Required after each statement | Not allowed after the expression |
| Output | Produces no output by itself | Prints the result into the response |
| Variables | Become instance variables, shared by all requests (not thread-safe) | None |
| Example | <%! int count = 0; %> | <%= count + 1 %> |
JSP to find the greatest of three numbers
greatest.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<body>
<form method="post" action="greatest.jsp">
Number 1: <input type="text" name="n1"><br>
Number 2: <input type="text" name="n2"><br>
Number 3: <input type="text" name="n3"><br>
<input type="submit" value="Find Greatest">
</form>
<%
String s1 = request.getParameter("n1");
String s2 = request.getParameter("n2");
String s3 = request.getParameter("n3");
if (s1 != null && s2 != null && s3 != null
&& !s1.isEmpty() && !s2.isEmpty() && !s3.isEmpty()) {
double a = Double.parseDouble(s1);
double b = Double.parseDouble(s2);
double c = Double.parseDouble(s3);
double max = a;
if (b > max) max = b;
if (c > max) max = c;
%>
<h3>Greatest number is: <%= max %></h3>
<%
}
%>
</body>
</html>
When the button is clicked, the form posts the three values to the same page. The scriptlet reads them with request.getParameter(), converts them to numbers, finds the maximum and prints it with an expression tag.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2022 · 10 marks
What is RMI? Explain its components. Write a client-server application in RMI to find the selling price of an item with cost price Rs. 5000 after a discount of Rs. 50.
Answer
RMI (Remote Method Invocation) is a Java API that lets an object running in one JVM invoke methods of an object in another JVM (on the same or a different machine) as if it were local. It is built on object serialization and gives a simple distributed-object model for Java.
Components of RMI
- Remote interface: declares the methods callable remotely. It extends
java.rmi.Remote, and every method throwsRemoteException. - Remote object (server implementation): implements the remote interface, usually by extending
UnicastRemoteObject. - Stub: the client-side proxy. It marshals the arguments, sends the call and unmarshals the result.
- Skeleton: the server-side dispatcher that unmarshals the request and calls the real object. In modern Java the stub talks to the server directly and the skeleton is not needed.
- RMI Registry: a naming service (
rmiregistry, default port 1099) where the server binds the remote object under a name and clients look it up. - Remote Reference Layer and Transport Layer: manage references and the network connection (JRMP over TCP).
- Client: looks up the stub in the registry and calls the methods.
Application: selling price = cost price - discount = 5000 - 50 = Rs 4950
PriceService.java:
import java.rmi.*;
public interface PriceService extends Remote {
double sellingPrice(double costPrice, double discount) throws RemoteException;
}
PriceServiceImpl.java:
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class PriceServiceImpl extends UnicastRemoteObject implements PriceService {
public PriceServiceImpl() throws RemoteException { super(); }
public double sellingPrice(double costPrice, double discount) throws RemoteException {
return costPrice - discount;
}
}
Server.java:
import java.rmi.registry.*;
public class Server {
public static void main(String[] args) throws Exception {
Registry reg = LocateRegistry.createRegistry(1099);
reg.rebind("PriceService", new PriceServiceImpl());
System.out.println("Server ready");
}
}
Client.java:
import java.rmi.registry.*;
public class Client {
public static void main(String[] args) throws Exception {
Registry reg = LocateRegistry.getRegistry("localhost", 1099);
PriceService ps = (PriceService) reg.lookup("PriceService");
System.out.println("Selling price = Rs " + ps.sellingPrice(5000, 50));
}
}
Run the server first, then the client. Output: Selling price = Rs 4950.0.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
What is the role of Event Listener in event handling? List different event listeners provided by Java.
Answer
Role of an event listener
Java uses the delegation event model. A source component (button, text field, window) generates an event object; a listener registered with that source receives it and runs the handling code. The listener is an interface with callback methods. The programmer implements it and registers it with addXxxListener(), so the user interface code is separated from the logic that responds to events. The source calls the listener's method automatically when the event occurs.
button.addActionListener(e -> label.setText("Clicked"));
Event listeners provided by Java (package java.awt.event and javax.swing.event)
| Listener | Event | Methods |
|---|---|---|
ActionListener | ActionEvent | actionPerformed |
ItemListener | ItemEvent | itemStateChanged |
KeyListener | KeyEvent | keyPressed, keyReleased, keyTyped |
MouseListener | MouseEvent | mouseClicked, mousePressed, mouseReleased, mouseEntered, mouseExited |
MouseMotionListener | MouseEvent | mouseMoved, mouseDragged |
MouseWheelListener | MouseWheelEvent | mouseWheelMoved |
WindowListener | WindowEvent | windowOpened, windowClosing, windowClosed, windowIconified, windowDeiconified, windowActivated, windowDeactivated |
FocusListener | FocusEvent | focusGained, focusLost |
TextListener | TextEvent | textValueChanged |
AdjustmentListener | AdjustmentEvent | adjustmentValueChanged |
ComponentListener | ComponentEvent | componentResized, componentMoved, componentShown, componentHidden |
ContainerListener | ContainerEvent | componentAdded, componentRemoved |
ListSelectionListener (Swing) | ListSelectionEvent | valueChanged |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
What is the use of RowSet interface? Explain connected and disconnected rowsets.
Answer
Use of the RowSet interface
javax.sql.RowSet extends java.sql.ResultSet. It is a wrapper that makes a result set easier to use: it is a JavaBeans component (with properties and listeners), it can manage its own connection (set with setUrl(), setUsername(), setPassword(), setCommand() and run with execute()), it is scrollable and updatable by default, and it can be serialized and sent over a network. Standard sub-interfaces are JdbcRowSet, CachedRowSet, WebRowSet, FilteredRowSet and JoinRowSet.
Connected RowSet
A connected rowset keeps its connection to the database open for as long as it is used. JdbcRowSet is the only connected type; it is a thin wrapper around a ResultSet that makes it a JavaBean. Changes (updates, inserts, deletes) are sent to the database immediately. It is simple, but it holds a connection and is not serializable for transport.
JdbcRowSet rs = RowSetProvider.newFactory().createJdbcRowSet();
rs.setUrl("jdbc:mysql://localhost/college");
rs.setUsername("root"); rs.setPassword("pw");
rs.setCommand("SELECT * FROM Students");
rs.execute();
while (rs.next()) System.out.println(rs.getString("Name"));
Disconnected RowSet
A disconnected rowset (CachedRowSet and its subtypes WebRowSet, FilteredRowSet, JoinRowSet) connects only to read data, copies it into memory, and then closes the connection. The application works on the cached data offline. When changes are made, it reconnects and writes them back with acceptChanges(). It is serializable, so it can be passed between tiers, and it saves connection resources. The drawback is that the cached data may become stale, and concurrent changes need conflict handling.
| Basis | Connected | Disconnected |
|---|---|---|
| Connection | Kept open | Closed after fetching |
| Example | JdbcRowSet | CachedRowSet |
| Serializable | No | Yes |
| Updates | Immediate | After acceptChanges() |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
What are bounded and constrained properties in JavaBeans? Explain the advantages of Java beans.
Answer
Bounded and constrained properties in JavaBeans
A JavaBean property is a private field exposed by getter and setter methods. Two special kinds of property notify other objects of changes.
Bounded property: when its value changes, the bean notifies registered listeners after the change. The bean keeps a PropertyChangeSupport object and fires firePropertyChange(name, oldValue, newValue). Listeners implement PropertyChangeListener and its propertyChange(PropertyChangeEvent e) method and register with addPropertyChangeListener(). The change cannot be refused.
Constrained property: listeners get a chance to veto the change before it happens. The bean uses VetoableChangeSupport and calls fireVetoableChange(name, old, new), and the setter throws PropertyVetoException. Listeners implement VetoableChangeListener and its vetoableChange() method. If any listener throws PropertyVetoException, the property keeps its old value.
public void setAge(int newAge) throws PropertyVetoException {
vcs.fireVetoableChange("age", age, newAge); // may veto
int old = age;
age = newAge;
pcs.firePropertyChange("age", old, newAge); // bound notification
}
Advantages of JavaBeans
- Reusability: write once, use in many applications and builder tools.
- Encapsulation: state is private and reached only through getters and setters.
- Easy visual use: builder tools discover properties, methods and events by introspection and let developers customise beans without coding.
- Persistence: beans are
Serializable, so their state can be saved and restored. - Event support: beans communicate through events and listeners.
- Platform independence: being Java, they run anywhere.
- Simplicity: just a public no-argument constructor plus naming conventions.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
What are the key methods provided in HttpSession interface for handling sessions? Explain.
Answer
HttpSession interface
HTTP is stateless, so a servlet container creates an HttpSession object to keep information about one user across several requests (a shopping cart, a login). It is obtained from the request with request.getSession() (creates one if absent) or request.getSession(false) (returns null if none). The container tracks it with a cookie (JSESSIONID) or URL rewriting.
Key methods
| Method | Use |
|---|---|
setAttribute(String name, Object value) | Stores an object in the session |
getAttribute(String name) | Retrieves the stored object (null if absent) |
removeAttribute(String name) | Removes an attribute |
getAttributeNames() | Enumerates all attribute names |
getId() | Returns the unique session ID |
getCreationTime() | Time the session was created (milliseconds) |
getLastAccessedTime() | Time of the last request in this session |
setMaxInactiveInterval(int sec) | Sets the timeout in seconds |
getMaxInactiveInterval() | Returns the timeout |
isNew() | True if the client has not yet joined the session |
invalidate() | Destroys the session and removes its data (used for logout) |
Example:
HttpSession session = request.getSession();
session.setAttribute("user", "Ram");
String u = (String) session.getAttribute("user");
session.setMaxInactiveInterval(600); // 10 minutes
// on logout
session.invalidate();
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 5 marks
Write short notes on (any two): a) Adapter classes b) CORBA c) Life cycle of a servlet
Answer
(a) Adapter classes
Many listener interfaces have several methods, and a class implementing one must define all of them even if only one is needed. An adapter class is a class that provides empty implementations of all the methods of a listener interface, so the programmer extends it and overrides only the methods needed. Adapters exist for listeners with more than one method: MouseAdapter, KeyAdapter, WindowAdapter, FocusAdapter, ComponentAdapter, MouseMotionAdapter, ContainerAdapter.
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(0); }
});
Since Java has no multiple inheritance, an adapter cannot be used if the class already extends another class (such as JFrame); an anonymous inner class is used instead.
(b) CORBA
The Common Object Request Broker Architecture is an OMG standard that lets objects written in different languages on different platforms communicate. Its main parts are:
- IDL (Interface Definition Language): a language-neutral description of the interfaces, compiled into stubs and skeletons for each language.
- ORB (Object Request Broker): the middleware that locates the remote object and carries the request and response.
- IIOP: the standard protocol between ORBs over TCP/IP.
- Naming Service: lets clients find objects by name.
- Stub and Skeleton: client and server proxies generated from the IDL.
It is language independent and platform independent, but more complex than RMI.
(c) Life cycle of a servlet
The container manages the servlet through three methods of the Servlet interface:
init(ServletConfig): called once after the servlet is loaded and instantiated, for one-time setup.service(request, response): called for every client request, in a separate thread. It dispatches todoGet(),doPost()and similar methods.destroy(): called once before the servlet is removed, to release resources.
Phases: loading and instantiation, initialization, request handling, destruction.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 10 marks
How a frame can be created in Java? Explain. Write a program to create a GUI application in Java that identifies the smaller and greater number between two input numbers taken through two text fields and displays the result in a label. If the user presses the mouse it should display the smaller number and if the user releases the mouse it should display the greater number.
Answer
Creating a frame in Java
A frame is a top-level window with a title bar and borders. In Swing it is created in two ways:
- By creating an object of
JFrame:JFrame f = new JFrame("My Frame"); f.setSize(400, 300); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); - By extending
JFrameand setting up the components in the constructor (used below).
Steps: create the frame, set its layout, add components (labels, text fields, buttons), set size, set the close operation and make it visible. Events are handled by registering listeners.
Program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MinMaxFrame extends JFrame {
JTextField t1 = new JTextField(8);
JTextField t2 = new JTextField(8);
JLabel result = new JLabel("Result: ");
public MinMaxFrame() {
super("Smaller / Greater");
setLayout(new FlowLayout());
add(new JLabel("Number 1:")); add(t1);
add(new JLabel("Number 2:")); add(t2);
add(result);
// The mouse is pressed or released on the frame's content area
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
try {
double a = Double.parseDouble(t1.getText().trim());
double b = Double.parseDouble(t2.getText().trim());
result.setText("Smaller: " + Math.min(a, b));
} catch (NumberFormatException ex) {
result.setText("Enter valid numbers");
}
}
public void mouseReleased(MouseEvent e) {
try {
double a = Double.parseDouble(t1.getText().trim());
double b = Double.parseDouble(t2.getText().trim());
result.setText("Greater: " + Math.max(a, b));
} catch (NumberFormatException ex) {
result.setText("Enter valid numbers");
}
}
});
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(MinMaxFrame::new);
}
}
The user types two numbers and presses the mouse on the free area of the frame; the label shows the smaller number. On releasing the mouse, the label shows the greater number.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 10 marks
Explain JDBC architecture. Write a program to insert three records into a table Item which is in the database Shop and contains the columns ItemID, Name, UnitPrice, Units and ExpiryDate.
Answer
JDBC architecture
JDBC (Java Database Connectivity) is an API for connecting Java programs to relational databases. The architecture has two layers:
- JDBC API layer: what the programmer uses. It contains
DriverManager,Connection,Statement,PreparedStatement,CallableStatement,ResultSetandSQLException. - JDBC Driver layer: vendor-specific drivers that translate JDBC calls to the database protocol.
DriverManagerselects the right driver for the URL.
Java application -> JDBC API -> DriverManager -> JDBC driver -> Database
Driver types: Type 1 (JDBC-ODBC bridge), Type 2 (native API), Type 3 (network protocol/middleware), Type 4 (pure Java thin driver, most widely used).
Steps in an application: load the driver, open a Connection, create a statement, execute the SQL, process the results, and close the resources.
Program (inserting three records into Item in the Shop database)
import java.sql.*;
public class InsertItems {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/Shop";
String sql = "INSERT INTO Item (ItemID, Name, UnitPrice, Units, ExpiryDate) VALUES (?, ?, ?, ?, ?)";
try (Connection con = DriverManager.getConnection(url, "root", "password");
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, 1); ps.setString(2, "Milk");
ps.setDouble(3, 120.0); ps.setInt(4, 50);
ps.setDate(5, Date.valueOf("2026-12-31"));
ps.executeUpdate();
ps.setInt(1, 2); ps.setString(2, "Biscuit");
ps.setDouble(3, 30.0); ps.setInt(4, 200);
ps.setDate(5, Date.valueOf("2027-03-15"));
ps.executeUpdate();
ps.setInt(1, 3); ps.setString(2, "Juice");
ps.setDouble(3, 90.0); ps.setInt(4, 80);
ps.setDate(5, Date.valueOf("2027-01-10"));
ps.executeUpdate();
System.out.println("Three records inserted");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
The same prepared statement is reused with new parameter values for each of the three rows.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2023 · 10 marks
Differentiate between servlet and JSP. Create a servlet that computes and displays the factorial of an input number entered from a page when the button from that page is pressed by the user.
Answer
Servlet vs JSP
| Basis | Servlet | JSP |
|---|---|---|
| Nature | Java class that contains HTML inside Java code | HTML page with Java code embedded in tags |
| Best for | Business logic, controllers | Presentation, views |
| Writing | Harder; HTML is printed with out.println() | Easier; HTML is written directly |
| Compilation | Compiled manually by the developer | Translated into a servlet and compiled by the container automatically |
| Modification | Needs recompilation and redeployment | Changes are picked up automatically |
| Implicit objects | Must be obtained by the programmer | Built in (request, response, session, out, etc.) |
| Maintenance | Harder for designers | Easier; suitable for web designers |
Factorial servlet
index.html:
<html>
<body>
<form action="FactorialServlet" method="post">
Enter a number: <input type="number" name="num" min="0" required>
<input type="submit" value="Compute Factorial">
</form>
</body>
</html>
FactorialServlet.java:
import java.io.*;
import java.math.BigInteger;
import javax.servlet.*;
import javax.servlet.http.*;
public class FactorialServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
int n = Integer.parseInt(request.getParameter("num"));
if (n < 0) {
out.println("<h3>Factorial is not defined for negative numbers</h3>");
} else {
BigInteger fact = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
fact = fact.multiply(BigInteger.valueOf(i));
}
out.println("<h3>Factorial of " + n + " = " + fact + "</h3>");
}
} catch (NumberFormatException e) {
out.println("<h3>Please enter a valid integer</h3>");
}
}
}
web.xml mapping (or use @WebServlet("/FactorialServlet")):
<servlet>
<servlet-name>FactorialServlet</servlet-name>
<servlet-class>FactorialServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FactorialServlet</servlet-name>
<url-pattern>/FactorialServlet</url-pattern>
</servlet-mapping>
For example, input 5 gives .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
What is the use of WindowEvent? List different methods of WindowListener interface with its uses.
Answer
WindowEvent
A WindowEvent (package java.awt.event) is generated when the state of a window (Frame, JFrame, Dialog) changes: it is opened, closed, minimized, restored, activated or deactivated. It lets a program react, for example by asking for confirmation before closing or saving data when the window closes. It is handled by a WindowListener registered with addWindowListener(); getWindow() returns the window that caused the event.
Methods of WindowListener
| Method | Use |
|---|---|
windowOpened(WindowEvent e) | Called the first time the window is made visible |
windowClosing(WindowEvent e) | Called when the user clicks the close (X) button; used to exit or confirm |
windowClosed(WindowEvent e) | Called after the window has been disposed |
windowIconified(WindowEvent e) | Called when the window is minimized |
windowDeiconified(WindowEvent e) | Called when the window is restored from the minimized state |
windowActivated(WindowEvent e) | Called when the window becomes the active window |
windowDeactivated(WindowEvent e) | Called when the window stops being the active window |
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(0); }
});
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
How can you display images in GUI using Java? Explain.
Answer
Displaying images in a Java GUI
In Swing, an image is shown by loading it into an ImageIcon and placing the icon on a component, most commonly a JLabel (or a JButton). ImageIcon supports GIF, JPEG and PNG.
import javax.swing.*;
import java.awt.*;
public class ImageDemo {
public static void main(String[] args) {
JFrame f = new JFrame("Image");
ImageIcon icon = new ImageIcon("photo.jpg");
JLabel label = new JLabel(icon);
f.add(label);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
To resize the image, scale it first:
Image img = icon.getImage().getScaledInstance(200, 150, Image.SCALE_SMOOTH);
label.setIcon(new ImageIcon(img));
Drawing with Graphics: a second method is to override paintComponent(Graphics g) of a JPanel and call g.drawImage(image, x, y, observer), where the image is loaded with Toolkit.getDefaultToolkit().getImage("photo.jpg") or ImageIO.read(new File("photo.jpg")). This gives control over position and size and is used for animation and custom drawing.
In AWT, the same is done with Toolkit.getImage() and Graphics.drawImage() inside paint().
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
Why do we need to create JavaBeans? Explain the steps involved in the creation of a JavaBean.
Answer
Need for JavaBeans
A JavaBean is a reusable software component written in Java. Beans are needed because they:
- are reusable and can be assembled into applications without rewriting code;
- can be manipulated visually in IDEs and builder tools through introspection;
- encapsulate data through private properties and public getters and setters;
- communicate with each other through events;
- are serializable, so their state can be saved and restored;
- are platform independent.
Steps to create a JavaBean
- Create a public class.
- Make it implement
java.io.Serializable. - Provide a public no-argument constructor.
- Declare private properties.
- Provide public
getXxx()/setXxx()methods (isXxx()for booleans) following the naming convention. - Optionally add event support (
PropertyChangeSupport) for bound properties. - Compile it, and package it in a JAR with a manifest entry marking it as a bean (
Java-Bean: True) for use in a builder tool.
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private int age;
public Student() { }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}
It can then be used by creating an object and calling its setters and getters (or <jsp:useBean> in JSP).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
What is the use of PreparedStatement? Differentiate between Statement and PreparedStatement.
Answer
Use of PreparedStatement
PreparedStatement (package java.sql) represents a precompiled SQL statement with placeholders (?) for parameters. The SQL is sent to the database once and compiled, then run many times with different values supplied through setInt(), setString(), setDouble(), setDate() and so on. It is used to run the same query repeatedly with different values efficiently and to protect against SQL injection, because parameter values are never part of the SQL text.
PreparedStatement ps = con.prepareStatement("INSERT INTO Student(id, name) VALUES (?, ?)");
ps.setInt(1, 101);
ps.setString(2, "Sita");
ps.executeUpdate();
Difference between Statement and PreparedStatement
| Basis | Statement | PreparedStatement |
|---|---|---|
| SQL | Static SQL string built by concatenation | Precompiled SQL with ? placeholders |
| Compilation | Compiled on every execution | Compiled once, reused |
| Performance | Slower for repeated queries | Faster for repeated queries |
| SQL injection | Vulnerable | Safe, since parameters are escaped |
| Parameters | Not supported | setXxx() methods |
| Readability | Hard with many values | Cleaner |
| Created by | con.createStatement() | con.prepareStatement(sql) |
| Execution | executeQuery(sql) | executeQuery() with no argument |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
What are declaration and expression tags in JSP? Explain with examples.
Answer
Declaration tag
The declaration tag <%! ... %> declares variables and methods at class level of the servlet generated from the JSP. The code goes outside _jspService(), and each statement ends with a semicolon. Declared variables are instance variables shared by all requests.
<%! int count = 0;
int square(int n) { return n * n; } %>
Expression tag
The expression tag <%= ... %> evaluates a single Java expression, converts the result to a string and writes it to the response. It is placed inside _jspService() as out.print(expression), and no semicolon is used.
<p>Square of 5 is <%= square(5) %></p>
<p>Today is <%= new java.util.Date() %></p>
Complete example
<html>
<body>
<%! int visits = 0;
int add(int a, int b) { return a + b; } %>
<% visits++; %>
<p>Sum = <%= add(10, 20) %></p>
<p>Page visited <%= visits %> times</p>
</body>
</html>
Output: Sum = 30 and the visit count, which increases with each request because the declared variable persists.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
What is RMI? Write a RMI client and server program to find the greater number among two numbers.
Answer
RMI (Remote Method Invocation) is a Java mechanism that lets a program in one JVM call methods of an object located in another JVM, on the same or a different machine, as if the object were local. The client uses a stub, and the server's remote object is registered in the RMI registry under a name that the client looks up.
Program: greater of two numbers
Compare.java (remote interface):
import java.rmi.*;
public interface Compare extends Remote {
int greater(int a, int b) throws RemoteException;
}
CompareImpl.java (server implementation):
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class CompareImpl extends UnicastRemoteObject implements Compare {
public CompareImpl() throws RemoteException { super(); }
public int greater(int a, int b) throws RemoteException {
return a > b ? a : b;
}
}
Server.java:
import java.rmi.registry.*;
public class Server {
public static void main(String[] args) throws Exception {
Registry reg = LocateRegistry.createRegistry(1099);
reg.rebind("CompareService", new CompareImpl());
System.out.println("Server started");
}
}
Client.java:
import java.rmi.registry.*;
public class Client {
public static void main(String[] args) throws Exception {
Registry reg = LocateRegistry.getRegistry("localhost", 1099);
Compare c = (Compare) reg.lookup("CompareService");
System.out.println("Greater = " + c.greater(25, 40));
}
}
Start the server and then the client. Output: Greater = 40.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 5 marks
Write short notes on (Any two): a) JMenuBar b) Session handling in Servlet c) Marshalling and Unmarshalling of arguments in RMI
Answer
(a) JMenuBar
JMenuBar is the Swing component that holds the menus of a window. It is placed at the top of a JFrame with setJMenuBar(). Menus (JMenu) are added to the bar, and each menu contains items (JMenuItem, JCheckBoxMenuItem, JRadioButtonMenuItem) and separators. Items fire ActionEvents handled by an ActionListener.
JMenuBar bar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem open = new JMenuItem("Open");
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(e -> System.exit(0));
file.add(open);
file.addSeparator();
file.add(exit);
bar.add(file);
frame.setJMenuBar(bar);
(b) Session handling in Servlet
HTTP is stateless, so the server must recognise a returning user. Session handling (session tracking) keeps user data across requests. The techniques are:
- Cookies: small data stored in the browser (
Cookieclass,response.addCookie()). - Hidden form fields: values carried inside the form.
- URL rewriting: the session ID is appended to the URL (
response.encodeURL()). - HttpSession: the container creates a session object per user, identified by the
JSESSIONIDcookie. Methods includegetSession(),setAttribute(),getAttribute(),setMaxInactiveInterval()andinvalidate().
(c) Marshalling and unmarshalling of arguments in RMI
Marshalling converts the method name, arguments and return values into a byte stream (via serialization) so they can be sent between JVMs; the stub performs it on the client side. Unmarshalling rebuilds the objects from the byte stream on the receiving side so the real method can be called. Arguments must be serializable or remote objects (passed as stubs).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 10 marks
Why do we need to use layout managers in GUI programming? Write a program to create a GUI form that takes data about a customer including cid, name, address, email and age and insert these data into the Customer table of the Shop database.
Answer
Need for layout managers
Components should keep a sensible arrangement whatever the screen size, resolution, font or operating system. A layout manager automatically positions and sizes the components in a container according to a rule, so the code need not use fixed coordinates. It handles window resizing, makes the GUI portable, and keeps the code simpler and easier to maintain. Common ones are FlowLayout, BorderLayout, GridLayout, CardLayout, BoxLayout and GridBagLayout.
Program: customer form saved to the database
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
public class CustomerForm extends JFrame implements ActionListener {
JTextField tCid = new JTextField(15), tName = new JTextField(15),
tAddress = new JTextField(15), tEmail = new JTextField(15),
tAge = new JTextField(15);
JButton save = new JButton("Save");
public CustomerForm() {
super("Customer Form");
setLayout(new GridLayout(6, 2, 5, 5));
add(new JLabel("CID:")); add(tCid);
add(new JLabel("Name:")); add(tName);
add(new JLabel("Address:")); add(tAddress);
add(new JLabel("Email:")); add(tEmail);
add(new JLabel("Age:")); add(tAge);
add(new JLabel("")); add(save);
save.addActionListener(this);
setSize(350, 250);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String sql = "INSERT INTO Customer (cid, name, address, email, age) VALUES (?, ?, ?, ?, ?)";
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/Shop", "root", "password");
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, Integer.parseInt(tCid.getText().trim()));
ps.setString(2, tName.getText());
ps.setString(3, tAddress.getText());
ps.setString(4, tEmail.getText());
ps.setInt(5, Integer.parseInt(tAge.getText().trim()));
ps.executeUpdate();
JOptionPane.showMessageDialog(this, "Customer saved");
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "CID and Age must be numbers");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "Database error: " + ex.getMessage());
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(CustomerForm::new);
}
}
The GridLayout arranges labels and fields in a neat table. On pressing Save, the values are read, converted and inserted through a PreparedStatement.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 10 marks
Explain the lifecycle of a Java Servlet. Write a servlet program that takes three numbers from an HTML page and computes the sum of natural numbers up to the greatest number among the three numbers.
Answer
Life cycle of a servlet
The servlet container controls the life of a servlet through the javax.servlet.Servlet interface.
- Loading and instantiation: the container loads the servlet class (on first request or at startup if
load-on-startupis set) and creates one instance. - Initialization,
init(ServletConfig config): called exactly once, for one-time setup such as opening database connections. - Request handling,
service(ServletRequest, ServletResponse): called for every request, each in a separate thread of the same instance.HttpServlet.service()callsdoGet(),doPost(),doPut()ordoDelete()according to the HTTP method. - Destruction,
destroy(): called once when the container removes the servlet or shuts down, to release resources. After that the object is garbage collected.
Servlet: sum of natural numbers up to the greatest of three numbers
If is the greatest number, the sum is (computed here with a loop). For example, for 4, 9, 6 the greatest is 9 and the sum is .
index.html:
<html>
<body>
<form action="SumServlet" method="post">
Number 1: <input type="number" name="n1" required><br>
Number 2: <input type="number" name="n2" required><br>
Number 3: <input type="number" name="n3" required><br>
<input type="submit" value="Calculate">
</form>
</body>
</html>
SumServlet.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SumServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
int a = Integer.parseInt(request.getParameter("n1"));
int b = Integer.parseInt(request.getParameter("n2"));
int c = Integer.parseInt(request.getParameter("n3"));
int max = Math.max(a, Math.max(b, c));
long sum = 0;
for (int i = 1; i <= max; i++) {
sum += i;
}
out.println("<h3>Greatest number = " + max + "</h3>");
out.println("<h3>Sum of natural numbers up to " + max + " = " + sum + "</h3>");
} catch (NumberFormatException e) {
out.println("<h3>Please enter valid integers</h3>");
}
}
}
Map the servlet to /SumServlet in web.xml or with @WebServlet("/SumServlet").
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2024 · 10 marks
What is directive element in JSP? Explain in detail. Create a JSP page that verifies the username and password entered form an HTML file and if the username and password are correct it displays a greetings message. Otherwise, it redirects to the register page.
Answer
Directive elements in JSP
Directives give the JSP container global information about the page that affects the whole generated servlet. Syntax: <%@ directive attribute="value" %>. There are three directives.
pagedirective: defines page-level properties. Attributes includelanguage,import(import Java packages),contentType,pageEncoding,session(true/false),errorPage,isErrorPage,buffer,autoFlush,isThreadSafe,info.<%@ page language="java" import="java.util.*,java.sql.*" contentType="text/html" errorPage="error.jsp" %>includedirective: inserts the content of another file (HTML, JSP) at translation time, before the page is compiled. Used for common headers and footers.<%@ include file="header.jsp" %>taglibdirective: declares a custom tag library (such as JSTL) and a prefix to use its tags.<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Login verification
login.html:
<html>
<body>
<form action="login.jsp" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
login.jsp (assuming the valid credentials are admin / admin123):
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%
String user = request.getParameter("username");
String pass = request.getParameter("password");
if ("admin".equals(user) && "admin123".equals(pass)) {
%>
<html><body>
<h2>Welcome, <%= user %>! Login successful.</h2>
</body></html>
<%
} else {
response.sendRedirect("register.html");
}
%>
If the username and password match, a greeting is shown; otherwise response.sendRedirect() sends the browser to the register page. In a real application the credentials would be checked against a database table rather than fixed strings.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
Explain event handling model in Java in detail.
Answer
Event handling model in Java (delegation event model)
Event handling is the mechanism that responds to user actions such as clicking a button, typing, moving the mouse or closing a window. Java uses the delegation event model: the component that generates an event delegates the handling to separate listener objects.
Components
- Event source: the component that generates the event (button, text field, frame). It allows listeners to register:
addActionListener(),addMouseListener(), etc. - Event object: an instance of
java.util.EventObjectsubclasses (ActionEvent,MouseEvent,KeyEvent,WindowEvent,ItemEvent) carrying information about the event and its source. - Event listener: an interface in
java.awt.event(ActionListener,MouseListener,KeyListener,WindowListener, ...) whose methods are called on the event. The programmer implements these methods (or extends an adapter class) to define the response.
Steps
- Implement the listener interface in a class.
- Register the listener with the source.
- When the user acts, the source creates an event object and calls the matching listener method, passing the object.
JButton b = new JButton("Click");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked");
}
});
Advantages: application logic is separated from the interface code, only registered listeners are notified (efficient), and a listener can serve several sources.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
What is the use of Layout managers in GUI applications in Java? Explain with proper examples.
Answer
Use of layout managers
A layout manager controls how components are sized and positioned inside a container. It is used so that the interface adapts to window resizing, different screen sizes and platforms, without the programmer calculating pixel positions. A layout is set with setLayout(new XxxLayout()).
Common layout managers
- FlowLayout: places components left to right in a row, wrapping to the next row when full. Default for
Panel/JPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); add(new JButton("A")); add(new JButton("B")); - BorderLayout: divides the container into North, South, East, West and Center. Default for
Frame/JFrame.add(new JButton("Top"), BorderLayout.NORTH); add(new JTextArea(), BorderLayout.CENTER); - GridLayout: arranges components in a grid of equal-sized cells.
setLayout(new GridLayout(2, 3)); - CardLayout: stacks components like cards, showing one at a time.
- GridBagLayout: flexible grid where components may span several rows and columns with constraints.
- BoxLayout: arranges components in a single row or column.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
What is the use of Resultset class in JDBC? Explain the types of Resultset in JDBC.
Answer
Use of ResultSet
java.sql.ResultSet stores the table of data returned by executing a SELECT query. It keeps a cursor positioned before the first row; next() moves forward one row, and the getters (getInt(), getString(), getDouble(), getDate()) read column values by name or index. It can also be used to update rows if it is updatable (updateXxx(), updateRow(), insertRow(), deleteRow()).
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString("name"));
}
Types of ResultSet
By scrolling ability and sensitivity (set in con.createStatement(type, concurrency)):
- TYPE_FORWARD_ONLY: cursor moves only forward (default); fastest.
- TYPE_SCROLL_INSENSITIVE: cursor moves both ways and can jump to any row (
first(),last(),previous(),absolute()); does not reflect changes made to the data by others after the query. - TYPE_SCROLL_SENSITIVE: scrollable and reflects changes made by others in the underlying data.
By concurrency:
- CONCUR_READ_ONLY: the data can only be read (default).
- CONCUR_UPDATABLE: the data can be modified through the result set.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
Define Jayabean. How persistence is achieved in Javabeans?
Answer
JavaBean
A JavaBean is a reusable Java component: a public class with a public no-argument constructor, private properties accessed through public getter and setter methods, and which implements java.io.Serializable. It can be used and customised in visual builder tools and in JSP via <jsp:useBean>.
Persistence in JavaBeans
Persistence means saving the state of a bean (the values of its properties) so that it can be restored later. In JavaBeans it is achieved through serialization:
- The bean implements
java.io.Serializable(orExternalizablefor custom control). - Its state is written to a stream by
ObjectOutputStream.writeObject(bean)(for example into a file or a JAR), and restored withObjectInputStream.readObject(). - Fields marked
transient(andstaticfields) are not saved. - A builder tool uses the same mechanism to save a customised bean at design time and reload it at run time.
// save
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("bean.ser"));
out.writeObject(student);
out.close();
// restore
ObjectInputStream in = new ObjectInputStream(new FileInputStream("bean.ser"));
Student s = (Student) in.readObject();
in.close();
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
How JSP is different from servlet? Explain JSP scriptlet tag with an example.
Answer
JSP vs servlet
| JSP | Servlet |
|---|---|
| HTML with Java code embedded in tags | Java code with HTML printed using out.println() |
| Best for presentation (view) | Best for logic and control |
| Automatically translated and compiled into a servlet by the container | Compiled by the programmer and mapped in web.xml/annotation |
| Easy to write and maintain; designers can edit it | Harder to write and maintain for UI |
Implicit objects (request, response, session, out...) available | Must be obtained manually |
| Changes take effect without recompiling manually | Needs recompilation and redeployment |
Scriptlet tag
Written <% ... %>, it holds any Java statements. The code is placed inside the _jspService() method of the generated servlet and is executed for each request. Variables declared in it are local, and every statement ends with a semicolon.
<html><body>
<%
int n = 5;
int fact = 1;
for (int i = 1; i <= n; i++) fact *= i;
out.println("Factorial of " + n + " is " + fact);
%>
</body></html>
Output: Factorial of 5 is 120.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
What are stub and skeleton? Also explain the use of RMI Registry.
Answer
Stub and skeleton
- Stub: a client-side proxy object representing the remote object. The client calls methods on the stub as if on the real object; the stub marshals the parameters, sends the request to the server, waits, and unmarshals the returned value or exception. It is created from the remote interface (dynamically in modern Java; earlier by
rmic). - Skeleton: a server-side helper that receives the request from the network, unmarshals the parameters, invokes the method on the actual remote object, and marshals the result back to the stub. (Skeletons are no longer required since Java 1.2, where the runtime does this using reflection.)
Use of RMI Registry
The RMI registry is a simple naming service that runs on the server host (default port 1099). It keeps a table mapping names to remote object references.
- The server binds its remote object to a name:
Naming.rebind("rmi://host/Name", obj)orregistry.bind(). - The client looks up the name:
Naming.lookup("rmi://host/Name"), and receives a stub for the remote object.
It therefore lets clients find remote objects without knowing their location in advance. It is started with the rmiregistry command or LocateRegistry.createRegistry(1099).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 5 marks
Write short notes on: (Any two)
a) Declaration tag in JSP
b) Graphics class
c) Rowset in JDBC
Answer
(a) Declaration tag in JSP
Written <%! ... %>, it declares variables and methods at the class level of the servlet generated from the JSP. They become instance members, so a declared variable is shared by all requests. It produces no output and each statement ends with a semicolon.
<%! int hits = 0;
int add(int a, int b) { return a + b; } %>
<% hits++; %>
Hits: <%= hits %>, Sum: <%= add(2, 3) %>
(b) Graphics class
java.awt.Graphics is an abstract class that provides methods for drawing on components. Drawing is done by overriding paint(Graphics g) (AWT) or paintComponent(Graphics g) (Swing). Main methods:
drawLine(),drawRect(),fillRect(),drawOval(),fillOval(),drawArc(),drawPolygon()drawString(String, x, y)for text,drawImage()for imagessetColor(Color),setFont(Font)
public void paint(Graphics g) {
g.setColor(Color.RED);
g.fillOval(50, 50, 100, 100);
g.drawString("Circle", 80, 170);
}
repaint() requests a redraw. Graphics2D extends it with advanced shapes, strokes and transformations.
(c) RowSet in JDBC
javax.sql.RowSet extends ResultSet and is a JavaBean-style, scrollable and updatable wrapper for tabular data. Connected rowset: JdbcRowSet, which keeps the database connection open. Disconnected rowsets: CachedRowSet, WebRowSet, FilteredRowSet, JoinRowSet, which cache the data in memory, work without a connection and can be serialised; changes are applied back using acceptChanges(). It is configured with properties (setUrl, setUsername, setPassword, setCommand) and execute().
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 10 marks
What is window event? List and explain WindowListener interface methods in detail with example.
Answer
Window event
A WindowEvent (java.awt.event.WindowEvent) is generated when the state of a window such as Frame, JFrame or Dialog changes: opened, closing, closed, minimised, restored, activated or deactivated. It is handled by a class implementing WindowListener (or extending WindowAdapter) and registered with addWindowListener().
Methods of WindowListener
windowOpened(WindowEvent e): invoked when the window is first made visible.windowClosing(WindowEvent e): invoked when the user clicks the close button; used to exit or confirm closure.windowClosed(WindowEvent e): invoked after the window has been disposed.windowIconified(WindowEvent e): invoked when the window is minimised.windowDeiconified(WindowEvent e): invoked when the window is restored from minimised.windowActivated(WindowEvent e): invoked when the window becomes active (gets focus).windowDeactivated(WindowEvent e): invoked when the window ceases to be active.
Example
import java.awt.*;
import java.awt.event.*;
public class WindowDemo extends Frame implements WindowListener {
Label lbl = new Label("Window status");
WindowDemo() {
add(lbl);
addWindowListener(this);
setSize(300, 150);
setVisible(true);
}
public void windowOpened(WindowEvent e) { lbl.setText("Opened"); }
public void windowClosing(WindowEvent e) { dispose(); }
public void windowClosed(WindowEvent e) { System.out.println("Closed"); }
public void windowIconified(WindowEvent e) { System.out.println("Minimised"); }
public void windowDeiconified(WindowEvent e) { System.out.println("Restored"); }
public void windowActivated(WindowEvent e) { lbl.setText("Active"); }
public void windowDeactivated(WindowEvent e) { lbl.setText("Inactive"); }
public static void main(String[] args) { new WindowDemo(); }
}
Since all seven methods must be defined when implementing the interface, WindowAdapter is often used when only a few are needed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 10 marks
What are HTTPServletRequest and HTTPServletResponse? Create a servlet application that takes student's information including their roll number, name, address and level and store these information in the database.
Answer
HttpServletRequest and HttpServletResponse
- HttpServletRequest (
javax.servlet.http): represents the client's HTTP request and is passed todoGet()/doPost(). It gives access to request parameters (getParameter(),getParameterValues()), headers (getHeader()), cookies (getCookies()), the session (getSession()), the method (getMethod()), attributes and the request dispatcher. - HttpServletResponse: represents the response sent to the client. It is used to set the content type (
setContentType()), obtain the writer/stream (getWriter(),getOutputStream()), add cookies (addCookie()), set headers and status (setHeader(),setStatus()), and redirect (sendRedirect()).
Application: storing student information
student.html
<html><body>
<form action="StudentServlet" method="post">
Roll No: <input type="text" name="roll"><br>
Name: <input type="text" name="name"><br>
Address: <input type="text" name="address"><br>
Level: <input type="text" name="level"><br>
<input type="submit" value="Save">
</form>
</body></html>
StudentServlet.java
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/StudentServlet")
public class StudentServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String sql = "INSERT INTO Student (roll, name, address, level) VALUES (?, ?, ?, ?)";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/College", "root", "");
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, Integer.parseInt(req.getParameter("roll")));
ps.setString(2, req.getParameter("name"));
ps.setString(3, req.getParameter("address"));
ps.setString(4, req.getParameter("level"));
int rows = ps.executeUpdate();
out.println(rows > 0 ? "<h3>Student record saved</h3>"
: "<h3>Record not saved</h3>");
}
} catch (NumberFormatException e) {
out.println("<h3>Roll number must be a number</h3>");
} catch (Exception e) {
out.println("<h3>Error: " + e.getMessage() + "</h3>");
}
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2025 · 10 marks
Differentiate between RMI and CORBA. Write a client and server program to accept three numbers and display the greatest one.
Answer
RMI vs CORBA
| RMI | CORBA |
|---|---|
| Java-to-Java only | Language independent (Java, C++, Python, etc.) |
Interfaces written in Java (extend Remote) | Interfaces written in OMG IDL |
| Uses JRMP (or RMI-IIOP) | Uses IIOP through an ORB |
| Objects can be passed by value (serialization) and code can be downloaded | Only IDL data types; no code download |
| Simple, lightweight, easy to build | More complex, with a larger infrastructure |
| Naming through RMI registry | Naming through CORBA Naming Service |
| Garbage collection of remote objects is built in | No automatic distributed garbage collection |
Program: greatest of three numbers
Greatest.java
import java.rmi.*;
public interface Greatest extends Remote {
int greatest(int a, int b, int c) throws RemoteException;
}
GreatestImpl.java (server)
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
public class GreatestImpl extends UnicastRemoteObject implements Greatest {
public GreatestImpl() throws RemoteException { super(); }
public int greatest(int a, int b, int c) throws RemoteException {
return Math.max(a, Math.max(b, c));
}
public static void main(String[] args) throws Exception {
LocateRegistry.createRegistry(1099);
Naming.rebind("rmi://localhost:1099/GreatestService", new GreatestImpl());
System.out.println("Server ready");
}
}
GreatestClient.java
import java.rmi.*;
import java.util.Scanner;
public class GreatestClient {
public static void main(String[] args) throws Exception {
Greatest g = (Greatest) Naming.lookup("rmi://localhost:1099/GreatestService");
Scanner sc = new Scanner(System.in);
System.out.print("Enter three numbers: ");
int a = sc.nextInt(), b = sc.nextInt(), c = sc.nextInt();
System.out.println("Greatest number: " + g.greatest(a, b, c));
}
}
Start the server first, then the client.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2026 · 5 marks
List and explain different drawing methods in Graphics class.
Answer
The java.awt.Graphics class provides methods for drawing on a component, usually inside paint(Graphics g) or paintComponent(Graphics g).
Main drawing methods
drawString(String s, int x, int y)draws text with its baseline at (x, y).drawLine(int x1, int y1, int x2, int y2)draws a straight line between two points.drawRect(int x, int y, int w, int h)andfillRect(...)draw an outlined or filled rectangle.drawRoundRect(x, y, w, h, arcW, arcH)andfillRoundRect(...)draw a rectangle with rounded corners.drawOval(int x, int y, int w, int h)andfillOval(...)draw an ellipse or circle inside the given bounding box.drawArc(x, y, w, h, startAngle, arcAngle)andfillArc(...)draw part of an oval.drawPolygon(int[] xs, int[] ys, int n)andfillPolygon(...)draw a closed polygon;drawPolyline(...)leaves it open.draw3DRect(...)draws a rectangle with a raised or sunken 3D look.drawImage(Image img, int x, int y, ImageObserver o)draws an image.setColor(Color c)andsetFont(Font f)set the current colour and font;clearRect(...)clears an area.
Example
import java.awt.*;
public class DrawDemo extends Frame {
public void paint(Graphics g) {
g.setColor(Color.RED);
g.drawLine(50, 50, 200, 50);
g.drawRect(50, 70, 100, 60);
g.setColor(Color.BLUE);
g.fillOval(180, 70, 80, 60);
g.setColor(Color.BLACK);
g.drawString("Hello Graphics", 50, 170);
}
public static void main(String[] a) {
DrawDemo f = new DrawDemo();
f.setSize(320, 220);
f.setVisible(true);
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2026 · 1+4 marks
What is JDBC? Explain the steps for developing database applications using JDBC.
Answer
JDBC (Java Database Connectivity) is a Java API (package java.sql) that lets Java programs connect to relational databases, send SQL statements and process the results in a database-independent way. It uses a driver for each database (MySQL, Oracle, etc.).
Steps for developing a JDBC application
- Load the driver:
Class.forName("com.mysql.cj.jdbc.Driver");(automatic in JDBC 4 and later when the driver JAR is on the classpath). - Establish a connection:
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "root", "password"); - Create a statement:
Statement st = con.createStatement();or aPreparedStatementfor parameterised queries. - Execute the SQL:
ResultSet rs = st.executeQuery("SELECT * FROM student");for queries, orst.executeUpdate("INSERT ...")for insert, update and delete. - Process the result:
while (rs.next()) { System.out.println(rs.getInt(1) + " " + rs.getString(2)); } - Close the resources:
rs.close(); st.close(); con.close();
import java.sql.*;
public class Demo {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM student");
while (rs.next())
System.out.println(rs.getInt(1) + " " + rs.getString(2));
con.close();
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2026 · 5 marks
How can we create Java beans? Explain.
Answer
A Java Bean is a reusable software component written in Java that can be manipulated visually in a builder tool. It follows these conventions:
- It is a public class with a public no-argument constructor.
- Its properties are private and accessed through public getter and setter methods (
getXxx(),setXxx(), andisXxx()for booleans). - It should implement
java.io.Serializableso its state can be saved. - It may support events, using listeners such as
PropertyChangeListener.
Steps to create a bean
- Write the class following the rules above.
- Compile it.
- Package it in a JAR with a manifest entry
Name: Student.classandJava-Bean: True, if it is to be used in a builder tool. - Use it in a program, or in JSP with
<jsp:useBean>,<jsp:setProperty>and<jsp:getProperty>.
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private int roll;
public Student() {}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getRoll() { return roll; }
public void setRoll(int roll) { this.roll = roll; }
}
Use in JSP:
<jsp:useBean id="s" class="Student" scope="session"/>
<jsp:setProperty name="s" property="name" value="Ram"/>
<jsp:getProperty name="s" property="name"/>
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2026 · 2.5+2.5 marks
Write short notes on:(Any two)
a. JSP request
b. Adapter classes
c. Color class in Java
Answer
a. JSP request
request is an implicit object of type javax.servlet.http.HttpServletRequest, available in every JSP page without declaring it. It carries the client's data to the page. Common methods are:
getParameter("name")returns a form or query parameter.getParameterValues("name")returns all values of a multi-valued parameter.getHeader("User-Agent")returns a header value.getMethod(),getRemoteAddr()andgetRequestURI()return details of the request.getSession()returns the session, andgetCookies()returns the cookies.setAttribute()andgetAttribute()share data within one request, for example across<jsp:forward>.
<% String user = request.getParameter("user"); %>
Welcome, <%= user %>
b. Adapter classes
An adapter class is a convenience class that gives empty implementations of all methods of an event listener interface. A programmer extends it and overrides only the needed methods, instead of implementing every method of the interface. Examples:
| Adapter | Listener interface |
|---|---|
WindowAdapter | WindowListener |
MouseAdapter | MouseListener |
KeyAdapter | KeyListener |
FocusAdapter | FocusListener |
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(0); }
});
c. Color class in Java
java.awt.Color represents a colour in the RGB colour space, with each component from 0 to 255 and an optional alpha value. Constants such as Color.RED, Color.BLUE and Color.GREEN are predefined. A custom colour is created with new Color(255, 128, 0). Useful methods are getRed(), getGreen(), getBlue(), brighter() and darker(). Colours are applied with g.setColor(c), setBackground(c) and setForeground(c).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2026 · 2+8 marks
What is the role of Event Listener in event handling? Explain in details with an example.
Answer
Role of an event listener
In the Java delegation event model, a source component (button, text field, window) generates an event object when the user acts on it. A listener is an object that implements a listener interface, such as ActionListener, MouseListener or KeyListener, and is registered with the source. When the event occurs, the source calls the listener's handler method and passes the event object, so the program can respond. The listener therefore:
- receives the event from the source,
- separates the event-handling code from the user interface code,
- contains the logic that responds to the event.
Steps
- Implement the listener interface (or use an inner or anonymous class).
- Register it with the component, for example
button.addActionListener(this). - Override the handler method, for example
actionPerformed(ActionEvent e).
Example
import java.awt.*;
import java.awt.event.*;
public class AddDemo extends Frame implements ActionListener {
TextField t1 = new TextField(10), t2 = new TextField(10);
Label result = new Label("Result: ");
Button b = new Button("Add");
AddDemo() {
setLayout(new FlowLayout());
add(t1); add(t2); add(b); add(result);
b.addActionListener(this); // register the listener
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(0); }
});
setSize(300, 150);
setVisible(true);
}
public void actionPerformed(ActionEvent e) { // event handler
int a = Integer.parseInt(t1.getText());
int c = Integer.parseInt(t2.getText());
result.setText("Result: " + (a + c));
}
public static void main(String[] args) { new AddDemo(); }
}
Here the Button is the event source, ActionEvent is the event object, and AddDemo is the listener whose actionPerformed() adds the numbers when the button is clicked.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2026 · 2+3+5 marks
How cookies can be used to store the session information? Explain different methods of the Cookie class for managing cookies. Also create a servlet that creates a cookie and display the information stored in that cookie.
Answer
Cookies for session information
A cookie is a small piece of data (name and value) that the server sends to the browser in the response header. The browser stores it and sends it back with every later request to the same site. A server can store a session identifier, such as a session ID or user name, in a cookie. On each request the servlet reads the cookie and recognises the user, which makes up for HTTP being stateless. Cookies may have an expiry time, so they can last beyond a single session.
Methods of the Cookie class
Cookie(String name, String value)is the constructor.getName()returns the cookie name.getValue()andsetValue(String)get and set the value.setMaxAge(int seconds)sets the lifetime;getMaxAge()reads it. A negative value means the cookie is deleted when the browser closes, and 0 deletes it.setPath(String)andsetDomain(String)restrict where the cookie is sent.setSecure(boolean)sends it only over HTTPS.setHttpOnly(boolean)hides it from client-side scripts.setComment(String)andgetComment()handle the comment text.
The servlet adds a cookie with response.addCookie(c) and reads cookies with request.getCookies().
Servlet that creates a cookie and displays it
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie[] cookies = request.getCookies();
boolean found = false;
if (cookies != null) {
for (Cookie c : cookies) {
if (c.getName().equals("username")) {
out.println("<h3>Cookie found</h3>");
out.println("Name: " + c.getName() + "<br>");
out.println("Value: " + c.getValue());
found = true;
}
}
}
if (!found) {
Cookie c = new Cookie("username", "Ram");
c.setMaxAge(60 * 60); // one hour
response.addCookie(c);
out.println("<h3>Cookie created: username = Ram</h3>");
out.println("Reload the page to read it.");
}
}
}
On the first request the cookie is created. On reload the browser returns it and the servlet prints its name and value.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2026 · 3+7 marks
What is RMI registry? Explain its role in the RMI application. Create a JSP application that takes a product details that includes product id, product name, price and quantity and store these information in the database.
Answer
RMI registry
The RMI registry is a simple naming service (a remote object directory) that runs on the server host, by default on port 1099. The server binds a remote object to a name in the registry. Clients look up that name to obtain a stub (a reference to the remote object).
Role in an RMI application
- The server creates the remote object and registers it with
Naming.rebind("rmi://localhost/Calc", obj)orLocateRegistry.getRegistry().rebind(...). - The client calls
Naming.lookup("rmi://host/Calc")to get the stub, and then calls remote methods through it as if they were local. - It decouples client and server, since clients need only the name and the host, not the object itself.
- It is started with the
rmiregistrycommand, or in code withLocateRegistry.createRegistry(1099).
JSP application to store product details
product.html
<form action="saveProduct.jsp" method="post">
Product ID: <input type="text" name="pid"><br>
Product Name: <input type="text" name="pname"><br>
Price: <input type="text" name="price"><br>
Quantity: <input type="text" name="qty"><br>
<input type="submit" value="Save">
</form>
saveProduct.jsp
<%@ page import="java.sql.*" %>
<%
int pid = Integer.parseInt(request.getParameter("pid"));
String pname = request.getParameter("pname");
double price = Double.parseDouble(request.getParameter("price"));
int qty = Integer.parseInt(request.getParameter("qty"));
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/shop", "root", "");
PreparedStatement ps = con.prepareStatement(
"INSERT INTO product(pid, pname, price, quantity) VALUES(?,?,?,?)");
ps.setInt(1, pid);
ps.setString(2, pname);
ps.setDouble(3, price);
ps.setInt(4, qty);
int n = ps.executeUpdate();
if (n > 0) out.println("Product saved successfully.");
con.close();
} catch (Exception e) {
out.println("Error: " + e.getMessage());
}
%>
The table is created with CREATE TABLE product(pid INT PRIMARY KEY, pname VARCHAR(50), price DOUBLE, quantity INT);
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
Questions from TU BCA 2021 Sixth Semester Applied Economics (TU board exam, 2021), TU BCA 2022 Sixth Semester Applied Economics (TU board exam, 2022), TU BCA 2023 Sixth Semester Applied Economics (TU board exam, 2023), TU BCA 2024 Sixth Semester Applied Economics (TU board exam, 2024), TU BCA 2025 Sixth Semester Applied Economics (TU board exam, 2025), TU BCA 2026 Sixth Semester Applied Economics (TU board exam, 2026), TU BCA 2021 Sixth Semester Distributed System (TU board exam, 2021), TU BCA 2022 Sixth Semester Distributed System (TU board exam, 2022), TU BCA 2023 Sixth Semester Distributed System (TU board exam, 2023), TU BCA 2024 Sixth Semester Distributed System (TU board exam, 2024), TU BCA 2025 Sixth Semester Distributed System (TU board exam, 2025), TU BCA 2026 Sixth Semester Distributed System (TU board exam, 2026), TU BCA 2021 Sixth Semester Advanced Java Programming (TU board exam, 2021), TU BCA 2022 Sixth Semester Advanced Java Programming (TU board exam, 2022), TU BCA 2023 Sixth Semester Advanced Java Programming (TU board exam, 2023), TU BCA 2024 Sixth Semester Advanced Java Programming (TU board exam, 2024), TU BCA 2025 Sixth Semester Advanced Java Programming (TU board exam, 2025), TU BCA 2026 Sixth Semester Advanced Java Programming (TU board exam, 2026), TU BCA 2021 Sixth Semester Mobile Programming (TU board exam, 2021), TU BCA 2022 Sixth Semester Mobile Programming (TU board exam, 2022), TU BCA 2023 Sixth Semester Mobile Programming (TU board exam, 2023), TU BCA 2024 Sixth Semester Mobile Programming (TU board exam, 2024), TU BCA 2025 Sixth Semester Mobile Programming (TU board exam, 2025), TU BCA 2026 Sixth Semester Mobile Programming (TU board exam, 2026), TU BCA 2021 Sixth Semester Network Programming (TU board exam, 2021), TU BCA 2022 Sixth Semester Network Programming (TU board exam, 2022), TU BCA 2023 Sixth Semester Network Programming (TU board exam, 2023), TU BCA 2024 Sixth Semester Network Programming (TU board exam, 2024) and TU BCA 2025 Sixth Semester Network Programming (TU board exam, 2025). Answers are written for this site; check them against your class notes.