Skip to main content

Chapter 1

Advanced Java Programming

TU BIT past exam questions

Past questions and answers

36 questions set from this chapter. Most repeated first.

  • 2080 · 10 marks

Explain why interfaces are needed. Define a Shape interface with an area() method. Create Rectangle (length, breadth) and Circle (radius) classes that implement it, then create objects of both and display their areas.

Answer

Why interfaces are needed

An interface is a contract that lists method signatures (and constants) without implementation. Classes that implement the interface must provide the method bodies. Interfaces are needed because:

  • Abstraction: they separate what an object does from how it does it.
  • Multiple inheritance of type: Java classes can extend only one class but can implement many interfaces.
  • Loose coupling and polymorphism: code can be written against the interface type (Shape), and any implementing class can be plugged in without changing that code.
  • Standard contract: unrelated classes can guarantee a common set of behaviours (e.g. Comparable, Runnable).

Program

interface Shape {
    double area();
}

class Rectangle implements Shape {
    private double length, breadth;

    Rectangle(double length, double breadth) {
        this.length = length;
        this.breadth = breadth;
    }

    public double area() {
        return length * breadth;
    }
}

class Circle implements Shape {
    private double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    public double area() {
        return Math.PI * radius * radius;
    }
}

public class ShapeTest {
    public static void main(String[] args) {
        Shape r = new Rectangle(5, 3);
        Shape c = new Circle(2);

        System.out.println("Area of rectangle = " + r.area());
        System.out.printf("Area of circle = %.2f%n", c.area());
    }
}

Output

Area of rectangle = 15.0
Area of circle = 12.57

Here Shape references hold both objects, and the call area() is resolved at run time to the correct implementation (runtime polymorphism). The area of the rectangle is l×b=5×3=15l \times b = 5 \times 3 = 15 and that of the circle is πr2=π×22≈12.57\pi r^2 = \pi \times 2^2 \approx 12.57.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 10 marks

Write a Java program with a UI of three labels and three text boxes (First Number, Second Number, Result) and four buttons (Add, Subtract, Multiply, Divide), handling each button's event.

Answer

The program uses Swing, with an ActionListener registered on each of the four buttons.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Calculator extends JFrame implements ActionListener {
    JLabel l1, l2, l3;
    JTextField t1, t2, t3;
    JButton add, sub, mul, div;

    public Calculator() {
        setTitle("Calculator");
        setLayout(new GridLayout(5, 2, 5, 5));

        l1 = new JLabel("First Number");
        l2 = new JLabel("Second Number");
        l3 = new JLabel("Result");
        t1 = new JTextField();
        t2 = new JTextField();
        t3 = new JTextField();
        t3.setEditable(false);
        add = new JButton("Add");
        sub = new JButton("Subtract");
        mul = new JButton("Multiply");
        div = new JButton("Divide");

        add(l1); add(t1);
        add(l2); add(t2);
        add(l3); add(t3);
        add(this.add); add(sub);
        add(mul); add(div);

        this.add.addActionListener(this);
        sub.addActionListener(this);
        mul.addActionListener(this);
        div.addActionListener(this);

        setSize(350, 250);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        try {
            double a = Double.parseDouble(t1.getText());
            double b = Double.parseDouble(t2.getText());
            double r = 0;
            Object src = e.getSource();
            if (src == add) r = a + b;
            else if (src == sub) r = a - b;
            else if (src == mul) r = a * b;
            else if (src == div) {
                if (b == 0) {
                    t3.setText("Cannot divide by zero");
                    return;
                }
                r = a / b;
            }
            t3.setText(String.valueOf(r));
        } catch (NumberFormatException ex) {
            t3.setText("Invalid input");
        }
    }

    public static void main(String[] args) {
        new Calculator();
    }
}

When a button is clicked, actionPerformed() is called; e.getSource() identifies the button, the two numbers are read from the text fields, the operation is performed and the result is shown in the third text box.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 10 marks

List the tags used in JSP programs. Explain how HTML forms are processed using JSP, with an example.

Answer

Tags used in JSP

TypeSyntaxPurpose
Declaration<%! int count = 0; %>declares variables/methods of the servlet class
Scriptlet<% ... %>Java code placed in _jspService()
Expression<%= expression %>value is evaluated and printed to output
Comment<%-- comment --%>JSP comment, not sent to client
Directive<%@ page ... %>, <%@ include ... %>, <%@ taglib ... %>give instructions to the container
Action<jsp:include>, <jsp:forward>, <jsp:useBean>, <jsp:setProperty>, <jsp:getProperty>standard XML-style actions
Expression Language${param.name}access data without Java code

Processing HTML forms using JSP

The form submits its fields to a JSP page through GET or POST. The JSP reads the values using the implicit request object (request.getParameter("fieldName")), processes them, and writes the response.

form.html

<form action="welcome.jsp" method="post">
    Name: <input type="text" name="name"><br>
    Age: <input type="text" name="age"><br>
    <input type="submit" value="Submit">
</form>

welcome.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<body>
<%
    String name = request.getParameter("name");
    int age = Integer.parseInt(request.getParameter("age"));
%>
<h3>Hello, <%= name %></h3>
<p>Next year you will be <%= age + 1 %> years old.</p>
</body>
</html>

Steps: (1) the user fills in the form and clicks Submit; (2) the browser sends an HTTP request with the field names and values; (3) the container translates the JSP to a servlet and calls it; (4) the JSP reads parameters with request.getParameter(), validates/processes them; (5) the generated HTML is returned to the browser.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Describe constructor chaining with an example.

Answer

Constructor chaining is the process of calling one constructor from another. It can happen:

  • within the same class using this(...), and
  • between a subclass and its superclass using super(...).

The call to this(...) or super(...) must be the first statement of the constructor. If it is not written, the compiler inserts super() automatically, so constructors of all ancestors execute from the top of the hierarchy down. Chaining avoids code duplication.

