Chapter 1
Advanced Java Programming
TU BSc CSIT past exam questions
Past questions and answers
72 questions set from this chapter. Most repeated first.
- 2077 · 10 marks
What is the significance of stub and skeleton In RMI? Create a RMI application such that a client sends an Integer number to the server and the server return the factorial value of that integer. Give a clear specification for every step.
Answer
Significance of stub and skeleton
RMI (Remote Method Invocation) lets an object in one JVM call methods of an object in another JVM as if it were local. The stub and skeleton hide the network communication.
- Stub (client-side proxy): It implements the same remote interface as the real object. When the client calls a method, the stub marshals (serializes) the method name and arguments, sends them over the network, waits, then unmarshals the return value or exception and gives it to the client. The client never writes socket code.
- Skeleton (server-side dispatcher): It receives the request, unmarshals the arguments, invokes the method on the actual remote object, and marshals the result back to the stub. (From Java 1.2 the skeleton is replaced by reflection in the RMI runtime, and from Java 5 stubs are generated dynamically, but the concept remains.)
Together they provide location transparency, and the stub/skeleton sit above the Remote Reference Layer and Transport Layer.
Application: factorial using RMI
Step 1: Define the remote interface (Factorial.java). It extends Remote, and every method throws RemoteException.
import java.rmi.*;
public interface Factorial extends Remote {
long fact(int n) throws RemoteException;
}
Step 2: Implement the remote object (FactorialImpl.java). It extends UnicastRemoteObject, which exports the object.
import java.rmi.*;
import java.rmi.server.*;
public class FactorialImpl extends UnicastRemoteObject implements Factorial {
public FactorialImpl() throws RemoteException { super(); }
public long fact(int n) throws RemoteException {
long f = 1;
for (int i = 2; i <= n; i++) f *= i;
return f;
}
}
Step 3: Write the server (FactorialServer.java). It creates the object and binds it to the RMI registry.
import java.rmi.*;
import java.rmi.registry.*;
public class FactorialServer {
public static void main(String[] args) {
try {
LocateRegistry.createRegistry(1099);
Factorial obj = new FactorialImpl();
Naming.rebind("rmi://localhost:1099/FactService", obj);
System.out.println("Server ready");
} catch (Exception e) { e.printStackTrace(); }
}
}
Step 4: Write the client (FactorialClient.java). It looks up the remote object and calls the method.
import java.rmi.*;
import java.util.Scanner;
public class FactorialClient {
public static void main(String[] args) {
try {
Factorial f = (Factorial) Naming.lookup("rmi://localhost:1099/FactService");
Scanner sc = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = sc.nextInt();
System.out.println("Factorial of " + n + " = " + f.fact(n));
} catch (Exception e) { e.printStackTrace(); }
}
}
Step 5: Compile and run
javac *.java(for older JDKs also runrmic FactorialImplto generate the stub).- Start the server:
java FactorialServer(it also starts the registry on port 1099). - Start the client:
java FactorialClient, enter e.g. 5, and the output isFactorial of 5 = 120.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2077 · 10 marks
You are hired by a reputed software company which is going to design an application for “Movie Rental System”. Your responsibility is to design a schema named MRS and create a table named Movie(id, Tille, Genre, Language, Length). Write a program to design a GUI form to take input for this table and insert the data into table after clicking the OK button
Answer
Step 1: Create the schema and table (MySQL)
CREATE SCHEMA MRS;
USE MRS;
CREATE TABLE Movie (
id INT PRIMARY KEY,
Title VARCHAR(100),
Genre VARCHAR(50),
Language VARCHAR(30),
Length INT -- running time in minutes
);
Step 2: Swing form that inserts into the table. The MySQL Connector/J jar must be on the classpath. A PreparedStatement is used so the input is safely bound to the query.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class MovieForm extends JFrame implements ActionListener {
JTextField tId = new JTextField(), tTitle = new JTextField(),
tGenre = new JTextField(), tLang = new JTextField(),
tLength = new JTextField();
JButton ok = new JButton("OK");
MovieForm() {
setTitle("Movie Rental System");
setLayout(new GridLayout(6, 2, 5, 5));
add(new JLabel("ID")); add(tId);
add(new JLabel("Title")); add(tTitle);
add(new JLabel("Genre")); add(tGenre);
add(new JLabel("Language")); add(tLang);
add(new JLabel("Length")); add(tLength);
add(new JLabel("")); add(ok);
ok.addActionListener(this);
setSize(350, 250);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/MRS", "root", "password");
PreparedStatement ps = con.prepareStatement(
"INSERT INTO Movie(id, Title, Genre, Language, Length) VALUES (?,?,?,?,?)")) {
ps.setInt(1, Integer.parseInt(tId.getText().trim()));
ps.setString(2, tTitle.getText());
ps.setString(3, tGenre.getText());
ps.setString(4, tLang.getText());
ps.setInt(5, Integer.parseInt(tLength.getText().trim()));
ps.executeUpdate();
JOptionPane.showMessageDialog(this, "Record inserted");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());
}
}
public static void main(String[] args) { new MovieForm(); }
}
When the user fills in the five fields and clicks OK, actionPerformed opens a connection to the MRS schema and inserts one row into Movie.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2077 · 10 marks
Describe the responsibility of Serializable interface. Write a program to read an input string from the user and write the vowels of that string in VOWEL.TXT and consonants in CONSOLNANT.TXT
Answer
Responsibility of the Serializable interface
java.io.Serializable is a marker interface (it has no methods). A class that implements it tells the JVM that its objects may be converted into a byte stream (serialization) and rebuilt from it (deserialization). Its responsibilities are:
- It allows an object's state to be saved to a file or database, or sent across a network (for example in RMI arguments).
- It lets
ObjectOutputStream.writeObject()andObjectInputStream.readObject()work; otherwise aNotSerializableExceptionis thrown. - Fields marked
transientorstaticare not serialized, and aserialVersionUIDis used to check version compatibility during deserialization.
Program: write vowels and consonants into separate files
import java.io.*;
import java.util.Scanner;
public class SplitString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = sc.nextLine();
StringBuilder vowels = new StringBuilder();
StringBuilder cons = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isLetter(c)) {
if ("aeiouAEIOU".indexOf(c) >= 0) vowels.append(c);
else cons.append(c);
}
}
try (FileWriter fv = new FileWriter("VOWEL.TXT");
FileWriter fc = new FileWriter("CONSONANT.TXT")) {
fv.write(vowels.toString());
fc.write(cons.toString());
System.out.println("Files written.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
For the input Education Nepal, VOWEL.TXT contains Euaioea and CONSONANT.TXT contains dctnNpl. Non-letters such as spaces are skipped.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2077 · 5 marks
A non-empty array A of length n is called on array of all possibilities if it contains all numbers between 0 and A.length-1 inclusive. Write a method named is All Possibilities that accepts an integer array and returns 1 if the array is an array of all possiblities, otherwise it returns 0.
Answer
An array of length is an "array of all possibilities" if it contains every value from to exactly once, since slots must hold distinct values. The method marks the values seen in a boolean array and rejects any value outside the range or any repeat.
public class AllPossibilities {
public static int isAllPossibilities(int[] a) {
if (a == null || a.length == 0) return 0; // must be non-empty
boolean[] seen = new boolean[a.length];
for (int i = 0; i < a.length; i++) {
if (a[i] < 0 || a[i] >= a.length) return 0; // out of range
if (seen[a[i]]) return 0; // duplicate
seen[a[i]] = true;
}
return 1;
}
public static void main(String[] args) {
System.out.println(isAllPossibilities(new int[]{1, 2, 0, 3})); // 1
System.out.println(isAllPossibilities(new int[]{3, 0, 1, 3})); // 0
System.out.println(isAllPossibilities(new int[]{0, 5})); // 0
}
}
Time complexity is and extra space is . For all of 0, 1, 2, 3 appear, so the result is 1. For the value 3 repeats, so the result is 0.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2077 · 5 marks
Define event delegation model. Why do we need adapter class in event handling?
Answer
Event delegation model
In the delegation event model (Java 1.1 onwards) the handling of an event is delegated from the component that generates it to a separate object called a listener. It has three parts:
- Event source: the component (button, text field, window) that generates the event.
- Event object: an object such as
ActionEventorMouseEventthat describes what happened. - Event listener: an object that implements a listener interface (e.g.
ActionListener) and is registered with the source usingaddXxxListener().
When the event occurs, the source creates the event object and calls the appropriate method of every registered listener. Events are sent only to registered listeners, which makes handling efficient and separates the user-interface code from the application logic.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) { /* handle click */ }
});
Why adapter classes are needed
A listener interface such as WindowListener has seven abstract methods, and a class implementing it must define all of them even if only one (say windowClosing) is needed. An adapter class (WindowAdapter, MouseAdapter, KeyAdapter) provides empty implementations of all the methods of the interface. The programmer extends the adapter and overrides only the methods of interest, which reduces code and clutter.
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(0); }
});
Adapter classes exist only for listener interfaces with more than one method.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2077 · 5 marks
What is the task of Layout manager? Describe about default layout manager.
Answer
Task of a layout manager
A layout manager is an object that controls the size and position of the components inside a container. Instead of fixing pixel coordinates, the programmer adds components and the layout manager arranges them according to a rule, so the interface adapts when the window is resized, and works on different screen sizes and platforms. Each container has one layout manager, set with setLayout(). Common managers are FlowLayout, BorderLayout, GridLayout, CardLayout and GridBagLayout.
Default layout managers
Every container has a default layout manager if none is set:
| Container | Default layout |
|---|---|
Frame, JFrame (its content pane), Dialog | BorderLayout |
Panel, JPanel, Applet | FlowLayout |
- BorderLayout divides the container into five regions: North, South, East, West and Center. A component added without a region goes to the Center, and the Center takes all the space left over by the others.
- FlowLayout places components one after another from left to right in the order they were added, centered, and wraps to the next row when the row is full. Each component keeps its preferred size.
JFrame f = new JFrame();
f.add(new JButton("North"), BorderLayout.NORTH); // default BorderLayout
JPanel p = new JPanel(); // default FlowLayout
p.add(new JButton("A")); p.add(new JButton("B"));
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2077 · 5 marks
When does the finally block is mandatory in while handling exception? Describe with a suitable scenario.
Answer
The finally block is always executed after the try (and any catch) whether or not an exception occurs, and even when return, break or continue is used. It is mandatory (in practice) when a try block has no catch clause (a try must be followed by catch or finally), and, more importantly, whenever a resource must be released whatever happens, for example closing a file, a database connection or a socket, releasing a lock. Without it, an exception or early return would skip the cleanup code and leak the resource.
Scenario: reading a file
import java.io.*;
public class ReadFile {
public static void main(String[] args) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("data.txt"));
System.out.println(br.readLine());
int x = 10 / 0; // may throw an exception
} catch (IOException e) {
System.out.println("I/O problem: " + e.getMessage());
} finally {
try {
if (br != null) br.close(); // always release the file
System.out.println("File closed");
} catch (IOException e) { }
}
}
}
Here an ArithmeticException is not caught by the catch (IOException) clause, yet finally still runs and closes the file before the program terminates. Without the finally block the file handle would stay open. (Since Java 7 try-with-resources can close resources automatically, but finally is still needed for other cleanup.)
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2077 · 5 marks
Explain the life cycle of a servlet.
Answer
A servlet is a Java class that runs inside a web container (such as Tomcat) and handles HTTP requests. Its life cycle is controlled by the container through three methods of the javax.servlet.Servlet interface.
- Loading and instantiation: When the first request arrives (or at start-up if
load-on-startupis set) the container loads the servlet class and creates one instance. - Initialization,
init(ServletConfig config): Called exactly once, after the instance is created. It is used for one-time set-up such as opening a database connection or reading init parameters. The servlet cannot serve requests untilinit()completes. - Request handling,
service(ServletRequest req, ServletResponse res): Called for every client request, each in a separate thread of the same instance. InHttpServlet,service()dispatches todoGet(),doPost(), etc. depending on the HTTP method. - Destruction,
destroy(): Called once when the container removes the servlet (for example on shutdown or redeployment). It releases resources such as connections and threads. After this the instance is garbage collected.
Load class -> create instance -> init() -> service()/doGet()/doPost() (many times) -> destroy()
init() and destroy() are called once per life, while service() is called once per request.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2077 · 5 marks
What is the task of manifest file? Write the procedure to create it.
Answer
Task of the manifest file
A manifest file (META-INF/MANIFEST.MF) is a special file inside a JAR archive that holds metadata about the JAR as name-value pairs. Its tasks are:
- To specify the entry point with
Main-Class, so the JAR can be run withjava -jar app.jar. - To set the class path with
Class-Pathfor other JARs it depends on. - To hold version and vendor information, package sealing, and digital-signature data.
Procedure to create it
- Create a plain text file, e.g.
manifest.txt, containing:
Main-Class: MyApp
The last line must end with a newline, and there must be a space after the colon.
- Compile the classes:
javac MyApp.java. - Create the JAR with the manifest using the
moption:
jar cfm MyApp.jar manifest.txt MyApp.class
Here c creates the archive, f names the file, and m merges the given manifest. The tool puts it into META-INF/MANIFEST.MF and adds a Manifest-Version: 1.0 line.
- Run it:
java -jar MyApp.jar.
If the m option is omitted, jar creates a default manifest without Main-Class.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2077 · 5 marks
Why multiple inheritance is not allowed in Java using classes? Give an example.
Answer
Why multiple inheritance with classes is not allowed
Java does not allow a class to extend more than one class (class C extends A, B is an error). The reason is the diamond problem and the ambiguity it causes: if two superclasses define the same method (or field), the compiler and the JVM cannot decide which version the subclass should inherit. Allowing it would also complicate constructor chaining and the object layout. Java designers dropped it to keep the language simple and safe.
Example
class A {
void show() { System.out.println("A's show"); }
}
class B {
void show() { System.out.println("B's show"); }
}
// class C extends A, B { } // compile-time error
// C c = new C(); c.show(); // which show() should run, A's or B's?
If C extends A, B were allowed, c.show() would be ambiguous.
How Java achieves the effect: a class may implement many interfaces.
interface Printable { void print(); }
interface Showable { void show(); }
class C implements Printable, Showable {
public void print() { System.out.println("print"); }
public void show() { System.out.println("show"); }
}
Since an interface supplies only method signatures (and default methods must be explicitly resolved by the class), the implementing class provides the single body, so there is no ambiguity.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2077 · 5 marks
How forms can be created and processed using JSP? Make it clear with your own assumptions.
Answer
JSP (JavaServer Pages) lets Java code be embedded in an HTML page. A form is created with ordinary HTML <form> elements, and a JSP page reads the submitted values with the implicit object request and its getParameter() method. The name attribute of each input is the key used to retrieve its value.
Assumption: a login form with a username and a password, processed by login.jsp.
form.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
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<body>
<%
String user = request.getParameter("username");
String pass = request.getParameter("password");
if ("admin".equals(user) && "1234".equals(pass)) {
out.println("<h3>Welcome, " + user + "</h3>");
} else {
out.println("<h3>Invalid username or password</h3>");
}
%>
</body>
</html>
Working: the browser submits the data with POST, the container translates login.jsp into a servlet, the scriptlet reads the parameters through request, checks them (in a real application against a database with JDBC), and writes the result into the response with out. Checkboxes or multi-selects are read with getParameterValues(). The same page can also use session to remember the logged-in user.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2077 · 5 marks
Why synchronization in essential in multithreading? Describe.
Answer
Why synchronization is essential
In multithreading, several threads run concurrently and may access the same shared object or variable. If they read and modify it at the same time, the result depends on the order in which the threads happen to be scheduled. This is called a race condition and leads to inconsistent data. Synchronization ensures that only one thread at a time executes a critical section, so shared data stays consistent. It provides mutual exclusion (via the object's monitor/lock) and visibility of changes between threads.
Example without synchronization: two threads each execute count++ 1000 times. The operation is really read, add, write, so two threads can read the same old value and both write back the same new value, and the final count may be less than 2000.
Fix using a synchronized method
class Counter {
private int count = 0;
synchronized void increment() { count++; } // only one thread at a time
int get() { return count; }
}
public class Test {
public static void main(String[] args) throws Exception {
Counter c = new Counter();
Runnable r = () -> { for (int i = 0; i < 1000; i++) c.increment(); };
Thread t1 = new Thread(r), t2 = new Thread(r);
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println(c.get()); // always 2000
}
}
Ways to synchronize:
- A
synchronizedmethod locks the object (this) for its duration. - A
synchronized (obj) { ... }block locks only a section of code. - A
static synchronizedmethod locks the class.
A thread entering the block acquires the monitor, and other threads wanting it wait (blocked) until it is released. Inter-thread communication uses wait(), notify() and notifyAll(). Overuse can cause reduced performance and deadlock, so only the critical section should be synchronized.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2077 · 5 marks
Write short notes on:
a. JAVA beans and JAR file
b. MVC design pattern
Answer
a. JavaBeans and JAR file
JavaBeans are reusable software components written in Java that can be manipulated visually in a builder tool (such as an IDE). A class is a bean if it:
- is
publicand has a public no-argument constructor, - has private properties with public getter and setter methods (
getXxx()/setXxx(), andisXxx()for boolean), - implements
java.io.Serializableso its state can be saved, - optionally supports events through listeners (bound and constrained properties with
PropertyChangeListener).
public class Student implements java.io.Serializable {
private String name;
public Student() { }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
JAR (Java ARchive) file is a compressed archive (ZIP format) that packages many class files, resources, images and a manifest into one file for easy distribution and deployment. It is created with jar cf app.jar *.class and executable ones run with java -jar app.jar. Beans are normally packaged in JAR files together with a manifest that marks the bean classes (Java-Bean: True).
b. MVC design pattern
Model-View-Controller separates an application into three parts:
- Model: holds the data and business logic (e.g. a JavaBean or database access class). It is independent of the interface.
- View: the presentation of data to the user (e.g. JSP, HTML, Swing).
- Controller: receives user input, calls the model to update or fetch data, and selects the view to display (e.g. a servlet).
Flow in a web application: Browser request -> Controller servlet -> Model (database) -> Controller forwards the result to the View (JSP) -> response. Advantages are separation of concerns, easy maintenance, reuse of the model with several views, and parallel development by developers and designers.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 10 marks
Compare AWT with Swing. Write a GUI program using components to find sum and difference of two numbers. Use two text fields for giving input and a label for output. The program should display sum if user presses mouse and difference if user release mouse.
Answer
Comparison of AWT and Swing
| AWT | Swing |
|---|---|
Package java.awt | Package javax.swing |
| Heavyweight: each component uses a native peer of the operating system | Lightweight: components are drawn by Java itself (mostly pure Java) |
| Look and feel depends on the platform | Pluggable look and feel, the same on all platforms |
| Limited set of components | Richer set (JTable, JTree, JTabbedPane, etc.) |
| Does not follow MVC | Based on a modified MVC architecture |
| Faster for simple tasks but less flexible | Slightly slower but more powerful and flexible |
Components like Button, TextField | Components like JButton, JTextField |
Program: the sum is shown when the mouse is pressed and the difference when it is released. A MouseListener is added to the frame (and to the label so that clicks anywhere count).
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SumDiff extends JFrame {
JTextField t1 = new JTextField(8), t2 = new JTextField(8);
JLabel result = new JLabel("Result: ");
SumDiff() {
setTitle("Sum and Difference");
setLayout(new FlowLayout());
add(new JLabel("First:")); add(t1);
add(new JLabel("Second:")); add(t2);
add(result);
MouseAdapter ma = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
try {
double a = Double.parseDouble(t1.getText().trim());
double b = Double.parseDouble(t2.getText().trim());
result.setText("Sum = " + (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("Difference = " + (a - b));
} catch (NumberFormatException ex) {
result.setText("Enter valid numbers");
}
}
};
getContentPane().addMouseListener(ma);
result.addMouseListener(ma);
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(SumDiff::new);
}
}
With inputs 8 and 3, pressing the mouse on the frame shows Sum = 11.0, and releasing it shows Difference = 5.0.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 10 marks
Explain life-cycle of servlet in detail. Create a simple servlet that reads and displays data from HTML form. Assume form with two fields username and password.
Answer
Life cycle of a servlet
The web container manages a servlet through the following stages.
- Loading and instantiation: the container loads the servlet class on the first request (or at start-up if
load-on-startupis given) and creates a single instance using the no-argument constructor. - Initialization,
init(ServletConfig): called once after instantiation, for one-time set-up such as opening database connections or reading initialization parameters. The servlet cannot serve requests until it completes successfully. - Request processing,
service(ServletRequest, ServletResponse): called for every request. The container creates a new thread for each request, using the same instance. InHttpServlet,service()callsdoGet(),doPost(),doPut()etc. according to the HTTP method. Request and response objects are passed in. - Destruction,
destroy(): called once when the container takes the servlet out of service (shutdown, undeploy or idle). The servlet releases resources, then becomes eligible for garbage collection.
Load -> instantiate -> init() [once] -> service() [per request] -> destroy() [once]
Servlet that reads form data
login.html
<html>
<body>
<form action="LoginServlet" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
LoginServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String user = request.getParameter("username");
String pass = request.getParameter("password");
out.println("<html><body>");
out.println("<h3>Data received from the form</h3>");
out.println("Username: " + user + "<br>");
out.println("Password: " + pass);
out.println("</body></html>");
}
}
web.xml mapping
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
(With Servlet 3.0 the annotation @WebServlet("/LoginServlet") can replace the XML.) When the form is submitted, the container calls doPost(), which reads both fields with getParameter() and writes them to the browser. In a real application the password would never be echoed back.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 10 marks
Explain RMI architecture layers in detail. Write a Java programs using RMI to find product of two numbers.
Answer
RMI architecture layers
RMI has three layers between the client and server applications, each independent of the others.
- Stub and skeleton layer (proxy layer): The stub is the client-side proxy that implements the remote interface. It marshals the method name and arguments (using object serialization) and passes them to the layer below, then unmarshals the result. The skeleton on the server receives the call, unmarshals the arguments, calls the real object and marshals the return value. (Skeletons are no longer needed from Java 1.2 onwards, as the runtime uses reflection.)
- Remote Reference Layer (RRL): It interprets and manages references to remote objects. It decides the invocation semantics (for example unicast point-to-point), and handles the connection to the remote object, using the
RemoteRefinterface. It receives a marshalled stream from the stub and passes it down. - Transport layer: It sets up and manages the actual network connection (TCP/IP sockets) between the two JVMs, tracks remote objects, and dispatches incoming calls. It uses the default JRMP (Java Remote Method Protocol) protocol.
In addition, the RMI registry is a naming service on the server where remote objects are bound by name (bind/rebind) and from which clients obtain stubs with lookup.
Flow: Client -> Stub -> RRL -> Transport -> network -> Transport -> RRL -> Skeleton -> Remote object, and back for the result.
Program: product of two numbers using RMI
Product.java (remote interface)
import java.rmi.*;
public interface Product extends Remote {
int multiply(int a, int b) throws RemoteException;
}
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;
}
}
ProductServer.java
import java.rmi.*;
import java.rmi.registry.*;
public class ProductServer {
public static void main(String[] args) {
try {
LocateRegistry.createRegistry(1099);
Naming.rebind("rmi://localhost:1099/ProductService", new ProductImpl());
System.out.println("Server started");
} catch (Exception e) { e.printStackTrace(); }
}
}
ProductClient.java
import java.rmi.*;
public class ProductClient {
public static void main(String[] args) {
try {
Product p = (Product) Naming.lookup("rmi://localhost:1099/ProductService");
System.out.println("Product = " + p.multiply(6, 7)); // 42
} catch (Exception e) { e.printStackTrace(); }
}
}
Compile with javac *.java, run java ProductServer and then java ProductClient. The output is Product = 42.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
What is package? How can you create your own package in Java? Explain with example.
Answer
Package
A package is a namespace that groups related classes, interfaces and sub-packages (for example java.util, java.io). Packages avoid name conflicts, make classes easy to locate and reuse, and provide access protection (default and protected members are accessible within the package). A package corresponds to a directory structure on disk.
Creating your own package
- Write the
packagestatement as the first statement of the source file. - Save the file in a directory with the same name as the package.
- Compile with the
-doption so the class file is placed in the right folder. - Import the package in another program and use it.
File mypack/Calculator.java
package mypack;
public class Calculator {
public int add(int a, int b) { return a + b; }
public int sub(int a, int b) { return a - b; }
}
Compile: javac -d . Calculator.java (this creates the folder mypack containing Calculator.class).
File TestPack.java (uses the package)
import mypack.Calculator;
public class TestPack {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(10, 5)); // 15
System.out.println(c.sub(10, 5)); // 5
}
}
Compile and run: javac TestPack.java and java TestPack. If the package folder is elsewhere, its parent directory must be on the classpath (-cp). The class and its used methods must be public to be reachable from outside the package.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Why do we need swing components ? Explain the uses of check boxes and radio buttons in GUI programming.
Answer
Why Swing components are needed
AWT components depend on the native operating system and so look and behave differently on each platform, and the set of components is small. Swing components (javax.swing) solve this because they:
- are lightweight and written in Java, so they look the same on all platforms,
- offer a pluggable look and feel,
- provide richer components (
JTable,JTree,JTabbedPane,JScrollPane,JColorChooser), - support features like borders, tooltips, icons on components, and double buffering,
- follow a model-view approach, which allows custom data models.
Check boxes (JCheckBox)
A check box is a two-state (selected or not) button, used when the user may choose any number of options independently, e.g. choosing hobbies or subjects, or turning a setting on or off. Each box works independently. The state is read with isSelected(), and ItemListener/ActionListener handles changes.
Radio buttons (JRadioButton)
Radio buttons are used when the user must choose exactly one option from a group, e.g. gender or payment method. They are placed in a ButtonGroup, which makes the buttons mutually exclusive: selecting one deselects the others.
JCheckBox c1 = new JCheckBox("Music"), c2 = new JCheckBox("Sports");
JRadioButton m = new JRadioButton("Male"), f = new JRadioButton("Female");
ButtonGroup g = new ButtonGroup();
g.add(m); g.add(f);
Thus check boxes give multiple selection and radio buttons give single selection in forms and dialogs.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
How can we use listener interface to handle events? Compare listener interface with adapter class.
Answer
Using listener interfaces to handle events
Java uses the delegation event model. A listener interface declares the methods that are called when a particular kind of event occurs. To handle an event:
- Create a class that implements the proper listener interface (e.g.
ActionListener,MouseListener,KeyListener,WindowListener) and defines all its methods. - Create an object of that class and register it with the source component using
addXxxListener(). - When the event occurs, the source calls the listener's method with an event object, which the method uses to find out what happened (
e.getSource(),e.getActionCommand()).
class MyFrame extends JFrame implements ActionListener {
JButton b = new JButton("Click");
MyFrame() {
add(b);
b.addActionListener(this); // register the listener
setSize(200, 100); setVisible(true);
}
public void actionPerformed(ActionEvent e) {
b.setText("Clicked"); // event handling code
}
}
Listener interface versus adapter class
| Listener interface | Adapter class |
|---|---|
| An interface; the class must implement all its methods | A class with empty implementations of all methods; override only the needed ones |
Class uses implements | Class uses extends |
| A class can implement many listener interfaces | Because Java has single inheritance, a class that already extends another class (e.g. JFrame) cannot extend an adapter (usually an inner/anonymous class is used) |
Needed for interfaces with a single method, e.g. ActionListener | Exists only for interfaces with more than one method, e.g. MouseAdapter, WindowAdapter, KeyAdapter |
| More code when only one method is wanted | Less code, since unused methods are not written |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
What is row set? Explain cached row set in detail.
Answer
RowSet
A RowSet (package javax.sql) is an object that holds tabular data, and it extends ResultSet. It is a JavaBeans component: it has properties (url, username, password, command) and supports event notification. Compared to a plain ResultSet, a RowSet is easier to use because it can create its own connection and run its own command, and it can be scrollable and updatable by default. There are two kinds:
- Connected RowSet: keeps the database connection open, e.g.
JdbcRowSet. - Disconnected RowSet: works without keeping the connection open, e.g.
CachedRowSet,WebRowSet,FilteredRowSet,JoinRowSet.
CachedRowSet
CachedRowSet is a disconnected, serializable rowset that caches its rows in memory. It connects to the database only to fill itself and to write changes back, so it does not need a JDBC connection while the data is being used.
Main features:
- It is scrollable and updatable even if the underlying driver does not support this.
- It can be serialized and sent over a network to a client (e.g. a thin client or a mobile device) without a driver.
- Changes made (insert, update, delete) are tracked in memory and written to the database later by
acceptChanges(), which reconnects and checks for conflicts. - It uses less database resources because connections are held briefly.
Limitation: large data sets consume memory, and there may be update conflicts with other users.
import javax.sql.rowset.*;
CachedRowSet crs = RowSetProvider.newFactory().createCachedRowSet();
crs.setUrl("jdbc:mysql://localhost:3306/college");
crs.setUsername("root");
crs.setPassword("password");
crs.setCommand("SELECT id, name FROM student");
crs.execute(); // connects, fills the rowset, disconnects
while (crs.next())
System.out.println(crs.getInt("id") + " " + crs.getString("name"));
crs.absolute(1);
crs.updateString("name", "Ram");
crs.updateRow();
crs.acceptChanges(); // reconnects and writes changes back
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
What is Java Mail API ? How can you use this API to send email messages?
Answer
Java Mail API
The JavaMail API (javax.mail) is a platform-independent, protocol-independent framework for building mail and messaging applications in Java. It provides classes to send, receive and manage e-mail using protocols such as SMTP (sending), POP3 and IMAP (receiving). It needs the javax.mail jar (mail.jar / jakarta.mail) and the JavaBeans Activation Framework. The main classes are Session, Message (MimeMessage), Address (InternetAddress), Transport, Store and Folder.
Steps to send an email
- Set the properties of the mail server (host, port, authentication, TLS).
- Get a
Sessionobject (with anAuthenticatorsupplying username and password). - Create a
MimeMessageand set the sender, recipient, subject and body. - Send it with
Transport.send().
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendMail {
public static void main(String[] args) {
final String user = "sender@gmail.com";
final String pass = "app-password";
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass);
}
});
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(user));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("receiver@example.com"));
msg.setSubject("Test mail");
msg.setText("Hello from JavaMail API");
Transport.send(msg);
System.out.println("Mail sent");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Compare JavaFX with swing. Explain HBox and BBox layouts of JavaFX.
Answer
JavaFX versus Swing
| Swing | JavaFX |
|---|---|
Older GUI toolkit (javax.swing), part of the JDK till Java 8 | Newer toolkit (javafx.*) meant to replace Swing; separate module since Java 11 |
Event dispatch thread, JFrame is the main window | Application class with Stage and Scene (scene graph) |
Layouts via layout managers (FlowLayout, etc.) | Layout panes (HBox, VBox, BorderPane, GridPane, FlowPane) |
| Styling through look and feel | Styling with CSS and FXML (XML layout) |
| Limited graphics, animation and multimedia | Built-in animation, effects, 2D/3D graphics, audio/video, charts |
| Hardware acceleration limited | Hardware accelerated graphics pipeline |
HBox layout
HBox arranges its children in a single horizontal row, from left to right in the order added. Useful properties are setSpacing() (gap between children), setPadding(), setAlignment(), and HBox.setHgrow() (children growing to fill space).
VBox layout (the "BBox" in the question is read as VBox)
VBox arranges its children in a single vertical column, from top to bottom, with the same properties.
HBox hbox = new HBox(10); // spacing 10
hbox.getChildren().addAll(new Button("OK"), new Button("Cancel"));
VBox vbox = new VBox(10);
vbox.getChildren().addAll(new Label("Name"), new TextField());
Scene scene = new Scene(new VBox(10, hbox, vbox), 300, 150);
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
What is servlet? Write a simple JSP file to display “Tribhuwan University” five times.
Answer
Servlet
A servlet is a Java class that runs on a web server (inside a servlet container such as Tomcat) and extends the server's capabilities by handling client requests, usually HTTP, and generating dynamic responses. It extends HttpServlet and overrides doGet() and doPost(). Servlets are platform independent, efficient (one instance with a thread per request), and secure.
JSP to display "Tribhuwan University" five times
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<head><title>Display</title></head>
<body>
<%
for (int i = 1; i <= 5; i++) {
%>
<p>Tribhuwan University</p>
<%
}
%>
</body>
</html>
The scriptlet contains a for loop that runs five times, and each pass outputs the HTML paragraph. An alternative is out.println("Tribhuwan University<br>") inside the loop.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Why CORBA is important? Compare CORBA with RMI.
Answer
Importance of CORBA
CORBA (Common Object Request Broker Architecture) is a standard of the Object Management Group (OMG) that lets objects written in different programming languages and running on different platforms communicate over a network. It is important because:
- It is language independent: interfaces are described in IDL (Interface Definition Language) and mapped to Java, C++, Python, etc.
- It is platform independent and supports heterogeneous distributed systems and the integration of legacy systems.
- The ORB (Object Request Broker) provides location transparency by finding and invoking objects, and handles marshalling.
- It provides services such as naming, events, transactions and security.
- Its protocol IIOP lets ORBs from different vendors interoperate.
CORBA versus RMI
| CORBA | RMI |
|---|---|
| Language independent (many languages) | Java only (Java to Java) |
| Interfaces defined in IDL | Interfaces defined as Java interfaces extending Remote |
| Uses an ORB and the IIOP protocol | Uses JRMP (and RMI-IIOP optionally) |
Needs an IDL compiler (idlj) and a naming service (tnameserv/orbd) | Needs the RMI registry |
| Parameters passed are limited to IDL types | Can pass any serializable Java object by value, and download code dynamically |
| More complex to develop | Simpler to develop |
| Supports many object services | Fewer built-in services |
| Suited to heterogeneous systems | Suited to pure Java systems |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Write short notes on:
a. JDBC drivers
b. Java server pages
Answer
a. JDBC drivers
A JDBC driver is a set of classes that lets a Java program talk to a particular database by translating JDBC calls into the database's protocol. It is loaded with Class.forName() (automatically from JDBC 4) and used by DriverManager. There are four types:
- Type 1, JDBC-ODBC bridge driver: converts JDBC calls into ODBC calls. It needs an ODBC driver installed on the client, is slow and platform dependent, and was removed in Java 8.
- Type 2, native-API driver: converts JDBC calls into the database's native client library calls (e.g. Oracle OCI). It is faster than Type 1 but needs native libraries on the client and is not portable.
- Type 3, network protocol (middleware) driver: sends JDBC calls to a middleware server in a database-independent protocol, and the server converts them for the database. It is pure Java on the client and flexible, but needs a middle tier.
- Type 4, thin driver (native protocol, pure Java): converts JDBC calls directly into the database's network protocol. It is fast, portable and needs no client installation; it is the most widely used (e.g. MySQL Connector/J).
b. Java Server Pages (JSP)
JSP is a server-side technology for creating dynamic web pages by embedding Java code in HTML. A JSP file is translated by the container into a servlet on the first request, compiled, and then executed, so it has the same performance as a servlet but is easier to write for presentation. JSP elements are:
- Directives:
<%@ page ... %>,<%@ include ... %>,<%@ taglib ... %> - Scripting elements: declarations
<%! %>, scriptlets<% %>, expressions<%= %> - Actions:
<jsp:include>,<jsp:forward>,<jsp:useBean> - Implicit objects:
request,response,out,session,application,config,pageContext,page,exception
Advantages: separates presentation from business logic, easy to maintain, can use JavaBeans and custom tags (JSTL), and has all the power of Java.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
Explain feature of object-oriented programming. Create a class Distance with private variables feet of type integer and inches of type floating point. Use suitable constructor, and methods for adding and comparing two distance objects. [Hint: 1 feet = 12 inches]
Answer
Features of object-oriented programming
- Class and object: A class is a blueprint that bundles data (fields) and behaviour (methods); an object is a runtime instance of it.
- Encapsulation: Data members are kept
privateand exposed only through public methods, so the internal state is protected from misuse. - Abstraction: Only the essential features are shown to the user (abstract classes and interfaces), hiding implementation details.
- Inheritance: A subclass acquires the fields and methods of a superclass (
extends), which gives code reuse and an "is-a" hierarchy. - Polymorphism: One name, many forms: compile-time (method overloading) and run-time (method overriding with dynamic dispatch).
- Message passing / dynamic binding: Objects communicate by invoking each other's methods.
Distance class
public class Distance {
private int feet;
private float inches;
public Distance() {
this(0, 0f);
}
public Distance(int feet, float inches) {
this.feet = feet;
this.inches = inches;
normalize();
}
// convert inches >= 12 into feet
private void normalize() {
while (inches >= 12) {
inches -= 12;
feet++;
}
}
// total length in inches, used for comparison
private float toInches() {
return feet * 12 + inches;
}
// adds two distances and returns a new Distance
public Distance add(Distance d) {
return new Distance(this.feet + d.feet, this.inches + d.inches);
}
// returns -1, 0 or 1 as this distance is less than, equal to or greater than d
public int compare(Distance d) {
float a = this.toInches(), b = d.toInches();
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
public void display() {
System.out.println(feet + " feet " + inches + " inches");
}
public static void main(String[] args) {
Distance d1 = new Distance(5, 8.5f);
Distance d2 = new Distance(3, 6.5f);
Distance sum = d1.add(d2); // 8 ft 15 in -> 9 ft 3 in
sum.display();
int r = d1.compare(d2);
if (r > 0) System.out.println("d1 is greater");
else if (r < 0) System.out.println("d2 is greater");
else System.out.println("Both are equal");
}
}
Check: , and since it is normalised to . Also and , so d1 is greater.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
Why do we need layout management? Explain any two layout managers with example. Write a simple GUI program that displays “Hello World” in a text field. The program should display output if user clicks a button.
Answer
Need for layout management
A container holds many components. Hard-coding their pixel positions breaks when the window is resized, when the screen resolution changes or when the program runs on a different platform or font. A layout manager decides the position and size of each component automatically, so the GUI stays consistent and adapts to resizing. It is attached with setLayout(LayoutManager).
Two layout managers
- FlowLayout: Components are placed left to right in the order they are added; when a row is full, a new row starts. Alignment is centre by default (LEFT, RIGHT, CENTER). It is the default layout of
JPanel.
panel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 5));
panel.add(new JButton("One"));
panel.add(new JButton("Two"));
- BorderLayout: The container is divided into five regions: NORTH, SOUTH, EAST, WEST and CENTER. Each region holds one component; CENTER takes the remaining space. It is the default layout of
JFrame's content pane.
frame.setLayout(new BorderLayout());
frame.add(new JButton("North"), BorderLayout.NORTH);
frame.add(new JTextArea(), BorderLayout.CENTER);
Program: show "Hello World" in a text field on a button click
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class HelloGUI extends JFrame implements ActionListener {
private JTextField tf;
private JButton btn;
public HelloGUI() {
setTitle("Hello");
setLayout(new FlowLayout());
tf = new JTextField(15);
btn = new JButton("Show");
add(tf);
add(btn);
btn.addActionListener(this);
setSize(300, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
tf.setText("Hello World");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(HelloGUI::new);
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
Define JSP. What are the benefits of using JSP? Create a HTML file with two text fields to first name and last name. Create a JSP file that reads data from the HTML form and display full name.
Answer
JSP (JavaServer Pages)
JSP is a server-side technology that lets HTML pages embed Java code using scriptlets (<% %>), expressions (<%= %>), declarations (<%! %>), directives (<%@ %>) and tags. The container translates a JSP page into a servlet, compiles it once, and then serves requests from it.
Benefits of JSP
- Separates presentation (HTML) from business logic, so designers and programmers can work independently.
- Easier to write than servlets, since there are no
out.println()calls for every HTML line. - Automatic translation and compilation; changes to a page are picked up without manual recompilation.
- Implicit objects (
request,response,session, ...) and standard tags (JSTL, EL) reduce code. - Full access to the Java platform (JDBC, JavaBeans, etc.), platform independent and portable.
- Better performance than CGI, because the compiled servlet stays in memory.
form.html
<html>
<body>
<form action="fullname.jsp" method="post">
First name: <input type="text" name="fname"><br><br>
Last name: <input type="text" name="lname"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
fullname.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<body>
<%
String first = request.getParameter("fname");
String last = request.getParameter("lname");
%>
<h3>Full name: <%= first + " " + last %></h3>
</body>
</html>
The form sends the two fields to fullname.jsp; request.getParameter() reads them and the expression prints the concatenated full name.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
What is multithreading? How can you create multithreaded program in Java? Explain.
Answer
Multithreading
Multithreading is the ability of a program to run two or more threads (independent paths of execution) concurrently within one process. Threads share the same memory but each has its own stack and program counter. It improves CPU utilisation and responsiveness, for example one thread handles the GUI while another downloads a file.
Creating threads in Java
1. Extending the Thread class: override run() and call start().
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 3; i++)
System.out.println(getName() + " : " + i);
}
}
public class Test1 {
public static void main(String[] args) {
new MyThread().start();
new MyThread().start();
}
}
2. Implementing the Runnable interface: implement run(), pass the object to a Thread constructor and call start(). This is preferred because the class can still extend another class.
class Task implements Runnable {
public void run() {
System.out.println("Running in " + Thread.currentThread().getName());
}
}
public class Test2 {
public static void main(String[] args) {
Thread t = new Thread(new Task());
t.start();
}
}
start() creates a new call stack and invokes run(); calling run() directly would execute it in the current thread. A thread passes through the states new, runnable, running, blocked/waiting and terminated.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
What is grid layout? Compare grid layout with grid bag layout.
Answer
Grid layout
GridLayout arranges components in a rectangular grid of equal-sized cells, filling row by row from left to right. The number of rows and columns is given in the constructor: new GridLayout(rows, cols, hgap, vgap). Every component is stretched to fill its cell. It is suitable for calculators, keypads and boards.
setLayout(new GridLayout(2, 3, 5, 5));
for (int i = 1; i <= 6; i++) add(new JButton("B" + i));
Comparison of GridLayout and GridBagLayout
| Basis | GridLayout | GridBagLayout |
|---|---|---|
| Cell size | All cells have equal size | Rows and columns can have different sizes |
| Spanning | A component occupies exactly one cell | A component can span several rows/columns (gridwidth, gridheight) |
| Control | Only rows, columns and gaps | GridBagConstraints gives gridx/gridy, weightx/weighty, fill, anchor, insets |
| Complexity | Very simple | Flexible but complex and verbose |
| Resizing | Components grow equally | Extra space is shared according to weights |
| Use | Uniform layouts such as keypads | Complex forms with varied components |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Why do we need event handling? Explain the use of action event with example.
Answer
Need for event handling
A GUI is event driven: the program must react to what the user does, such as clicking a button, typing a key, moving the mouse or choosing a menu item. Event handling provides the mechanism to detect these actions (events generated by event sources) and to run code in response. Without it the GUI would only be a static picture. Java uses the delegation event model: a source component registers a listener, and when the event occurs the listener's handler method is called with an event object.
ActionEvent
An ActionEvent is generated when a button is clicked, a menu item is selected, Enter is pressed in a text field or an item in a list is double-clicked. It is handled by an ActionListener, which has one method, actionPerformed(ActionEvent e). Useful methods are e.getSource() and e.getActionCommand().
import javax.swing.*;
import java.awt.event.*;
public class ActionDemo extends JFrame implements ActionListener {
JButton b = new JButton("Click me");
JLabel l = new JLabel("Waiting...");
ActionDemo() {
setLayout(new java.awt.FlowLayout());
add(b); add(l);
b.addActionListener(this); // register the listener
setSize(250, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
l.setText("Button clicked");
}
public static void main(String[] a) { new ActionDemo(); }
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Explain JDBC driver types. What is scrollable result set?
Answer
JDBC driver types
A JDBC driver lets a Java program talk to a database. There are four types.
- Type 1: JDBC-ODBC bridge driver. Translates JDBC calls into ODBC calls, which the native ODBC driver passes to the database. It needs ODBC installed on the client, is slow and platform dependent. It was removed in Java 8.
- Type 2: Native-API (partly Java) driver. Converts JDBC calls into the database vendor's native client library calls (for example Oracle OCI). It is faster than Type 1 but needs native libraries on each client.
- Type 3: Network-protocol (middleware) driver. JDBC calls are sent to a middleware server in a database-independent protocol, and the server translates them to the database protocol. It is pure Java on the client and flexible, but needs an extra server tier.
- Type 4: Thin (pure Java) driver. Converts JDBC calls directly into the database's own network protocol. It needs no native code or middleware, is portable and fast, and is the most commonly used (for example MySQL Connector/J).
Scrollable result set
By default a ResultSet is forward-only. A scrollable result set can move both forward and backward and jump to an absolute or relative row. It is created by giving the type when making the statement:
Statement st = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = st.executeQuery("SELECT * FROM student");
rs.last(); // go to the last row
rs.previous(); // move backward
rs.absolute(2); // go to row 2
rs.relative(-1); // one row back
rs.first();
TYPE_SCROLL_INSENSITIVE does not reflect changes made to the database by others after the result set was opened; TYPE_SCROLL_SENSITIVE does.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Write Java program that send messages with each other using TCP socket.
Answer
Two-way messaging using TCP sockets
TCP gives a reliable connection. The server creates a ServerSocket and waits with accept(); the client creates a Socket to the server's address and port. Both sides then use the socket's input and output streams. The programs below let the client and server exchange messages until either one types "exit".
Server.java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(5000);
System.out.println("Waiting for client...");
Socket s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
String msg;
while ((msg = in.readLine()) != null) {
System.out.println("Client: " + msg);
if (msg.equalsIgnoreCase("exit")) break;
System.out.print("Server: ");
String reply = kb.readLine();
out.println(reply);
if (reply.equalsIgnoreCase("exit")) break;
}
s.close();
ss.close();
}
}
Client.java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost", 5000);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
String msg;
while (true) {
System.out.print("Client: ");
msg = kb.readLine();
out.println(msg);
if (msg.equalsIgnoreCase("exit")) break;
String reply = in.readLine();
if (reply == null || reply.equalsIgnoreCase("exit")) break;
System.out.println("Server: " + reply);
}
s.close();
}
}
Run the server first, then the client.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
What is JavaFX? Compare it with swing. Explain FlowPane layout of JavaFX.
Answer
JavaFX
JavaFX is the modern Java platform for building rich desktop and mobile client applications. It uses a scene graph (a Stage holds a Scene, which holds nodes), supports FXML for describing the UI, CSS styling, animation, effects, media, 2D/3D graphics and hardware-accelerated rendering. Applications extend javafx.application.Application and override start(Stage).
Comparison with Swing
| Swing | JavaFX |
|---|---|
| Older toolkit, part of the JDK until Java 8 and now in maintenance mode | Modern toolkit, successor of Swing (separate module since Java 11) |
| Event-dispatch thread, components drawn with Java2D | Scene graph with a GPU-accelerated pipeline |
| Look and feel is set through pluggable L&F | Styled with CSS |
| UI built in code only | UI can be declared in FXML and designed with Scene Builder |
| Limited animation and media support | Built-in animation, effects, charts, media |
| Layouts: FlowLayout, BorderLayout, etc. | Layout panes: HBox, VBox, FlowPane, BorderPane, GridPane, etc. |
FlowPane layout
FlowPane lays out its children in a row (horizontal orientation, the default) or a column (vertical orientation) and wraps them to the next row or column when the available width or height is exceeded. Wrapping is controlled by setPrefWrapLength(). Gaps are set by setHgap() and setVgap(), and alignment by setAlignment().
FlowPane pane = new FlowPane(10, 10); // hgap, vgap
pane.setPadding(new Insets(10));
pane.setPrefWrapLength(200);
for (int i = 1; i <= 6; i++)
pane.getChildren().add(new Button("Btn " + i));
Scene scene = new Scene(pane, 300, 150);
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Compare JSP with servlet. What are different implicit objects in JSP?
Answer
JSP versus Servlet
| Servlet | JSP |
|---|---|
Java class with HTML written through out.println() | HTML page with embedded Java |
| Best for control and business logic | Best for presentation |
| Must be compiled and deployed manually | Translated to a servlet and compiled automatically by the container |
| Harder to maintain for page design | Easy for web designers |
Configured in web.xml or annotations | No mapping needed |
| Implicit objects must be obtained by hand | Implicit objects available directly |
| Faster on first request | Slower on first request (translation), then similar |
JSP implicit objects
These are objects created automatically by the container and available in scriptlets without declaration.
request(HttpServletRequest): holds client request data and parameters.response(HttpServletResponse): used to send the response to the client.out(JspWriter): writes output to the response.session(HttpSession): stores per-user data across requests.application(ServletContext): data shared by the whole web application.config(ServletConfig): initialisation parameters of the page.pageContext(PageContext): access to all scopes and other implicit objects.page(Object): reference to the generated servlet instance (this).exception(Throwable): available only in error pages (isErrorPage="true").
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Write short notes on:
- Final class
- Result set
Answer
1. Final class
A class declared with the keyword final cannot be extended (inherited). It is used to prevent subclassing for security or to keep behaviour fixed and immutable, as in String, Integer and the other wrapper classes.
final class Account {
void show() { System.out.println("Account"); }
}
// class Saving extends Account { } // compile-time error
Related uses of final: a final method cannot be overridden, and a final variable cannot be reassigned after initialisation. All methods of a final class are implicitly final.
2. ResultSet
java.sql.ResultSet represents the table of data returned by executing a SQL query with Statement.executeQuery(). It keeps a cursor positioned before the first row; next() moves the cursor to the next row and returns false when there are no more. Column values are read with getter methods such as getInt(), getString() and getDouble() by column index (starting at 1) or by column name.
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT id, name FROM student");
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
rs.close();
Result sets may be forward-only, scrollable, and read-only or updatable, depending on the type and concurrency given when the statement is created.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 10 marks
Why do we need to synchronize the thread? Justify with an example. An array with an odd number of elements is said to be centered if all elements (except the middle one) are strictly greater than the value of the middle element. Note that only arrays with an odd number of elements have a middle element. Write a function that accepts an integer array and returns 1 if it is a centered array, otherwise it returns 0.
Answer
Why thread synchronization is needed
Threads of one process share the same heap objects. When two or more threads read and modify a shared resource at the same time, the result depends on the order in which they are scheduled (a race condition) and data can become inconsistent. Synchronization allows only one thread at a time to execute a critical section, using the object's monitor lock (synchronized method or block), so the shared data stays correct.
Example: two threads withdraw from the same account.
class Account {
private int balance = 1000;
// without synchronized, both threads may pass the check before either deducts
synchronized void withdraw(int amt) {
if (balance >= amt) {
balance -= amt;
System.out.println(Thread.currentThread().getName()
+ " withdrew " + amt + ", left " + balance);
} else {
System.out.println(Thread.currentThread().getName() + ": insufficient balance");
}
}
}
public class SyncDemo {
public static void main(String[] args) {
Account acc = new Account();
Runnable r = () -> acc.withdraw(700);
new Thread(r, "T1").start();
new Thread(r, "T2").start();
}
}
Without synchronized, both threads could see balance 1000, pass the test and leave a balance of . With it, one thread withdraws (balance 300) and the other is correctly refused.
Centered array
An array is centered if its length is odd and every element other than the middle one (index ) is strictly greater than the middle element.
public static int isCentered(int[] a) {
int n = a.length;
if (n % 2 == 0) return 0; // no middle element (also covers empty array)
int mid = a[n / 2];
for (int i = 0; i < n; i++) {
if (i != n / 2 && a[i] <= mid) return 0;
}
return 1;
}
Check: {5, 3, 3, 4, 3, 3, 5} has , middle , and the elements 5, 3, 3, 3, 3, 5 are not all greater than 4, so the result is 0. {5, 7, 2, 9, 8} has middle 2 and all others are greater, so the result is 1. A one-element array returns 1.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 10 marks
How does JSP differ from Servlet and show the life cycle of Servlet? How do you create and read the cookies and session using JSP? Illustrate with an example.
Answer
JSP versus Servlet
| Servlet | JSP |
|---|---|
Java code containing HTML in out.println() | HTML containing Java code |
| Suited to logic and control (controller) | Suited to presentation (view) |
| Compiled and deployed manually | Translated to a servlet and compiled automatically |
Needs mapping in web.xml or @WebServlet | Accessed directly by file name |
| Implicit objects must be obtained explicitly | Implicit objects are built in |
| Harder to maintain for page layout | Easy to maintain, designer friendly |
Life cycle of a servlet
The container manages the life cycle through three methods of javax.servlet.Servlet:
- Loading and instantiation: the container loads the class and creates one instance, on first request or at start-up.
init(ServletConfig): called once to initialise the servlet (open connections, read parameters).service(request, response): called for each request, in a separate thread.HttpServletdispatches it todoGet(),doPost()and so on.destroy(): called once when the servlet is removed or the container shuts down, to release resources. The instance is then garbage collected.
A JSP follows the same cycle after translation: translation, compilation, jspInit(), _jspService() for each request, and jspDestroy().
Cookies and session in JSP
Cookie is a small piece of data stored in the browser; it is created with new Cookie(name, value) and added with response.addCookie(), and read with request.getCookies().
Session keeps data on the server for one user across requests, identified by a session id; it is accessed through the implicit object session with setAttribute() and getAttribute().
setdata.jsp
<%@ page language="java" %>
<%
String user = request.getParameter("user");
if (user == null) user = "guest";
// create a cookie, valid for one hour
Cookie c = new Cookie("username", user);
c.setMaxAge(60 * 60);
response.addCookie(c);
// store in session
session.setAttribute("loginUser", user);
%>
<html><body>
Cookie and session created for <%= user %>.
<a href="getdata.jsp">View</a>
</body></html>
getdata.jsp
<%@ page language="java" %>
<html><body>
<%
String fromCookie = "not found";
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie c : cookies) {
if (c.getName().equals("username")) fromCookie = c.getValue();
}
}
String fromSession = (String) session.getAttribute("loginUser");
%>
Cookie value: <%= fromCookie %><br>
Session value: <%= fromSession %>
</body></html>
Call setdata.jsp?user=Ram; then getdata.jsp prints Ram for both the cookie and the session.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 10 marks
Describe any two types of Layout manager. Using swing components, design a form with three buttons with captions “RED,” “BLUE,” and “GREEN,” respectively. Then write a program to handle the event such that when the user clicks the button, the color of that button will be the same as its caption.
Answer
Two layout managers
- FlowLayout: Places components one after another from left to right and wraps to a new row when the row is full. Alignment can be LEFT, CENTER or RIGHT, with horizontal and vertical gaps. It is the default layout of
JPanel. - BorderLayout: Divides the container into NORTH, SOUTH, EAST, WEST and CENTER regions, each holding one component; CENTER receives the remaining space. It is the default layout of
JFrame.
(GridLayout, which arranges equal-sized cells in rows and columns, is another common one.)
Program: colour buttons
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ColorButtons extends JFrame implements ActionListener {
JButton red = new JButton("RED");
JButton blue = new JButton("BLUE");
JButton green = new JButton("GREEN");
public ColorButtons() {
setTitle("Colors");
setLayout(new FlowLayout());
add(red); add(blue); add(green);
red.addActionListener(this);
blue.addActionListener(this);
green.addActionListener(this);
setSize(300, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
b.setOpaque(true);
b.setBorderPainted(false); // so the colour shows on all look-and-feels
switch (e.getActionCommand()) {
case "RED": b.setBackground(Color.RED); break;
case "BLUE": b.setBackground(Color.BLUE); break;
case "GREEN": b.setBackground(Color.GREEN); break;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(ColorButtons::new);
}
}
getSource() identifies the clicked button and getActionCommand() returns its caption, which selects the colour.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
List the steps to create an RMI application. Differentiate between RMI and CORBA.
Answer
Steps to create an RMI application
- Define the remote interface: extend
java.rmi.Remote; every method declaresthrows RemoteException. - Implement the remote interface: the implementation class extends
UnicastRemoteObject(or exports the object) and has a constructor that throwsRemoteException. - Write the server: create the object, optionally start the registry (
LocateRegistry.createRegistry(1099)), and bind the object withNaming.rebind("rmi://localhost/Name", obj). - Write the client: look up the remote object with
Naming.lookup(...), cast it to the interface and invoke methods. - Compile all files with
javac(stubs are generated dynamically in modern Java; older versions neededrmic). - Run: start
rmiregistry(if not started in code), then the server, then the client.
RMI versus CORBA
| RMI | CORBA |
|---|---|
| Java-specific: both client and server must be in Java | Language independent (C++, Java, Python, ...) |
| Interfaces are written in Java | Interfaces are written in IDL |
| Uses JRMP (or IIOP) protocol | Uses IIOP/GIOP through an ORB |
| Objects can be passed by value (serialisation) and code can be downloaded | Objects are passed by reference; no code download |
| Simple to learn and use | More complex, needs IDL compiler and ORB |
| Uses the RMI registry for naming | Uses the Naming service (COS Naming) |
| Garbage collection of remote objects | No distributed garbage collection |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Write a JavaFX application with components, buttons, text fields, and labels, arranged in a VBox or HBox layout.
Answer
JavaFX application with a VBox layout
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class FxDemo extends Application {
@Override
public void start(Stage stage) {
Label prompt = new Label("Enter your name:");
TextField nameField = new TextField();
Button btn = new Button("Greet");
Label output = new Label();
btn.setOnAction(e -> output.setText("Hello, " + nameField.getText() + "!"));
VBox root = new VBox(10, prompt, nameField, btn, output); // spacing 10
root.setPadding(new Insets(15));
stage.setScene(new Scene(root, 300, 200));
stage.setTitle("JavaFX Demo");
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
VBox stacks its children vertically (an HBox would place them in a row). The button's action handler reads the text field and shows a greeting in the label.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Assume a table MOVIE(id, title, genre). Now, using JDBC, perform the following queries:
a. Add any three records to the MOVIE table.
b. Using a prepared statement, update the genre to “Comedy” having the title “Jatra”.
Answer
JDBC operations on MOVIE(id, title, genre)
import java.sql.*;
public class MovieDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mrs";
try (Connection con = DriverManager.getConnection(url, "root", "password")) {
// a. insert three records
String ins = "INSERT INTO MOVIE(id, title, genre) VALUES (?, ?, ?)";
try (PreparedStatement ps = con.prepareStatement(ins)) {
Object[][] rows = {
{1, "Jatra", "Drama"},
{2, "Kabaddi", "Comedy"},
{3, "Loot", "Thriller"}
};
for (Object[] r : rows) {
ps.setInt(1, (Integer) r[0]);
ps.setString(2, (String) r[1]);
ps.setString(3, (String) r[2]);
ps.executeUpdate();
}
}
// b. update genre of "Jatra" to Comedy using a prepared statement
String upd = "UPDATE MOVIE SET genre = ? WHERE title = ?";
try (PreparedStatement ps = con.prepareStatement(upd)) {
ps.setString(1, "Comedy");
ps.setString(2, "Jatra");
int n = ps.executeUpdate();
System.out.println(n + " row(s) updated");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
The MySQL driver jar must be on the classpath. Placeholders ? are filled with setXxx() and avoid SQL injection.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
When do we need an internal frame? How do you create a table using Swing?
Answer
Internal frame
A JInternalFrame is a lightweight window that lives inside another container, normally a JDesktopPane. It is needed for a multiple-document interface (MDI), in which an application shows several documents or child windows within one main window, as in an IDE or a report tool. Internal frames can be resized, dragged, iconified, maximised and closed inside the desktop pane.
JFrame f = new JFrame("MDI");
JDesktopPane desktop = new JDesktopPane();
JInternalFrame in = new JInternalFrame("Child", true, true, true, true);
in.setSize(200, 150);
in.setVisible(true);
desktop.add(in);
f.setContentPane(desktop);
Creating a table with Swing
A table is created with JTable, which shows data from a TableModel. The simplest way is to give a 2-D array of data and a 1-D array of column names, and place the table in a JScrollPane so the header is displayed.
import javax.swing.*;
public class TableDemo {
public static void main(String[] args) {
String[] cols = {"ID", "Name", "Marks"};
Object[][] data = {
{1, "Ram", 85},
{2, "Sita", 92},
{3, "Hari", 78}
};
JTable table = new JTable(data, cols);
JFrame f = new JFrame("Table");
f.add(new JScrollPane(table));
f.setSize(300, 150);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
For dynamic data, use DefaultTableModel and call addRow().
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
What do you mean by JSP implicit objects? Discuss Java Mail API.
Answer
JSP implicit objects
Implicit objects are objects that the JSP container creates automatically and makes available in scriptlets and expressions without declaring them.
| Object | Type | Purpose |
|---|---|---|
request | HttpServletRequest | Client request data and parameters |
response | HttpServletResponse | Response to the client |
out | JspWriter | Writes output to the page |
session | HttpSession | Per-user data across requests |
application | ServletContext | Data shared by the whole application |
config | ServletConfig | Servlet configuration of the page |
pageContext | PageContext | Access to all scopes |
page | Object | The generated servlet (this) |
exception | Throwable | Available in error pages only |
Java Mail API
The JavaMail API (javax.mail, now jakarta.mail) is a platform-independent framework for building mail and messaging applications. It supports protocols SMTP (sending), POP3 and IMAP (receiving). Main classes are Session (mail session and properties), Message/MimeMessage (the message), Address/InternetAddress, Transport (sends) and Store/Folder (receive). It needs the JavaMail jar and the JavaBeans Activation Framework.
Sending a message involves: setting SMTP properties, getting a Session (with an Authenticator), creating a MimeMessage with from, to, subject and text, and calling Transport.send().
Properties p = new Properties();
p.put("mail.smtp.host", "smtp.gmail.com");
p.put("mail.smtp.port", "587");
p.put("mail.smtp.auth", "true");
p.put("mail.smtp.starttls.enable", "true");
Session s = Session.getInstance(p, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("me@gmail.com", "app-password");
}
});
MimeMessage m = new MimeMessage(s);
m.setFrom(new InternetAddress("me@gmail.com"));
m.addRecipient(Message.RecipientType.TO, new InternetAddress("you@example.com"));
m.setSubject("Hello");
m.setText("This is a test mail.");
Transport.send(m);
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Describe the role of Result Sets. What is wrong in the following code?
public class Point {
int p;
public void setP(int p) {
p = p;
}
}
Answer
Role of ResultSet
A ResultSet holds the rows returned by a SQL SELECT query executed through a Statement or PreparedStatement. It maintains a cursor that starts before the first row. next() advances the cursor; the getter methods (getInt, getString, getDate, ...) read column values by index or name. It can be forward-only or scrollable (first(), last(), absolute(), previous()) and read-only or updatable (updateXxx(), updateRow(), insertRow(), deleteRow()). It also gives metadata through getMetaData().
Error in the code
public void setP(int p) {
p = p;
}
The parameter p shadows the instance variable p. The statement p = p; assigns the parameter to itself, so the field p is never changed and keeps its default value 0. The fix is to refer to the field with this:
public void setP(int p) {
this.p = p;
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Write a TCP client-server system in which the client program sends two integers to a server program, which returns the greatest among them.
Answer
TCP client-server: greatest of two integers
MaxServer.java
import java.io.*;
import java.net.*;
public class MaxServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(6000);
System.out.println("Server waiting...");
Socket s = ss.accept();
DataInputStream in = new DataInputStream(s.getInputStream());
DataOutputStream out = new DataOutputStream(s.getOutputStream());
int a = in.readInt();
int b = in.readInt();
int max = Math.max(a, b);
out.writeInt(max);
s.close();
ss.close();
}
}
MaxClient.java
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class MaxClient {
public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost", 6000);
DataOutputStream out = new DataOutputStream(s.getOutputStream());
DataInputStream in = new DataInputStream(s.getInputStream());
Scanner sc = new Scanner(System.in);
System.out.print("Enter two integers: ");
int a = sc.nextInt();
int b = sc.nextInt();
out.writeInt(a);
out.writeInt(b);
System.out.println("Greatest = " + in.readInt());
s.close();
}
}
Start the server first, then the client. For input 12 and 30 the server returns 30.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Suppose that 9 integers are written in a file named “magic.txt” in the arrangement of 3 × 3 separated by space. Write a program to check whether the integers in all rows, all columns, and both diagonals sum to the same constant or not.
Answer
Magic square check from magic.txt
A 3 x 3 arrangement is a magic square when all three row sums, all three column sums and both diagonal sums are equal to the same constant.
import java.io.*;
import java.util.Scanner;
public class MagicCheck {
public static void main(String[] args) throws IOException {
int[][] m = new int[3][3];
Scanner sc = new Scanner(new File("magic.txt"));
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
m[i][j] = sc.nextInt();
sc.close();
int target = m[0][0] + m[1][1] + m[2][2]; // main diagonal
boolean ok = (m[0][2] + m[1][1] + m[2][0]) == target; // anti-diagonal
for (int i = 0; i < 3 && ok; i++) {
int row = 0, col = 0;
for (int j = 0; j < 3; j++) {
row += m[i][j];
col += m[j][i];
}
if (row != target || col != target) ok = false;
}
if (ok) System.out.println("Magic square, constant = " + target);
else System.out.println("Not a magic square");
}
}
Check with the file 2 7 6 / 9 5 1 / 4 3 8: rows give 15, 15, 15; columns give 15, 15, 15; diagonals give and . The output is "Magic square, constant = 15".
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Write a program to create a menu named “File” with menu items “New,” “Save,” and “Exit”.
Answer
Menu "File" with New, Save and Exit
import javax.swing.*;
import java.awt.event.*;
public class MenuDemo extends JFrame implements ActionListener {
JMenuItem newItem, saveItem, exitItem;
public MenuDemo() {
setTitle("Menu Demo");
JMenuBar bar = new JMenuBar();
JMenu file = new JMenu("File");
newItem = new JMenuItem("New");
saveItem = new JMenuItem("Save");
exitItem = new JMenuItem("Exit");
newItem.addActionListener(this);
saveItem.addActionListener(this);
exitItem.addActionListener(this);
file.add(newItem);
file.add(saveItem);
file.addSeparator();
file.add(exitItem);
bar.add(file);
setJMenuBar(bar);
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == exitItem) System.exit(0);
else System.out.println(e.getActionCommand() + " selected");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(MenuDemo::new);
}
}
The menu items are added to a JMenu, the menu to a JMenuBar, and the bar is attached to the frame with setJMenuBar().
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 10 marks
What is the task of the Listener interface? Write a socket program for a file server that makes a collection of files available for transmission to clients. When a client connects to the server, the server first reads a one-line command from the client. The command string can be of the form “GET <filename>”, where <filename> is a file name. The server checks whether the requested file actually exists. If so, it first sends the word “OK” as a message to the client. Then it sends the contents of the file and closes the connection. Otherwise, it sends “ERROR” to the client as message and closes the connection. Assume that there is no sub directories.
Answer
Task of the Listener interface
In the delegation event model, an event source (button, text field, window) generates an event object and delegates its handling to a registered listener. A listener interface (ActionListener, MouseListener, KeyListener, WindowListener, ...) declares the handler methods that the container calls when the event occurs. A class implements the interface, defines the methods with the response code, and registers itself with the source using addXxxListener(). This separates the event-generating code from the event-handling code.
File server using sockets
FileServer.java
import java.io.*;
import java.net.*;
public class FileServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(7000);
System.out.println("File server started");
while (true) {
Socket s = ss.accept();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
OutputStream out = s.getOutputStream();
PrintWriter pw = new PrintWriter(new OutputStreamWriter(out), true);
String cmd = in.readLine();
if (cmd != null && cmd.startsWith("GET ")) {
String name = cmd.substring(4).trim();
File f = new File(name);
// no sub directories: reject any path component
if (f.getName().equals(name) && f.isFile()) {
pw.println("OK");
FileInputStream fis = new FileInputStream(f);
byte[] buf = new byte[4096];
int n;
while ((n = fis.read(buf)) != -1) out.write(buf, 0, n);
out.flush();
fis.close();
} else {
pw.println("ERROR");
}
} else {
pw.println("ERROR");
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} finally {
s.close();
}
}
}
}
FileClient.java
import java.io.*;
import java.net.*;
public class FileClient {
public static void main(String[] args) throws IOException {
String fileName = args.length > 0 ? args[0] : "test.txt";
Socket s = new Socket("localhost", 7000);
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
InputStream raw = s.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(raw));
out.println("GET " + fileName);
String status = in.readLine();
if ("OK".equals(status)) {
String line;
while ((line = in.readLine()) != null) System.out.println(line);
} else {
System.out.println("File not found (ERROR)");
}
s.close();
}
}
The server reads the one-line command, checks that the file exists, replies OK followed by the file contents (or ERROR), and closes the connection.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 10 marks
Differentiate between path and class path in Java. When do you prefer anonymous inner class? Consider the following program and answer the given questions.
class A {
class B {
public void test() {
int i = 0;
while (i<=100){
System.out.println(i);
i = i + 2;
}
}
}
}
- Name the list of class file created after compiling above program
- Rewrite the above program using for loop
Answer
Path versus classpath
| PATH | CLASSPATH |
|---|---|
| Operating-system environment variable | Java-specific variable (or -cp option) |
Tells the OS where to find executables such as javac and java | Tells the JVM and compiler where to find user-defined classes, packages and jar files |
Holds directories of the JDK bin folder | Holds directories or jar files containing .class files |
Example: C:\Program Files\Java\jdk\bin | Example: .;lib/mysql-connector.jar |
Without it, the command javac is not recognised | Without it, ClassNotFoundException or "cannot find symbol" occurs |
When to prefer an anonymous inner class
An anonymous inner class is a nameless class declared and instantiated in one expression. It is preferred when a class is needed only once, usually to implement an interface or override a few methods of a class on the spot, for example an event listener, a Runnable or a Comparator, because it keeps the code short and close to where it is used and can access the final or effectively final local variables of the enclosing method.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Clicked");
}
});
1. Class files produced
Compiling the program generates two class files: A.class for the outer class and A$B.class for the inner class B.
2. Program using a for loop
class A {
class B {
public void test() {
for (int i = 0; i <= 100; i += 2) {
System.out.println(i);
}
}
}
}
It prints the even numbers 0, 2, 4, ..., 100, exactly as the original while loop does.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 10 marks
What are the tasks of sliders and scroll pane? Explain any four types of layout manager.
Answer
Tasks of sliders and scroll pane
Slider (JSlider). A slider lets the user choose a numeric value from a bounded range by dragging a knob along a track, so no typing is needed and invalid values cannot be entered. Its main tasks are:
- selecting a value between a minimum and a maximum (for example volume, brightness, zoom, colour component),
- showing tick marks and labels (
setMajorTickSpacing(),setMinorTickSpacing(),setPaintTicks(true),setPaintLabels(true)), - reporting changes through a
ChangeListener, whosestateChanged()method reads the current value withgetValue().
JSlider s = new JSlider(JSlider.HORIZONTAL, 0, 100, 50); // min, max, initial
s.setMajorTickSpacing(20);
s.setPaintTicks(true);
s.setPaintLabels(true);
s.addChangeListener(e -> label.setText("Value = " + s.getValue()));
Scroll pane (JScrollPane). A scroll pane is a container that holds one component (a text area, table, list, image label) which is larger than the visible area, and supplies horizontal and vertical scroll bars to view the hidden parts. Its tasks are:
- showing a large component through a smaller viewport,
- creating and managing the scroll bars automatically, according to the policy set by
setHorizontalScrollBarPolicy()andsetVerticalScrollBarPolicy()(AS_NEEDED,ALWAYS,NEVER), - optionally showing row and column headers.
JTextArea area = new JTextArea(10, 30);
JScrollPane sp = new JScrollPane(area);
frame.add(sp);
Layout managers
A layout manager decides the size and position of the components inside a container, and re-arranges them when the container is resized. It is set with setLayout().
1. FlowLayout. Places components one after another in a row from left to right, in the order they were added, and wraps to the next row when the row is full. Each component keeps its preferred size. It is the default layout of JPanel. Alignment and gaps can be given: new FlowLayout(FlowLayout.CENTER, 10, 10).
2. BorderLayout. Divides the container into five regions: NORTH, SOUTH, EAST, WEST and CENTER. One component goes in each region (add(comp, BorderLayout.NORTH)). North and south take their preferred height, east and west their preferred width, and the centre takes all remaining space. It is the default layout of JFrame.
3. GridLayout. Divides the container into equal-sized cells of a fixed number of rows and columns, and fills the cells row by row. Every component is stretched to the cell size. new GridLayout(3, 3, 5, 5) makes a 3 by 3 grid with 5 pixel gaps; it suits calculators and keypads.
4. CardLayout. Stacks several components (cards) one over another so that only one is visible at a time, like pages of a wizard. The visible card is changed with first(), next(), previous(), last() or show(container, "name").
(BoxLayout and GridBagLayout are other layouts: BoxLayout arranges components in a single row or column, and GridBagLayout is a flexible grid in which components may span several rows or columns.)
import javax.swing.*;
import java.awt.*;
public class LayoutDemo {
public static void main(String[] a) {
JFrame f = new JFrame("Layouts");
f.setLayout(new BorderLayout());
JPanel flow = new JPanel(new FlowLayout());
flow.add(new JButton("One")); flow.add(new JButton("Two"));
JPanel grid = new JPanel(new GridLayout(2, 2));
for (int i = 1; i <= 4; i++) grid.add(new JButton("G" + i));
f.add(flow, BorderLayout.NORTH);
f.add(grid, BorderLayout.CENTER);
f.setSize(300, 200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
How does JavaFX hyperlink control format text that functions as button? Illustrate with an example.
Answer
In JavaFX, Hyperlink (package javafx.scene.control) is a subclass of Labeled/ButtonBase. It displays text that looks like an HTML link: blue and underlined, a hand cursor on hover, and a different colour after it has been visited (setVisited(true)). Because it extends ButtonBase, it fires an ActionEvent when clicked, so it behaves as a button that is formatted as text. The look can be changed with setFont(), setTextFill(), setUnderline(), setBorder() or CSS, and it can also carry a graphic with setGraphic().
Typical uses are opening a web page (via HostServices.showDocument()), opening a dialog, or switching to another scene, while keeping the appearance of a link rather than a rectangular button.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class HyperlinkDemo extends Application {
@Override
public void start(Stage stage) {
Hyperlink link = new Hyperlink("Visit Tribhuvan University");
Label msg = new Label();
link.setOnAction(e -> {
getHostServices().showDocument("https://www.tu.edu.np");
link.setVisited(true); // link changes colour
msg.setText("Link clicked");
});
VBox root = new VBox(10, link, msg);
root.setStyle("-fx-padding: 20;");
stage.setScene(new Scene(root, 300, 120));
stage.setTitle("Hyperlink");
stage.show();
}
public static void main(String[] args) { launch(args); }
}
When the user clicks the text, the setOnAction handler runs exactly as it would for a Button, which shows how the hyperlink is a text-formatted button.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Describe any two types of events.
Answer
An event is an object that describes a change of state in a source component, for example a button click or a key press. Java handles events with the delegation event model: the source generates an event and passes it to a registered listener. Two common types are described below.
1. ActionEvent. Generated when an action is performed on a component: a button is clicked, a menu item is chosen, Enter is pressed in a text field, or a list item is double-clicked. It is handled by the ActionListener interface, which has one method, actionPerformed(ActionEvent e). The command string is obtained with e.getActionCommand() and the source with e.getSource().
JButton b = new JButton("OK");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked");
}
});
2. MouseEvent. Generated when the mouse is pressed, released, clicked, moved, dragged, or enters or leaves a component. It is handled by MouseListener (mousePressed, mouseReleased, mouseClicked, mouseEntered, mouseExited) and by MouseMotionListener (mouseMoved, mouseDragged). The position of the pointer is read with e.getX() and e.getY().
panel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Clicked at " + e.getX() + "," + e.getY());
}
});
Other event types are KeyEvent (keyboard), ItemEvent (check box or choice selection), FocusEvent (gaining or losing focus), WindowEvent and TextEvent.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
How do you write an IDL file and generate the stub and skeleton code for CORBA implementation? Explain.
Answer
CORBA (Common Object Request Broker Architecture) lets objects written in different languages on different machines communicate through an ORB. The interface of a remote object is described in a language-neutral IDL (Interface Definition Language) file, and an IDL compiler generates the language-specific stub (client-side proxy) and skeleton (server-side base class).
Step 1: Write the IDL file (Hello.idl). IDL uses module, interface and operation declarations with typed parameters.
module HelloApp {
interface Hello {
string sayHello();
oneway void shutdown();
};
};
Step 2: Compile the IDL file with the Java IDL compiler idlj (shipped with older JDKs, up to Java 8):
idlj -fall Hello.idl
The option -fall generates both client and server files. Inside the folder HelloApp the following are produced:
Hello.java: the Java interface, which is the signature of the remote object,HelloOperations.java: the operations declared in the interface,_HelloStub.java: the stub, which the client uses; it marshals the call and sends it to the ORB,HelloPOA.java: the skeleton on the server side; the servant class extends it and implements the operations,HelloHelper.java: hasnarrow()to cast an object reference toHello,HelloHolder.java: holder class for out and inout arguments.
Step 3: Implement the servant by extending the skeleton:
class HelloImpl extends HelloPOA {
public String sayHello() { return "Hello from CORBA"; }
public void shutdown() { }
}
Step 4: Write the server, which creates the ORB, activates the servant, and registers it with the Naming Service. Step 5: Write the client, which gets the naming context, resolves "Hello", narrows the reference with HelloHelper.narrow() and calls sayHello() through the stub.
Step 6: Compile and run: compile all the .java files with javac, start the name service with orbd -ORBInitialPort 1050, start the server and then the client with -ORBInitialPort 1050.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Design a simple form that takes name, password, hobbies and gender as input.
Answer
The form below is a Swing form with a text field for the name, a password field, check boxes for the hobbies, and radio buttons (in a ButtonGroup, so only one can be chosen) for the gender.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleForm extends JFrame implements ActionListener {
JTextField nameField = new JTextField(15);
JPasswordField passField = new JPasswordField(15);
JCheckBox reading = new JCheckBox("Reading");
JCheckBox music = new JCheckBox("Music");
JCheckBox sports = new JCheckBox("Sports");
JRadioButton male = new JRadioButton("Male");
JRadioButton female = new JRadioButton("Female");
JRadioButton other = new JRadioButton("Other");
JButton submit = new JButton("Submit");
JLabel result = new JLabel(" ");
public SimpleForm() {
super("Registration Form");
setLayout(new GridLayout(6, 2, 5, 5));
ButtonGroup bg = new ButtonGroup();
bg.add(male); bg.add(female); bg.add(other);
JPanel hobbies = new JPanel(new FlowLayout(FlowLayout.LEFT));
hobbies.add(reading); hobbies.add(music); hobbies.add(sports);
JPanel gender = new JPanel(new FlowLayout(FlowLayout.LEFT));
gender.add(male); gender.add(female); gender.add(other);
add(new JLabel("Name:")); add(nameField);
add(new JLabel("Password:")); add(passField);
add(new JLabel("Hobbies:")); add(hobbies);
add(new JLabel("Gender:")); add(gender);
add(new JLabel()); add(submit);
add(new JLabel()); add(result);
submit.addActionListener(this);
setSize(420, 280);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
StringBuilder h = new StringBuilder();
if (reading.isSelected()) h.append("Reading ");
if (music.isSelected()) h.append("Music ");
if (sports.isSelected()) h.append("Sports ");
String g = male.isSelected() ? "Male"
: female.isSelected() ? "Female"
: other.isSelected() ? "Other" : "-";
result.setText(nameField.getText() + ", " + h + ", " + g);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(SimpleForm::new);
}
}
The password is stored in passField.getPassword() (a char[]), and the characters are shown as dots.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Assume that a text file named “ONE.TXT” contains a paragraph of text. Write a program to copy the word that starts with vowel from “ONE.TXT” to another file “TWO.TXT”.
Answer
The program reads ONE.TXT word by word, checks whether the first letter of a word is a vowel (a, e, i, o, u, in either case), and writes such words to TWO.TXT. Punctuation is stripped from the word before testing, and the file streams are closed automatically by try-with-resources.
import java.io.*;
public class VowelWords {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("ONE.TXT"));
PrintWriter pw = new PrintWriter(new FileWriter("TWO.TXT"))) {
String line;
while ((line = br.readLine()) != null) {
String[] words = line.split("\\s+");
for (String w : words) {
w = w.replaceAll("[^A-Za-z0-9]", ""); // remove punctuation
if (w.isEmpty()) continue;
char c = Character.toLowerCase(w.charAt(0));
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
pw.print(w + " ");
}
}
}
System.out.println("Words starting with a vowel copied to TWO.TXT");
} catch (IOException e) {
System.out.println("File error: " + e.getMessage());
}
}
}
For example, if ONE.TXT contains An apple a day keeps every doctor away, then TWO.TXT contains An apple a every away.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
What do you mean by SQL escape? Describe about scrollable and updateable result sets.
Answer
SQL escape
SQL escape syntax is a standard, database-independent way to write non-standard features in a JDBC statement. The text is placed in curly braces, { ... }, and the JDBC driver translates it into the syntax of the particular database. This keeps the program portable. The main forms are:
- Date and time literals:
{d '2081-04-15'},{t '10:30:00'},{ts '2081-04-15 10:30:00'}. - Scalar functions:
{fn UCASE(name)},{fn NOW()}. - Stored procedure calls:
{call getStudent(?)}or{? = call getCount()}. - Outer joins:
{oj Student LEFT OUTER JOIN Result ON Student.id = Result.id}. - The LIKE escape character:
WHERE name LIKE '100\%' {escape '\'}, used to match a literal%or_.
ResultSet rs = st.executeQuery("SELECT * FROM Exam WHERE edate = {d '2081-04-15'}");
Scrollable result sets
By default a ResultSet is forward-only: it can be read once from the first row to the last using next(). A scrollable result set can move both ways and jump to any row. It is requested when creating the statement:
Statement st = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE, // or TYPE_SCROLL_SENSITIVE
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = st.executeQuery("SELECT id, name FROM Student");
rs.last(); // go to the last row
int rows = rs.getRow();
rs.first(); rs.previous(); rs.absolute(3); rs.relative(-1);
TYPE_FORWARD_ONLY: moves only forward.TYPE_SCROLL_INSENSITIVE: scrolls, and does not show changes made by others after the result set was opened.TYPE_SCROLL_SENSITIVE: scrolls, and does show such changes.
Navigation methods are first(), last(), next(), previous(), absolute(n), relative(n), beforeFirst() and afterLast().
Updatable result sets
With concurrency CONCUR_UPDATABLE, rows can be changed through the result set itself, without writing separate SQL UPDATE, INSERT or DELETE statements.
Statement st = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery("SELECT id, name FROM Student");
rs.absolute(2);
rs.updateString("name", "Sita"); // change column value
rs.updateRow(); // write it to the database
rs.moveToInsertRow(); // insert a new row
rs.updateInt("id", 10);
rs.updateString("name", "Ram");
rs.insertRow();
rs.absolute(3);
rs.deleteRow(); // delete the current row
The query must select from a single table and include the primary key for the result set to be updatable.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Explain the life cycle of servlets.
Answer
A servlet is a Java class that runs inside a servlet container (such as Tomcat) and handles HTTP requests. Its life cycle is controlled by the container through three methods of the javax.servlet.Servlet interface (jakarta.servlet in newer versions).
1. Loading and instantiation. When the first request arrives (or at server start if load-on-startup is set), the container loads the servlet class and creates one instance of it.
2. Initialization: init(ServletConfig config). Called once, after the instance is created and before any request is served. It is used for one-time work such as opening a database connection or reading initialization parameters.
3. Request handling: service(ServletRequest req, ServletResponse res). Called for every request, each in a separate thread of the same instance. In HttpServlet, service() looks at the HTTP method and dispatches to doGet(), doPost(), doPut() or doDelete(), which read the request and write the response.
4. Destruction: destroy(). Called once when the container removes the servlet, for example at shutdown or redeployment. It is used to release resources such as database connections and files. After this, the instance is garbage collected.
Load class -> create instance -> init() -> [ service() -> doGet()/doPost() ]* -> destroy()
public class LifeCycleServlet extends HttpServlet {
public void init() { System.out.println("init called once"); }
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
res.getWriter().println("Request handled");
}
public void destroy() { System.out.println("destroy called once"); }
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Write a program in JSP to display the string taken in one page in another page.
Answer
Two JSP pages are used: input.jsp has a form that takes a string, and display.jsp reads the string from the request and displays it.
input.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<head><title>Input Page</title></head>
<body>
<form action="display.jsp" method="post">
Enter a string: <input type="text" name="text">
<input type="submit" value="Send">
</form>
</body>
</html>
display.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<head><title>Display Page</title></head>
<body>
<%
String s = request.getParameter("text");
%>
<h3>The string entered in the previous page is: <%= s %></h3>
</body>
</html>
When the form is submitted, the browser sends the field text to display.jsp. The implicit object request gives the value with getParameter("text"), and the expression <%= s %> prints it into the response.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
How do you insert pop-up menu? Distinguish between GET and POST request.
Answer
Inserting a pop-up menu
In Swing a pop-up (context) menu is a JPopupMenu containing JMenuItems. It is shown when the user right-clicks a component. The steps are: create the JPopupMenu, add menu items with listeners, register a MouseListener on the component, and call popup.show(component, x, y) when the mouse event is the pop-up trigger (e.isPopupTrigger()).
import javax.swing.*;
import java.awt.event.*;
public class PopupDemo {
public static void main(String[] args) {
JFrame f = new JFrame("Popup");
JTextArea area = new JTextArea();
JPopupMenu popup = new JPopupMenu();
JMenuItem cut = new JMenuItem("Cut");
JMenuItem copy = new JMenuItem("Copy");
JMenuItem paste = new JMenuItem("Paste");
popup.add(cut); popup.add(copy); popup.addSeparator(); popup.add(paste);
cut.addActionListener(e -> area.cut());
copy.addActionListener(e -> area.copy());
paste.addActionListener(e -> area.paste());
area.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) { show(e); }
public void mouseReleased(MouseEvent e) { show(e); }
void show(MouseEvent e) {
if (e.isPopupTrigger()) popup.show(e.getComponent(), e.getX(), e.getY());
}
});
f.add(new JScrollPane(area));
f.setSize(300, 200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
Difference between GET and POST
| GET | POST |
|---|---|
Form data is appended to the URL as a query string (page?name=Ram). | Form data is sent in the body of the HTTP request. |
| Data is visible in the address bar, history and logs, so it is not suitable for passwords. | Data is not shown in the URL, so it is more secure for sensitive data. |
| Limited data size (URL length limit, about 2 KB in practice). | No practical size limit; large data and file uploads are possible. |
| Can be bookmarked and cached. | Cannot be bookmarked and is not cached. |
| Idempotent: repeating it has the same effect; used to retrieve data. | Not idempotent: used to create or change data on the server. |
Handled by doGet() in a servlet. | Handled by doPost() in a servlet. |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 10 marks
What are the uses of focus and item event? Write a socket program using UDP to create three programs, two of which are clients to a single server. Client1 will send a character to the server process. The server will circularly decrement the letter to the previous letter in the alphabet and send the result to Client2. Then Client2 prints the letter it receives and then all the processes terminate.
Answer
Uses of focus and item events
Focus event (FocusEvent). Generated when a component gains or loses the keyboard focus. It is handled by FocusListener with the methods focusGained(FocusEvent e) and focusLost(FocusEvent e). Uses: validating a text field when the user leaves it (focusLost), selecting or highlighting the text when the field is entered (focusGained), changing the colour of the active field, and showing help messages.
Item event (ItemEvent). Generated when the selection state of an item changes in a check box, radio button, combo box, choice or list. It is handled by ItemListener with the method itemStateChanged(ItemEvent e). e.getStateChange() returns ItemEvent.SELECTED or ItemEvent.DESELECTED, and e.getItem() returns the item. Uses: reacting to a change in a check box or a selection from a drop-down list, such as enabling a field when a box is ticked or updating a label when a city is chosen.
UDP program
There are three programs. The server listens on port 9000. Client1 sends one character to the server. The server replaces it with the previous letter of the alphabet, circularly (a becomes z, A becomes Z, any other letter x becomes x-1), and sends the result by UDP to Client2, which listens on port 9002. Client2 prints the letter. Start Client2 first, then the server, then Client1.
Client2.java (receiver)
import java.net.*;
public class Client2 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(9002);
byte[] buf = new byte[1];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
System.out.println("Client2 received: " + (char) buf[0]);
socket.close();
}
}
Server.java
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(9000);
byte[] buf = new byte[1];
DatagramPacket in = new DatagramPacket(buf, buf.length);
socket.receive(in); // from Client1
char c = (char) buf[0];
char prev;
if (c == 'a') prev = 'z';
else if (c == 'A') prev = 'Z';
else prev = (char) (c - 1); // previous letter
byte[] out = { (byte) prev };
InetAddress host = InetAddress.getByName("localhost");
DatagramPacket p = new DatagramPacket(out, out.length, host, 9002);
socket.send(p); // to Client2
System.out.println("Server: " + c + " -> " + prev);
socket.close();
}
}
Client1.java (sender)
import java.net.*;
public class Client1 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
char c = 'd'; // letter to send
byte[] data = { (byte) c };
InetAddress host = InetAddress.getByName("localhost");
socket.send(new DatagramPacket(data, data.length, host, 9000));
System.out.println("Client1 sent: " + c);
socket.close();
}
}
For the input d the output of Client2 is c; for a it is z. Each program closes its socket and ends, so all three processes terminate.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 10 marks
Write a JavaFX application that creates a ChoiceBox with a list of colors. Display a label that changes its text based on the selected color from the ChoiceBox. Write down steps for writing CORBA programs with a suitable example.
Answer
JavaFX ChoiceBox application
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ColorChoice extends Application {
@Override
public void start(Stage stage) {
ChoiceBox<String> box = new ChoiceBox<>(
FXCollections.observableArrayList("Red", "Green", "Blue", "Yellow"));
Label label = new Label("No color selected");
box.getSelectionModel().selectedItemProperty().addListener(
(obs, oldColor, newColor) -> label.setText("You selected: " + newColor));
VBox root = new VBox(15, box, label);
root.setStyle("-fx-padding: 20;");
stage.setScene(new Scene(root, 280, 130));
stage.setTitle("ChoiceBox Demo");
stage.show();
}
public static void main(String[] args) { launch(args); }
}
The listener on the selected item property runs each time the user chooses a colour and updates the label text.
Steps for writing a CORBA program
- Define the interface in IDL. Write the remote interface in a
.idlfile. ExampleHello.idl:
module HelloApp {
interface Hello { string sayHello(); };
};
-
Compile the IDL with
idlj -fall Hello.idl. It generatesHello.java,HelloOperations.java,_HelloStub.java(client stub),HelloPOA.java(server skeleton),HelloHelper.javaandHelloHolder.java. -
Write the servant that implements the operations by extending the skeleton:
class HelloImpl extends HelloPOA {
public String sayHello() { return "Hello from CORBA server"; }
}
- Write the server. It initialises the ORB, gets the root POA and activates the POA manager, creates the servant, gets its object reference, finds the Naming Service, and binds the name:
import org.omg.CORBA.*;
import org.omg.CosNaming.*;
import org.omg.PortableServer.*;
import HelloApp.*;
public class HelloServer {
public static void main(String[] args) throws Exception {
ORB orb = ORB.init(args, null);
POA rootpoa = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
rootpoa.the_POAManager().activate();
HelloImpl impl = new HelloImpl();
Hello ref = HelloHelper.narrow(rootpoa.servant_to_reference(impl));
NamingContextExt nc = NamingContextExtHelper.narrow(
orb.resolve_initial_references("NameService"));
nc.rebind(nc.to_name("Hello"), ref);
System.out.println("Server ready");
orb.run(); // wait for client calls
}
}
- Write the client. It initialises the ORB, resolves the name from the Naming Service, narrows the reference, and calls the remote method through the stub:
public class HelloClient {
public static void main(String[] args) throws Exception {
ORB orb = ORB.init(args, null);
NamingContextExt nc = NamingContextExtHelper.narrow(
orb.resolve_initial_references("NameService"));
Hello hello = HelloHelper.narrow(nc.resolve_str("Hello"));
System.out.println(hello.sayHello());
}
}
-
Compile all files with
javac HelloApp/*.java *.java. -
Run: start the ORB name service
orbd -ORBInitialPort 1050, then the serverjava HelloServer -ORBInitialPort 1050, then the clientjava HelloClient -ORBInitialPort 1050. The client printsHello from CORBA server.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 10 marks
Discuss about JSP implicit objects. Assume a database with the table TEACHER (ID, Name). Now using JDBC, execute the following SQL query:
- a. select * from TEACHER;
- b. insert into TEACHER values (8, 'Ramesh');
- c. select name from TEACHER where ID = 9;
Answer
JSP implicit objects
Implicit objects are objects that the JSP container creates automatically in every JSP page, so they can be used in scriptlets and expressions without being declared. There are nine:
| Object | Type | Purpose |
|---|---|---|
request | HttpServletRequest | Client request: parameters (getParameter()), headers, cookies. |
response | HttpServletResponse | Response to the client: set headers, redirect (sendRedirect()), add cookies. |
out | JspWriter | Writes output to the response (out.println()). |
session | HttpSession | Data kept across several requests of one user. |
application | ServletContext | Data shared by all users of the web application. |
config | ServletConfig | Initialization parameters of the JSP servlet. |
pageContext | PageContext | Access to all scopes and the other implicit objects. |
page | Object | The current servlet instance (like this). |
exception | Throwable | The uncaught exception; available only in an error page (isErrorPage="true"). |
JDBC program for the TEACHER table
The program loads the driver, connects, and runs the three queries. A MySQL database named college is assumed.
import java.sql.*;
public class TeacherDB {
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()) {
Class.forName("com.mysql.cj.jdbc.Driver");
// a. select * from TEACHER
ResultSet rs = st.executeQuery("select * from TEACHER");
while (rs.next()) {
System.out.println(rs.getInt("ID") + " " + rs.getString("Name"));
}
// b. insert into TEACHER values (8, 'Ramesh')
int n = st.executeUpdate("insert into TEACHER values (8, 'Ramesh')");
System.out.println(n + " row inserted");
// c. select name from TEACHER where ID = 9
ResultSet r2 = st.executeQuery("select name from TEACHER where ID = 9");
if (r2.next()) System.out.println("Name = " + r2.getString("name"));
else System.out.println("No teacher with ID 9");
} catch (Exception e) {
e.printStackTrace();
}
}
}
executeQuery() is used for select statements and returns a ResultSet; executeUpdate() is used for insert, update and delete and returns the number of rows affected.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Write a program to insert an icon in the frame and when the user presses the up arrow, it will move upward.
Answer
The program shows an icon (an ImageIcon in a JLabel) in a frame with no layout manager, and a KeyListener moves the label up by 10 pixels each time the up arrow is pressed. The panel must have the focus to receive key events. The image file icon.png is assumed to be in the working directory.
import javax.swing.*;
import java.awt.event.*;
public class MoveIcon extends JFrame implements KeyListener {
JLabel label;
public MoveIcon() {
super("Move Icon");
setLayout(null); // absolute positioning
label = new JLabel(new ImageIcon("icon.png"));
label.setBounds(150, 200, 50, 50); // x, y, width, height
add(label);
addKeyListener(this);
setFocusable(true);
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
int y = label.getY();
if (y > 0) label.setLocation(label.getX(), y - 10); // move upward
}
}
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) { }
public static void main(String[] args) {
SwingUtilities.invokeLater(MoveIcon::new);
}
}
The y-coordinate decreases upward on the screen, so subtracting 10 from y moves the icon up. The check y > 0 keeps it inside the frame.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
How do you handle HTTP request and response using JSP? Illustrate with an example.
Answer
In JSP the container supplies the implicit objects request (HttpServletRequest) and response (HttpServletResponse) for handling the HTTP request and response.
Handling the request. The request object gives the data sent by the client:
request.getParameter("name"): value of a form field or query-string parameter,request.getParameterValues("hobby"): all values of a multi-valued field,request.getMethod(),request.getHeader("User-Agent"),request.getRemoteAddr(),request.getCookies().
Handling the response. The response object controls what is sent back:
response.setContentType("text/html"): type of the output,response.sendRedirect("page.jsp"): send the browser to another URL,response.addCookie(cookie)andresponse.setHeader(name, value),out.println()orresponse.getWriter()to write the content.
Example
login.html
<form action="welcome.jsp" method="post">
Username: <input type="text" name="user">
Password: <input type="password" name="pass">
<input type="submit" value="Login">
</form>
welcome.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<%
String user = request.getParameter("user");
String pass = request.getParameter("pass");
if ("admin".equals(user) && "1234".equals(pass)) {
out.println("<h2>Welcome, " + user + "</h2>");
out.println("Request method: " + request.getMethod());
} else {
response.sendRedirect("login.html"); // wrong login: back to the form
}
%>
The form data is read from the request, a decision is made, and the response is either an HTML page or a redirect.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Describe the life cycle of a servlet.
Answer
A servlet is a Java class that runs inside a servlet container (for example Tomcat) and serves HTTP requests. The container manages its life cycle with three methods of the Servlet interface.
1. Loading and instantiation. The container loads the servlet class when the first request arrives, or at start-up if load-on-startup is given, and creates a single instance.
2. init(ServletConfig). Called exactly once after instantiation and before the first request. It performs one-time initialization such as opening database connections or reading initial parameters.
3. service(ServletRequest, ServletResponse). Called for each client request, in a separate thread for each request but on the same servlet instance. In HttpServlet it calls doGet(), doPost() or another doXxx() method according to the HTTP method. The servlet reads the request and writes the response here.
4. destroy(). Called once when the container takes the servlet out of service (shutdown, undeploy or reload). Resources are released here, and the instance then becomes eligible for garbage collection.
Loaded -> init() -> ready: service() for each request -> destroy() -> garbage collected
public class DemoServlet extends HttpServlet {
public void init() { System.out.println("Initialised"); }
protected void doGet(HttpServletRequest rq, HttpServletResponse rs) throws IOException {
rs.getWriter().println("Hello");
}
public void destroy() { System.out.println("Destroyed"); }
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Write a program to input the name of faculty and throw an exception if that input is not “CSIT”.
Answer
The program defines a user-defined (checked) exception InvalidFacultyException. It reads the faculty name and throws the exception if it is not "CSIT"; the exception is caught and a message is shown.
import java.util.Scanner;
class InvalidFacultyException extends Exception {
public InvalidFacultyException(String message) {
super(message);
}
}
public class FacultyCheck {
static void check(String faculty) throws InvalidFacultyException {
if (!faculty.equals("CSIT")) {
throw new InvalidFacultyException("Invalid faculty: " + faculty);
}
System.out.println("Faculty accepted: " + faculty);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter name of faculty: ");
String faculty = sc.nextLine().trim();
try {
check(faculty);
} catch (InvalidFacultyException e) {
System.out.println("Exception caught: " + e.getMessage());
} finally {
sc.close();
}
}
}
Sample runs: input CSIT prints Faculty accepted: CSIT; input BCA prints Exception caught: Invalid faculty: BCA.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Write a program to design a layout of a simple calculator. (Arithmetic operation not required.)
Answer
The calculator layout uses a BorderLayout: a non-editable text field in the NORTH region for the display, and a JPanel with a 4 by 4 GridLayout in the CENTER for the keys. No arithmetic is implemented.
import javax.swing.*;
import java.awt.*;
public class CalculatorLayout extends JFrame {
public CalculatorLayout() {
super("Calculator");
setLayout(new BorderLayout(5, 5));
JTextField display = new JTextField();
display.setEditable(false);
display.setHorizontalAlignment(JTextField.RIGHT);
display.setFont(new Font("Arial", Font.BOLD, 24));
add(display, BorderLayout.NORTH);
String[] keys = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};
JPanel pad = new JPanel(new GridLayout(4, 4, 5, 5));
for (String k : keys) {
JButton b = new JButton(k);
b.setFont(new Font("Arial", Font.PLAIN, 18));
pad.add(b);
}
add(pad, BorderLayout.CENTER);
JButton clear = new JButton("C");
add(clear, BorderLayout.SOUTH);
setSize(280, 340);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(CalculatorLayout::new);
}
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
What is a package? Differentiate between method overloading and overriding.
Answer
Package
A package is a named group of related classes, interfaces and sub-packages. It organises the code, avoids name conflicts (two classes with the same name can exist in different packages), and gives access control through the default (package-private) and protected access levels. Java has built-in packages such as java.util, java.io and java.sql, and users can create their own.
A package is created with the package statement as the first line of the source file, and used with import:
package college.util; // file: college/util/Calc.java
public class Calc {
public static int add(int a, int b) { return a + b; }
}
import college.util.Calc;
public class Test {
public static void main(String[] a) { System.out.println(Calc.add(2, 3)); }
}
It is compiled with javac -d . Calc.java, which creates the folder structure college/util.
Method overloading and method overriding
| Overloading | Overriding |
|---|---|
| Several methods with the same name but different parameter lists (number, type or order) in the same class. | A subclass gives its own implementation of a method already defined in its superclass, with the same name and parameters. |
| Compile-time (static) polymorphism. | Run-time (dynamic) polymorphism. |
| Return type may differ, but it alone cannot distinguish the methods. | Return type must be the same (or a covariant subtype). |
| No inheritance needed. | Inheritance is required. |
| Access modifier can be anything. | Access cannot be more restrictive than the overridden method. |
static and private methods can be overloaded. | static, private and final methods cannot be overridden. |
class A {
void show(int x) { System.out.println("int " + x); }
void show(String s) { System.out.println("String " + s); } // overloading
}
class B extends A {
@Override void show(int x) { System.out.println("B int " + x); } // overriding
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Write a program to demonstrate the concept of internal frame.
Answer
An internal frame (JInternalFrame) is a lightweight window that lives inside another container, normally a JDesktopPane, and so forms a multiple document interface (MDI). Internal frames can be dragged, resized, minimised, maximised, closed and iconified within the desktop pane, but cannot leave it.
import javax.swing.*;
public class InternalFrameDemo extends JFrame {
int count = 0;
public InternalFrameDemo() {
super("Internal Frame Demo");
JDesktopPane desktop = new JDesktopPane();
setContentPane(desktop);
JMenuBar bar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem newDoc = new JMenuItem("New Document");
file.add(newDoc);
bar.add(file);
setJMenuBar(bar);
newDoc.addActionListener(e -> {
count++;
JInternalFrame inner = new JInternalFrame(
"Document " + count,
true, // resizable
true, // closable
true, // maximizable
true); // iconifiable
inner.add(new JScrollPane(new JTextArea()));
inner.setSize(250, 150);
inner.setLocation(20 * count, 20 * count);
inner.setVisible(true);
desktop.add(inner);
});
setSize(600, 450);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(InternalFrameDemo::new);
}
}
Each click on File, New Document adds a new internal frame, cascaded slightly, inside the single outer window.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Write a program to create a class MOVIE with attributes name and genre. Write the movies with genre comedy on COM.DAT file.
Answer
The class Movie implements Serializable so that its objects can be written to a file with ObjectOutputStream. The program creates some movies and writes only those whose genre is "comedy" to COM.DAT. A second part reads the file back to check it.
import java.io.*;
import java.util.*;
class Movie implements Serializable {
private static final long serialVersionUID = 1L;
String name;
String genre;
Movie(String name, String genre) {
this.name = name;
this.genre = genre;
}
public String toString() { return name + " (" + genre + ")"; }
}
public class MovieFile {
public static void main(String[] args) {
List<Movie> movies = new ArrayList<>();
movies.add(new Movie("Jatra", "comedy"));
movies.add(new Movie("Kabaddi", "comedy"));
movies.add(new Movie("Loot", "thriller"));
movies.add(new Movie("Pashupati Prasad", "drama"));
// write comedy movies to COM.DAT
try (ObjectOutputStream out =
new ObjectOutputStream(new FileOutputStream("COM.DAT"))) {
for (Movie m : movies) {
if (m.genre.equalsIgnoreCase("comedy")) {
out.writeObject(m);
}
}
} catch (IOException e) {
System.out.println("Write error: " + e.getMessage());
}
// read back
try (ObjectInputStream in =
new ObjectInputStream(new FileInputStream("COM.DAT"))) {
while (true) {
System.out.println(in.readObject());
}
} catch (EOFException e) {
// end of file reached
} catch (IOException | ClassNotFoundException e) {
System.out.println("Read error: " + e.getMessage());
}
}
}
The output is Jatra (comedy) and Kabaddi (comedy); the thriller and drama movies are not written.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Do we still need Java Applet? Justify. Give the hierarchy of Swing class.
Answer
Do we still need Java Applet?
No, applets are no longer needed in practice. They were small Java programs embedded in a web page and run by the browser's Java plug-in. They are now obsolete for these reasons:
- Browsers (Chrome, Firefox, Edge, Safari) removed NPAPI plug-in support, so applets no longer run in them.
- Applets had many security problems and needed signing and permissions.
- Oracle deprecated the Applet API in Java 9 and marked it for removal in Java 17.
- HTML5, CSS and JavaScript (with frameworks such as React and Angular), WebAssembly and server-side Java (servlets, JSP, Spring) do the same job without a plug-in, and work on mobile devices too.
- Desktop-style Java interfaces are now built with Swing or JavaFX, and deployed as standalone applications or with Java Web Start alternatives.
Applets are still studied because they show the event model, the life cycle (init, start, stop, destroy, paint) and AWT or Swing painting, and some legacy systems still contain them.
Hierarchy of Swing classes
Swing components are in javax.swing and mostly extend the AWT class Container:
java.lang.Object
+-- java.awt.Component
+-- java.awt.Container
+-- java.awt.Window
| +-- java.awt.Frame
| | +-- javax.swing.JFrame
| +-- java.awt.Dialog
| +-- javax.swing.JDialog
| (java.awt.Applet -> javax.swing.JApplet)
+-- javax.swing.JComponent
+-- JPanel
+-- JLabel
+-- AbstractButton
| +-- JButton
| +-- JToggleButton
| | +-- JCheckBox, JRadioButton
| +-- JMenuItem
| +-- JMenu, JCheckBoxMenuItem, JRadioButtonMenuItem
+-- JTextComponent
| +-- JTextField (JPasswordField), JTextArea, JEditorPane
+-- JComboBox, JList, JTable, JTree
+-- JScrollPane, JSplitPane, JTabbedPane
+-- JSlider, JProgressBar, JMenuBar, JPopupMenu
+-- JInternalFrame
The top-level containers JFrame, JDialog and JApplet are heavyweight; all other Swing components extend JComponent and are lightweight.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
Questions from TU BSc CSIT 2077 Advanced Java Programming (TU IOST board exam, 2077), TU BSc CSIT 2078 Advanced Java Programming (TU IOST board exam, 2078), TU BSc CSIT 2079 Advanced Java Programming (TU IOST board exam, 2079), TU BSc CSIT 2080 Advanced Java Programming (TU IOST board exam, 2080), TU BSc CSIT 2081 Advanced Java Programming (TU IOST board exam, 2081), TU BSc CSIT 2082 Advanced Java Programming (TU IOST board exam, 2082), TU BSc CSIT 2078 Data Warehousing and Data Mining (TU IOST board exam, 2078), TU BSc CSIT 2079 Data Warehousing and Data Mining (TU IOST board exam, 2079), TU BSc CSIT 2080 Data Warehousing and Data Mining (TU IOST board exam, 2080), TU BSc CSIT 2081 Data Warehousing and Data Mining (TU IOST board exam, 2081), TU BSc CSIT 2082 Data Warehousing and Data Mining (TU IOST board exam, 2082), TU BSc CSIT 2079 International Marketing (TU IOST board exam, 2079), TU BSc CSIT 2080 International Marketing (TU IOST board exam, 2080), TU BSc CSIT 2082 International Marketing (TU IOST board exam, 2082), TU BSc CSIT 2080 Network Security (TU IOST board exam, 2080), TU BSc CSIT 2082 Network Security (TU IOST board exam, 2082), TU BSc CSIT 2078 Principles of Management (TU IOST board exam, 2078), TU BSc CSIT 2079 Principles of Management (TU IOST board exam, 2079), TU BSc CSIT 2080 Principles of Management (TU IOST board exam, 2080), TU BSc CSIT 2081 Principles of Management (TU IOST board exam, 2081), TU BSc CSIT 2082 Principles of Management (TU IOST board exam, 2082), TU BSc CSIT 2078 Software Project Management (TU IOST board exam, 2078), TU BSc CSIT 2079 Software Project Management (TU IOST board exam, 2079), TU BSc CSIT 2080 Software Project Management (TU IOST board exam, 2080), TU BSc CSIT 2081 Software Project Management (TU IOST board exam, 2081) and TU BSc CSIT 2082 Software Project Management (TU IOST board exam, 2082). Answers are written for this site; check them against your class notes.