class Person {
    String name;
    Person() {
        this("Unknown");              // chain within the class
        System.out.println("Person()");
    }
    Person(String name) {
        this.name = name;
        System.out.println("Person(String)");
    }
}

class Student extends Person {
    int roll;
    Student() {
        this(1);                       // chain within the class
        System.out.println("Student()");
    }
    Student(int roll) {
        super("Ram");                  // chain to superclass
        this.roll = roll;
        System.out.println("Student(int)");
    }
}

public class Test {
    public static void main(String[] args) {
        new Student();
    }
}

Output order: Person(String), Student(int), Student().

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Write a multithreaded program by extending the Thread class, creating at least three threads.

Answer

class MyThread extends Thread {
    private String name;

    MyThread(String name) {
        super(name);
        this.name = name;
    }

    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println(name + " : " + i);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                System.out.println(name + " interrupted");
            }
        }
        System.out.println(name + " finished");
    }
}

public class ThreadDemo {
    public static void main(String[] args) {
        MyThread t1 = new MyThread("Thread-A");
        MyThread t2 = new MyThread("Thread-B");
        MyThread t3 = new MyThread("Thread-C");

        t1.start();
        t2.start();
        t3.start();
    }
}

The class extends Thread and overrides run(), which holds the code for the thread. Calling start() (not run()) creates a new call stack and makes the JVM call run() concurrently. The three threads run together, so their output lines interleave; the order may vary between runs.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

What is a layout manager? Explain how FlowLayout works, with an example.

Answer

Layout manager

A layout manager is an object that controls how components are sized and positioned inside a container (Panel, Frame, JPanel). It lets the interface adapt to different screen sizes and platforms instead of using fixed pixel coordinates. A layout is set with setLayout(). Examples: FlowLayout, BorderLayout, GridLayout, CardLayout, GridBagLayout.

FlowLayout

FlowLayout places components one after another in a row, left to right, in the order they are added. When a row is full, it wraps to the next row. Each row is centred by default (alignment can be LEFT, RIGHT or CENTER), and components keep their preferred size. It is the default layout of Panel/JPanel. Constructors: FlowLayout(), FlowLayout(int align), FlowLayout(int align, int hgap, int vgap).

import javax.swing.*;
import java.awt.*;

public class FlowDemo {
    public static void main(String[] args) {
        JFrame f = new JFrame("FlowLayout");
        f.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
        for (int i = 1; i <= 5; i++) {
            f.add(new JButton("Button " + i));
        }
        f.setSize(300, 150);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

If the window is resized narrower, the buttons re-flow onto additional rows.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Describe exception handling with an example.

Answer

An exception is an abnormal event during execution that disrupts the normal flow of the program (e.g. divide by zero, file not found, array index out of bounds). Exception handling is the mechanism to catch and deal with such events so that the program does not terminate abruptly.

Java uses five keywords:

  • try: encloses code that may throw an exception;
  • catch: handles a particular exception type;
  • finally: block that always executes (used for clean-up);
  • throw: explicitly throws an exception;
  • throws: declares exceptions a method may pass to its caller.
public class ExceptionDemo {
    public static void main(String[] args) {
        int[] a = new int[3];
        try {
            int x = 10 / 0;                // ArithmeticException
            a[5] = 1;                      // not reached
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic error: " + e.getMessage());
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Index error: " + e.getMessage());
        } finally {
            System.out.println("finally block executed");
        }
        System.out.println("Program continues");
    }
}

Output: Arithmetic error: / by zero, then finally block executed, then Program continues. Control jumps from the faulty statement to the matching catch, then finally runs, and execution continues normally.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

How do PreparedStatements differ from Statements? Explain their use with an example.

Answer

Differences

StatementPreparedStatement
Created with con.createStatement()Created with con.prepareStatement(sql)
SQL is compiled each time it is executedSQL is precompiled once and reused, so it is faster for repeated execution
Values are concatenated into the SQL stringUses ? placeholders set with setInt(), setString(), etc.
Open to SQL injectionPrevents SQL injection because parameters are escaped
Suited to static queries run onceSuited to parameterised, repeated queries

Example

import java.sql.*;

public class PrepDemo {
    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection con = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/school", "root", "");

        PreparedStatement ps = con.prepareStatement(
            "INSERT INTO student(id, name) VALUES(?, ?)");
        ps.setInt(1, 101);
        ps.setString(2, "Sita");
        int rows = ps.executeUpdate();
        System.out.println(rows + " row inserted");

        PreparedStatement q = con.prepareStatement(
            "SELECT * FROM student WHERE id = ?");
        q.setInt(1, 101);
        ResultSet rs = q.executeQuery();
        while (rs.next()) {
            System.out.println(rs.getInt("id") + " " + rs.getString("name"));
        }
        con.close();
    }
}

The ? marks are filled by the setXxx() methods (index starts at 1), then executeUpdate() or executeQuery() is called.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Discuss the steps for writing JavaFX programs.

Answer

Steps for writing a JavaFX program:

  1. Extend javafx.application.Application and override the abstract method start(Stage primaryStage).
  2. Create UI controls (nodes) such as Label, Button, TextField.
  3. Create a layout pane (HBox, VBox, BorderPane, GridPane, etc.) and add the nodes to it.
  4. Create a Scene with the root layout and size: new Scene(root, 400, 300).
  5. Handle events by attaching handlers, e.g. button.setOnAction(e -> ...).
  6. Set the scene on the Stage (primaryStage.setScene(scene)), set a title, and call primaryStage.show().
  7. Launch the application by calling Application.launch(args) from main().
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class HelloFX extends Application {
    @Override
    public void start(Stage stage) {
        Label label = new Label("Welcome");
        Button btn = new Button("Click me");
        btn.setOnAction(e -> label.setText("Button clicked"));
        VBox root = new VBox(10, label, btn);
        stage.setScene(new Scene(root, 300, 200));
        stage.setTitle("JavaFX Demo");
        stage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }
}

The structure is: Stage (window) contains Scene, Scene contains the root node, which contains the scene graph of nodes.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Write a TCP socket program in which the client sends an integer and the server responds whether it is positive or negative.

Answer

Server

import java.io.*;
import java.net.*;

public class NumServer {
    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(5000);
        System.out.println("Server waiting...");
        Socket s = ss.accept();
        DataInputStream in = new DataInputStream(s.getInputStream());
        DataOutputStream out = new DataOutputStream(s.getOutputStream());

        int n = in.readInt();
        String reply;
        if (n > 0) reply = n + " is positive";
        else if (n < 0) reply = n + " is negative";
        else reply = "Zero is neither positive nor negative";
        out.writeUTF(reply);

        s.close();
        ss.close();
    }
}

Client

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class NumClient {
    public static void main(String[] args) throws Exception {
        Socket s = new Socket("localhost", 5000);
        DataOutputStream out = new DataOutputStream(s.getOutputStream());
        DataInputStream in = new DataInputStream(s.getInputStream());

        Scanner sc = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        int n = sc.nextInt();
        out.writeInt(n);

        System.out.println("Server says: " + in.readUTF());
        s.close();
    }
}

Start the server first, then the client. The client sends the integer with writeInt(), the server reads it, tests its sign and returns a message with writeUTF().

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

How can distributed programs be written in Java? Explain RMI architecture.

Answer

Distributed programs in Java

A distributed program has parts running on different JVMs/machines that cooperate over a network. In Java this can be done using:

  • Sockets (TCP/UDP): low-level communication of bytes between processes;
  • RMI (Remote Method Invocation): invoke methods on objects residing in another JVM as if they were local;
  • CORBA: language-independent distributed objects through an ORB;
  • Web services (SOAP/REST) and servlets/EJB/JMS for enterprise-level distribution.

RMI architecture

RMI has three layers between client and server:

  1. Stub and Skeleton layer: the stub is the client-side proxy of the remote object; it marshals (serialises) arguments, sends the call, and unmarshals the result. The skeleton is the server-side counterpart that unmarshals the request and calls the actual object (in modern Java the skeleton is replaced by reflection).
  2. Remote Reference Layer: manages references to remote objects and the invocation semantics (unicast, etc.).
  3. Transport Layer: sets up and manages the TCP connection between the JVMs.

A registry (rmiregistry, port 1099) is a naming service in which the server binds the remote object under a name (Naming.rebind), and the client looks it up (Naming.lookup) to obtain the stub.

Flow: server creates the remote object and binds it to the registry; client looks up the name and gets the stub; client calls a method on the stub; the stub sends the request through the layers to the server, the object executes, and the result returns the same way.

A remote interface must extend java.rmi.Remote, and each method must declare throws RemoteException.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Write short notes on: (a) the final keyword, (b) the Object class.

Answer

(a) The final keyword

final is a modifier that restricts change:

  • final variable: its value can be assigned only once, so it is a constant (final double PI = 3.14;).
  • final method: cannot be overridden by subclasses.
  • final class: cannot be extended (e.g. String, Integer).
  • final parameter/reference: the reference cannot be reassigned, though the object's contents may still change.
final class A { }
class B {
    final int MAX = 10;
    final void show() { }
}

(b) The Object class

java.lang.Object is the root of the Java class hierarchy; every class directly or indirectly extends it. Hence its methods are available to all objects:

  • toString(): string representation of the object;
  • equals(Object o): compares objects for equality;
  • hashCode(): integer hash used by hash-based collections;
  • getClass(): returns the runtime class;
  • clone(): creates a copy of the object;
  • finalize(): called before garbage collection;
  • wait(), notify(), notifyAll(): thread synchronisation.

A variable of type Object can hold a reference to any object, which is the basis of generic code written before generics.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 10 marks

Discuss about any four servlet APIs. Design a form in JSP to take the necessary information about an employee and when the user click submit button, it will be displayed in second page.

Answer

Four servlet APIs

  1. javax.servlet.Servlet interface: the core interface defining the life-cycle methods init(ServletConfig), service(ServletRequest, ServletResponse) and destroy().
  2. HttpServlet class: extends GenericServlet and provides doGet(), doPost() etc. to handle HTTP requests; most servlets extend it.
  3. HttpServletRequest: gives access to request data: getParameter(), getParameterValues(), getHeader(), getSession(), getCookies().
  4. HttpServletResponse: used to build the reply: setContentType(), getWriter(), sendRedirect(), addCookie().

(Others: ServletConfig, ServletContext, HttpSession, RequestDispatcher, Cookie.)

Employee form in JSP

employee.jsp

<html>
<body>
<h3>Employee Information</h3>
<form action="display.jsp" method="post">
    Employee ID: <input type="text" name="id"><br><br>
    Name: <input type="text" name="name"><br><br>
    Address: <input type="text" name="address"><br><br>
    Post: <input type="text" name="post"><br><br>
    Salary: <input type="text" name="salary"><br><br>
    <input type="submit" value="Submit">
</form>
</body>
</html>

display.jsp

<html>
<body>
<h3>Employee Details</h3>
<table border="1">
<tr><td>ID</td><td><%= request.getParameter("id") %></td></tr>
<tr><td>Name</td><td><%= request.getParameter("name") %></td></tr>
<tr><td>Address</td><td><%= request.getParameter("address") %></td></tr>
<tr><td>Post</td><td><%= request.getParameter("post") %></td></tr>
<tr><td>Salary</td><td><%= request.getParameter("salary") %></td></tr>
</table>
</body>
</html>

On clicking Submit, the browser posts the fields to display.jsp, which reads them through the implicit request object and shows them on the second page.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 10 marks

When do we use JPanel? How do you add mnemonics and accelerators to menu items? Explain.

Answer

When do we use JPanel?

JPanel is a lightweight, general-purpose container. It is used:

  • to group related components (e.g. a set of buttons) and treat them as one unit;
  • to apply a different layout manager to a part of the window (e.g. a GridLayout panel placed inside the BorderLayout of a frame);
  • as a drawing surface by overriding paintComponent(Graphics g) for custom graphics;
  • to build complex, nested user interfaces and as the content pane of frames and dialogs.

Its default layout is FlowLayout.

Mnemonics and accelerators

  • A mnemonic is a single underlined letter in a menu or menu item. Together with the Alt key it lets the user open/choose the item by keyboard when the menu is visible: setMnemonic(KeyEvent.VK_F) or new JMenuItem("Open", KeyEvent.VK_O).
  • An accelerator is a keyboard shortcut that triggers a menu item directly, without opening the menu, e.g. Ctrl+O. It is set with setAccelerator(KeyStroke) and works only on JMenuItem, not on top-level JMenu.
import javax.swing.*;
import java.awt.event.*;

public class MenuDemo {
    public static void main(String[] args) {
        JFrame f = new JFrame("Menu");
        JMenuBar bar = new JMenuBar();

        JMenu file = new JMenu("File");
        file.setMnemonic(KeyEvent.VK_F);          // Alt+F

        JMenuItem open = new JMenuItem("Open");
        open.setMnemonic(KeyEvent.VK_O);          // underlined O
        open.setAccelerator(KeyStroke.getKeyStroke(
            KeyEvent.VK_O, ActionEvent.CTRL_MASK)); // Ctrl+O

        JMenuItem exit = new JMenuItem("Exit", KeyEvent.VK_X);
        exit.setAccelerator(KeyStroke.getKeyStroke(
            KeyEvent.VK_Q, ActionEvent.CTRL_MASK)); // Ctrl+Q
        exit.addActionListener(e -> System.exit(0));

        file.add(open);
        file.add(exit);
        bar.add(file);
        f.setJMenuBar(bar);
        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 · 10 marks

How do you create inner class and anonymous inner class? Create a class EMPLOYEE with data members Emp_ID, Name and Occupation, and write those objects to the file DOC.DAT whose occupations is doctor.

Answer

Inner class

An inner (member) class is a class declared inside another class. It can access all members of the outer class, including private ones. An instance needs an outer instance:

class Outer {
    private int x = 10;
    class Inner {
        void show() { System.out.println("x = " + x); }
    }
}
// creation
Outer o = new Outer();
Outer.Inner i = o.new Inner();
i.show();

Anonymous inner class

A class without a name, declared and instantiated in one expression; it either extends a class or implements an interface, and is used for one-time use such as event handlers.

Runnable r = new Runnable() {
    public void run() {
        System.out.println("Anonymous class running");
    }
};
new Thread(r).start();

Writing doctor employees to DOC.DAT

The class must be Serializable so objects can be written with ObjectOutputStream.

import java.io.*;
import java.util.*;

class EMPLOYEE implements Serializable {
    int Emp_ID;
    String Name;
    String Occupation;

    EMPLOYEE(int id, String name, String occ) {
        Emp_ID = id;
        Name = name;
        Occupation = occ;
    }
}

public class WriteDoctors {
    public static void main(String[] args) throws Exception {
        List<EMPLOYEE> list = new ArrayList<>();
        list.add(new EMPLOYEE(1, "Ram", "doctor"));
        list.add(new EMPLOYEE(2, "Sita", "engineer"));
        list.add(new EMPLOYEE(3, "Hari", "doctor"));
        list.add(new EMPLOYEE(4, "Gita", "teacher"));

        ObjectOutputStream oos =
            new ObjectOutputStream(new FileOutputStream("DOC.DAT"));
        for (EMPLOYEE e : list) {
            if (e.Occupation.equalsIgnoreCase("doctor")) {
                oos.writeObject(e);
            }
        }
        oos.close();
        System.out.println("Doctors written to DOC.DAT");
    }
}

Only the objects whose occupation is "doctor" (Ram and Hari) are written to the file.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Describe about any three types of JavaFX layouts.

Answer

A layout pane in JavaFX arranges child nodes automatically. Three common ones:

1. HBox: places its children in a single horizontal row, left to right. Spacing and padding are set with setSpacing() and setPadding().

HBox hb = new HBox(10, new Button("A"), new Button("B"), new Button("C"));

2. VBox: places its children in a single vertical column, top to bottom.

VBox vb = new VBox(10, new Label("Name"), new TextField());

3. BorderPane: divides the area into five regions: top, bottom, left, right and centre. Each region holds one node; the centre takes the remaining space.

BorderPane bp = new BorderPane();
bp.setTop(new Label("Header"));
bp.setCenter(new TextArea());
bp.setBottom(new Button("OK"));

Others include GridPane (rows and columns), FlowPane (wraps), StackPane (stacked on top of each other) and AnchorPane (anchored to edges).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Write a program to design a form with a button and label, such that the number of times the button is clicked will be displayed in label.

Answer

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ClickCounter extends JFrame implements ActionListener {
    JButton button;
    JLabel label;
    int count = 0;

    public ClickCounter() {
        setLayout(new FlowLayout());
        button = new JButton("Click Me");
        label = new JLabel("Clicks: 0");
        add(button);
        add(label);
        button.addActionListener(this);

        setTitle("Click Counter");
        setSize(250, 120);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        count++;
        label.setText("Clicks: " + count);
    }

    public static void main(String[] args) {
        new ClickCounter();
    }
}

Each click fires an ActionEvent; actionPerformed() increments the counter and updates the label text.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Explain the architecture of RMI.

Answer

RMI (Remote Method Invocation) lets an object in one JVM invoke methods of an object in another JVM. Its architecture has the following parts:

  1. Client and server applications: the client calls remote methods; the server hosts the remote object implementing a Remote interface.
  2. Stub: client-side proxy of the remote object. It marshals the method arguments, sends the request and unmarshals the return value, making the remote call look local.
  3. Skeleton: server-side entity that receives the request, unmarshals the parameters, invokes the real method and sends back the result (in Java 2 onward this is done through reflection).
  4. Remote Reference Layer (RRL): handles references to remote objects and the call semantics.
  5. Transport Layer: sets up TCP connections and carries the data between the two JVMs.
  6. RMI Registry: naming service (default port 1099) where the server binds the object by name and the client looks it up.

Working: (1) the server creates the remote object and registers it (Naming.rebind("rmi://host/Name", obj)); (2) the client looks it up (Naming.lookup) and receives the stub; (3) the client invokes a method on the stub; (4) the call travels through the RRL and transport layer to the server's skeleton; (5) the method executes and the result returns by the same path.

Arguments and results are passed by serialisation (objects must be Serializable), and remote methods throw RemoteException.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Write a program to show the use of mouse event.

Answer

import java.awt.*;
import java.awt.event.*;

public class MouseDemo extends Frame implements MouseListener, MouseMotionListener {
    String msg = "";
    int x = 0, y = 0;

    public MouseDemo() {
        addMouseListener(this);
        addMouseMotionListener(this);
        setSize(400, 300);
        setTitle("Mouse Events");
        setVisible(true);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) { System.exit(0); }
        });
    }

    public void mouseClicked(MouseEvent e)  { x = e.getX(); y = e.getY(); msg = "Mouse clicked";  repaint(); }
    public void mousePressed(MouseEvent e)  { x = e.getX(); y = e.getY(); msg = "Mouse pressed";  repaint(); }
    public void mouseReleased(MouseEvent e) { x = e.getX(); y = e.getY(); msg = "Mouse released"; repaint(); }
    public void mouseEntered(MouseEvent e)  { x = 20; y = 50; msg = "Mouse entered"; repaint(); }
    public void mouseExited(MouseEvent e)   { x = 20; y = 50; msg = "Mouse exited";  repaint(); }
    public void mouseDragged(MouseEvent e)  { x = e.getX(); y = e.getY(); msg = "Dragging"; repaint(); }
    public void mouseMoved(MouseEvent e)    { x = e.getX(); y = e.getY(); msg = "Moving at " + x + "," + y; repaint(); }

    public void paint(Graphics g) {
        g.drawString(msg, x, y);
    }

    public static void main(String[] args) {
        new MouseDemo();
    }
}

The class implements MouseListener (click, press, release, enter, exit) and MouseMotionListener (drag, move), registers itself on the frame, and shows the event name at the pointer position.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Define package. What is the use of final keyword and finally block?

Answer

Package

A package is a named group of related classes and interfaces. It organises code, avoids name conflicts and provides access protection. It is declared with package mypack; as the first statement of a file and used with import mypack.ClassName;. Examples: java.util, java.io, javax.swing.

package mypack;
public class Hello {
    public void show() { System.out.println("Hello"); }
}

Use of final keyword

  • final variable: constant, assigned once;
  • final method: cannot be overridden;
  • final class: cannot be inherited.

finally block

finally is a block placed after try/catch that always executes, whether or not an exception occurred or was caught. It is used for clean-up such as closing files, database connections or sockets.

try {
    int a = 5 / 0;
} catch (ArithmeticException e) {
    System.out.println("Error");
} finally {
    System.out.println("Always executed");
}

(final is a modifier, finally is an exception-handling block; finalize() is a method called by the garbage collector.)

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Explain the architecture of JDBC and list the JDBC driver types.

Answer

JDBC architecture

JDBC (Java Database Connectivity) is the API through which Java programs access relational databases. It has two layers:

  1. JDBC API layer: used by the application. Main classes/interfaces: DriverManager, Connection, Statement, PreparedStatement, CallableStatement, ResultSet, SQLException.
  2. JDBC Driver layer: the driver implementing the API for a particular database; it translates JDBC calls into database-specific calls.

Flow: Java application, then JDBC API, then DriverManager, then the JDBC driver, then the database.

JDBC driver types

  • Type 1: JDBC-ODBC bridge driver: converts JDBC calls to ODBC calls; needs ODBC on the client; slow and removed from modern Java.
  • Type 2: Native-API (partly Java) driver: converts calls to the database's native client library; requires native libraries installed on the client.
  • Type 3: Network-protocol (middleware) driver: sends calls to a middleware server which translates them to database calls; entirely Java on the client.
  • Type 4: Thin (pure Java) driver: converts JDBC calls directly to the database's network protocol; fastest and most portable, and the most widely used (e.g. MySQL Connector/J).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Write the steps of writing socket program using UDP.

Answer

UDP is connectionless and uses DatagramSocket and DatagramPacket.

Server steps

  1. Create a DatagramSocket bound to a port: new DatagramSocket(9876).
  2. Create a byte array buffer and a DatagramPacket to receive data.
  3. Call socket.receive(packet) (blocks until a datagram arrives).
  4. Extract the data and the sender's address and port from the packet.
  5. Optionally build a reply DatagramPacket(data, len, address, port) and send it with socket.send().
  6. Close the socket.

Client steps

  1. Create a DatagramSocket() (any free port).
  2. Get the server address: InetAddress.getByName("localhost").
  3. Convert the message to bytes and create new DatagramPacket(data, data.length, address, 9876).
  4. Send it with socket.send(packet).
  5. Optionally receive the reply with socket.receive().
  6. Close the socket.
// client fragment
DatagramSocket ds = new DatagramSocket();
byte[] b = "Hello".getBytes();
ds.send(new DatagramPacket(b, b.length,
        InetAddress.getByName("localhost"), 9876));
ds.close();

No connection is established, and delivery or ordering is not guaranteed.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Define scriptlets. Discuss about JSP access models.

Answer

Scriptlet

A scriptlet is a block of Java code embedded in a JSP page between <% and %>. It is copied into the _jspService() method of the generated servlet and is executed on every request. It can declare local variables, use control structures and use implicit objects.

<%
    int n = Integer.parseInt(request.getParameter("n"));
    for (int i = 1; i <= 5; i++) {
        out.println(n * i + "<br>");
    }
%>

JSP access models

JSP access models describe how requests are processed using JSPs and servlets:

  • Model 1 architecture: the request goes directly to a JSP page, which contains presentation as well as business and database logic (possibly with JavaBeans). It is simple and good for small applications, but logic and presentation are mixed, so it is hard to maintain and scale.
  • Model 2 architecture (MVC): the request goes first to a Servlet (controller), which processes it, invokes the model (JavaBeans/DAO classes holding data and business logic), and then forwards to a JSP (view) that only presents the result. It separates concerns, gives better maintainability, reuse and control of navigation, and is the basis of frameworks such as Struts and Spring MVC.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Why do we need ports in socket programming? What types of instructions are written in try block?

Answer

Why ports are needed

An IP address identifies a host, but a host runs many network applications at once. A port (a 16-bit number, 0 to 65535) identifies a particular process or service on that host. Ports let the operating system deliver incoming data to the correct application, so several programs can use the network simultaneously. Together, IP address plus port form a socket address. Well-known ports include 80 (HTTP), 443 (HTTPS), 21 (FTP) and 25 (SMTP); ports 0-1023 are reserved, and programmers normally use ports above 1024.

Instructions in a try block

The try block contains the statements that may throw an exception, so that they can be handled by the following catch blocks. In socket programming these are, for example:

  • creating a ServerSocket or Socket (may throw IOException, UnknownHostException);
  • accept(), reading from or writing to streams;
  • file operations, database calls, type conversions (Integer.parseInt), array accesses and divisions.

Statements that depend on the risky code are also placed inside try, so they are skipped if an exception occurs. Clean-up code goes in finally.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 10 marks

List some features of Java. What are the types of exception? Write a program to take input an integer from the user and if the given integer is negative throw the exception.

Answer

Features of Java

  • Simple: syntax similar to C/C++ without pointers, operator overloading or multiple inheritance of classes.
  • Object-oriented: supports encapsulation, inheritance, polymorphism and abstraction.
  • Platform independent: source compiles to bytecode that runs on any JVM ("write once, run anywhere").
  • Robust: strong type checking, exception handling and automatic garbage collection.
  • Secure: no explicit pointers, bytecode verifier and security manager.
  • Multithreaded: built-in support for concurrent programming.
  • Distributed: networking, RMI and similar APIs.
  • High performance through JIT compilation, and dynamic.

Types of exception

  1. Checked exceptions: checked at compile time; must be handled or declared (e.g. IOException, SQLException, ClassNotFoundException).
  2. Unchecked (runtime) exceptions: subclasses of RuntimeException; not checked at compile time (e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException).
  3. Errors: serious problems of the JVM that should not be caught (e.g. OutOfMemoryError, StackOverflowError).

Program: throw an exception for a negative integer

import java.util.Scanner;

class NegativeNumberException extends Exception {
    NegativeNumberException(String msg) {
        super(msg);
    }
}

public class NegativeTest {
    static void check(int n) throws NegativeNumberException {
        if (n < 0) {
            throw new NegativeNumberException(n + " is negative");
        }
        System.out.println(n + " is valid");
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        int n = sc.nextInt();
        try {
            check(n);
        } catch (NegativeNumberException e) {
            System.out.println("Exception: " + e.getMessage());
        }
    }
}

For input -5 the output is Exception: -5 is negative; for 7 it is 7 is valid.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 10 marks

Distinguish between component and containers. What do you mean by keyboard mnemonics and accelerators? Illustrate the concept of Grid layout with an example.

Answer

Component vs container

ComponentContainer
Any visual element with a graphical representation that the user interacts with (Button, Label, TextField, Checkbox)A special component that can hold and arrange other components
Cannot hold other componentsHolds components using add() and a layout manager
Subclass of java.awt.ComponentSubclass of java.awt.Container (itself a Component)
Examples: JButton, JLabelExamples: JFrame, JPanel, JDialog, Applet

Keyboard mnemonics and accelerators

  • A mnemonic is an underlined letter of a menu or menu item that, combined with Alt, selects it from the keyboard while the menu is accessible: menu.setMnemonic(KeyEvent.VK_F).
  • An accelerator is a shortcut key combination (e.g. Ctrl+S) that activates a JMenuItem directly without opening the menu: item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK)).

GridLayout

GridLayout arranges components in a rectangular grid of equal-sized cells, filling row by row, left to right, in the order of addition. Constructor: GridLayout(rows, cols, hgap, vgap). Resizing the container resizes all cells equally.

import javax.swing.*;
import java.awt.*;

public class GridDemo {
    public static void main(String[] args) {
        JFrame f = new JFrame("GridLayout");
        f.setLayout(new GridLayout(3, 3, 5, 5));
        for (int i = 1; i <= 9; i++) {
            f.add(new JButton(String.valueOf(i)));
        }
        f.setSize(300, 300);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

This produces a 3 x 3 keypad of nine equally sized buttons.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 10 marks

What are the purposes of JSP implicit objects? Describe the methods of writing servlet program with example.

Answer

Purposes of JSP implicit objects

Implicit objects are created by the container and are available in scriptlets without declaration.

ObjectTypePurpose
requestHttpServletRequestreads form parameters, headers, cookies
responseHttpServletResponsesets headers/content type, redirects
outJspWriterwrites output to the page
sessionHttpSessionstores per-user data across requests
applicationServletContextdata shared by the whole web application
configServletConfigservlet configuration/init parameters
pageContextPageContextaccess to all scopes and other implicit objects
pageObjectreference to the current servlet instance (this)
exceptionThrowableavailable in error pages, holds the exception

Methods of writing a servlet program

A servlet can be written by:

  1. implementing the javax.servlet.Servlet interface (all five methods must be written);
  2. extending GenericServlet (protocol independent, override service());
  3. extending HttpServlet (most common; override doGet() / doPost()).
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        String name = req.getParameter("name");
        out.println("<html><body>");
        out.println("<h2>Hello, " + name + "</h2>");
        out.println("</body></html>");
    }
}

It is mapped in web.xml (or with @WebServlet("/hello")) and invoked as /hello?name=Ram. The container calls init() once, service()/doGet() for each request, and destroy() at the end.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

How do you access file randomly? Give an example.

Answer

Random access means reading or writing at any position in a file without processing it sequentially. Java provides the RandomAccessFile class, which maintains a file pointer that can be moved using seek(long pos).

Modes: "r" (read only) and "rw" (read and write). Useful methods: seek(), getFilePointer(), length(), read(), readInt(), readLine(), write(), writeInt(), writeUTF().

import java.io.*;

public class RandomDemo {
    public static void main(String[] args) throws IOException {
        RandomAccessFile raf = new RandomAccessFile("data.dat", "rw");

        // write five integers (4 bytes each)
        for (int i = 1; i <= 5; i++) {
            raf.writeInt(i * 10);
        }

        // read the 3rd integer directly: offset = (3 - 1) * 4
        raf.seek(2 * 4);
        System.out.println("3rd value = " + raf.readInt());   // 30

        // overwrite the 2nd integer
        raf.seek(1 * 4);
        raf.writeInt(99);

        raf.seek(0);
        while (raf.getFilePointer() < raf.length()) {
            System.out.print(raf.readInt() + " ");            // 10 99 30 40 50
        }
        raf.close();
    }
}

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

Design a form that contains two text fields and two buttons with caption 'OK' and 'CANCEL' using AWT.

Answer

import java.awt.*;
import java.awt.event.*;

public class SimpleForm extends Frame implements ActionListener {
    TextField tf1, tf2;
    Button ok, cancel;

    public SimpleForm() {
        setLayout(new FlowLayout());
        tf1 = new TextField(20);
        tf2 = new TextField(20);
        ok = new Button("OK");
        cancel = new Button("CANCEL");

        add(tf1);
        add(tf2);
        add(ok);
        add(cancel);

        ok.addActionListener(this);
        cancel.addActionListener(this);

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                dispose();
            }
        });

        setTitle("AWT Form");
        setSize(300, 150);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == ok) {
            System.out.println("Text 1: " + tf1.getText());
            System.out.println("Text 2: " + tf2.getText());
        } else {
            tf1.setText("");
            tf2.setText("");
        }
    }

    public static void main(String[] args) {
        new SimpleForm();
    }
}

The frame holds two TextFields and two Buttons in a FlowLayout. OK prints the contents and CANCEL clears both fields.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

How do you connect database using JSP?

Answer

A JSP page can connect to a database using JDBC code written in a scriptlet (or better, in a JavaBean/DAO class called from the JSP).

Steps:

  1. Place the JDBC driver JAR (e.g. MySQL Connector/J) in WEB-INF/lib.
  2. Import java.sql.* with the page directive.
  3. Load the driver: Class.forName(...).
  4. Get a Connection with DriverManager.getConnection(url, user, password).
  5. Create a Statement / PreparedStatement and execute the query.
  6. Process the ResultSet and print it.
  7. Close the resources.
<%@ page import="java.sql.*" %>
<html>
<body>
<table border="1">
<tr><th>ID</th><th>Name</th></tr>
<%
    Connection con = null;
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        con = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/school", "root", "");
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery("SELECT id, name FROM student");
        while (rs.next()) {
%>
<tr><td><%= rs.getInt("id") %></td><td><%= rs.getString("name") %></td></tr>
<%
        }
    } catch (Exception e) {
        out.println("Error: " + e.getMessage());
    } finally {
        if (con != null) con.close();
    }
%>
</table>
</body>
</html>

An alternative is the JSTL SQL tags (<sql:setDataSource>, <sql:query>).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

Write a program to illustrate the concept of Mouse Events.

Answer

Mouse events are generated when the user presses, releases, clicks, moves or drags the mouse or when it enters or leaves a component. They are handled by:

  • MouseListener: mouseClicked, mousePressed, mouseReleased, mouseEntered, mouseExited;
  • MouseMotionListener: mouseDragged, mouseMoved.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MouseEventDemo extends JFrame implements MouseListener, MouseMotionListener {
    JLabel status = new JLabel("Perform a mouse action");

    public MouseEventDemo() {
        add(status, BorderLayout.SOUTH);
        addMouseListener(this);
        addMouseMotionListener(this);
        setSize(400, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void mouseClicked(MouseEvent e)  { status.setText("Clicked at (" + e.getX() + "," + e.getY() + ")"); }
    public void mousePressed(MouseEvent e)  { status.setText("Pressed"); }
    public void mouseReleased(MouseEvent e) { status.setText("Released"); }
    public void mouseEntered(MouseEvent e)  { status.setText("Mouse entered"); }
    public void mouseExited(MouseEvent e)   { status.setText("Mouse exited"); }
    public void mouseDragged(MouseEvent e)  { status.setText("Dragged to (" + e.getX() + "," + e.getY() + ")"); }
    public void mouseMoved(MouseEvent e)    { status.setText("Moved to (" + e.getX() + "," + e.getY() + ")"); }

    public static void main(String[] args) {
        new MouseEventDemo();
    }
}

The frame registers itself as listener, and each callback shows the event and the pointer coordinates (getX(), getY()) in the label.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

Describe any two JavaFX layouts.

Answer

1. HBox: a layout pane that arranges its children in one horizontal row from left to right. Spacing between nodes is set with the constructor or setSpacing(), and padding with setPadding().

HBox box = new HBox(10);
box.getChildren().addAll(new Button("Save"), new Button("Cancel"));

2. GridPane: arranges nodes in a flexible grid of rows and columns. Each node is added with its column and row index, and may span several cells. It is suited to forms.

GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.add(new Label("Name:"), 0, 0);
grid.add(new TextField(), 1, 0);
grid.add(new Label("Age:"), 0, 1);
grid.add(new TextField(), 1, 1);

Other layouts are VBox, BorderPane, FlowPane, StackPane and AnchorPane.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

How do you handle multiple results in JDBC? Explain.

Answer

Some statements (typically stored procedures or dynamic SQL) can return more than one result, i.e. several ResultSets and/or update counts. JDBC handles this with the execute() method of Statement, together with getResultSet(), getUpdateCount() and getMoreResults().

Procedure:

  1. Call boolean hasResult = stmt.execute(sql). It returns true if the first result is a ResultSet, false if it is an update count (or there are no results).
  2. Loop while there are results:
    • if the current result is a ResultSet, get it with stmt.getResultSet() and process it;
    • otherwise get the count with stmt.getUpdateCount(); a value of -1 means no more results.
  3. Move to the next result with stmt.getMoreResults().
Statement stmt = con.createStatement();
boolean isRs = stmt.execute("CALL getStudentsAndCourses()");
while (true) {
    if (isRs) {
        ResultSet rs = stmt.getResultSet();
        while (rs.next()) {
            System.out.println(rs.getString(1));
        }
    } else {
        int count = stmt.getUpdateCount();
        if (count == -1) break;           // no more results
        System.out.println("Rows affected: " + count);
    }
    isRs = stmt.getMoreResults();
}

The same approach works with CallableStatement.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

Mention the steps to write the socket program using TCP.

Answer

TCP is connection-oriented, using ServerSocket and Socket from java.net.

Server side

  1. Create a ServerSocket on a port: new ServerSocket(5000).
  2. Wait for a client with accept(), which returns a Socket.
  3. Get the input and output streams: getInputStream() and getOutputStream(); wrap them in DataInputStream, BufferedReader or PrintWriter.
  4. Read the request and write the response.
  5. Close the streams and sockets.

Client side

  1. Create a Socket with the server's host and port: new Socket("localhost", 5000).
  2. Get the input and output streams of the socket.
  3. Send data to the server and read its response.
  4. Close the streams and socket.
// server
ServerSocket ss = new ServerSocket(5000);
Socket s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
out.println("Echo: " + in.readLine());
s.close(); ss.close();

The server must be started first, and exceptions (IOException) are handled in a try/catch block.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

Differentiate between RMI and CORBA.

Answer

RMICORBA
Remote Method Invocation, Java-specificCommon Object Request Broker Architecture, an OMG standard
Both client and server must be written in JavaClient and server can be in different languages (C++, Java, Python, etc.)
Interfaces are defined as Java interfaces extending RemoteInterfaces are defined in a neutral language, IDL (Interface Definition Language)
Uses the Java Remote Method Protocol (JRMP) (or RMI-IIOP)Uses IIOP through an Object Request Broker (ORB)
Uses stub/skeleton and the RMI registry as naming serviceUses stub/skeleton generated from IDL and the CORBA Naming Service
Objects can be passed by value (serialisation) and downloaded code can be usedMainly passes by reference; values are limited to IDL types
Simple and lightweightMore complex but more powerful and interoperable

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

What is Type 0 JDBC driver? Discuss about UDP.

Answer

Type 0 JDBC driver

There is no official "Type 0" JDBC driver. JDBC drivers are classified as Type 1 (JDBC-ODBC bridge), Type 2 (native API), Type 3 (network protocol) and Type 4 (thin, pure Java). "Type 0" is only an informal label sometimes used for the earliest or non-standard driver arrangements, such as a driver embedded directly in the database or application without the standard layers. For examination purposes, the standard four types should be named.

UDP (User Datagram Protocol)

UDP is a connectionless, unreliable transport protocol that sends independent packets called datagrams.

  • No connection is set up before sending; each datagram carries the destination address and port.
  • No guarantee of delivery, ordering or duplicate protection; no flow or congestion control.
  • Low overhead (8-byte header), so it is fast and suited to streaming, voice/video, DNS, games and broadcast.
  • In Java it is implemented with DatagramSocket (to send/receive) and DatagramPacket (the datagram), and InetAddress for addresses.

Compared with TCP, UDP is faster and simpler but not reliable.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

Questions from TU BIT 2080 Seventh Semester Advanced Java Programming (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2081 Seventh Semester Advanced Java Programming (TU IOST semester board exam, 2081 (BS), via StudyNp), TU BIT 2082 Seventh Semester Advanced Java Programming (TU IOST semester board exam, 2082 (BS), via StudyNp), TU BIT 2080 Seventh Semester Software Project Management (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2081 Seventh Semester Software Project Management (TU IOST semester board exam, 2081 (BS), via StudyNp), TU BIT 2082 Seventh Semester Software Project Management (TU IOST semester board exam, 2082 (BS), via StudyNp), TU BIT 2080 Seventh Semester E-Commerce (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2081 Seventh Semester E-Commerce (TU IOST semester board exam, 2081 (BS), via StudyNp), TU BIT 2082 Seventh Semester E-Commerce (TU IOST semester board exam, 2082 (BS), via StudyNp), TU BIT 2081 Seventh Semester Mobile Application Development (TU IOST semester board exam, 2081 (BS), via StudyNp), TU BIT 2080 Seventh Semester Cloud Computing (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2081 Seventh Semester Cloud Computing (TU IOST semester board exam, 2081 (BS), via StudyNp) and TU BIT 2082 Seventh Semester Cloud Computing (TU IOST semester board exam, 2082 (BS), via StudyNp). Answers are written for this site; check them against your class notes.