Skip to main content

Chapter 7

Java Programming II (old course)

TU BIM past exam questions

Past questions and answers

17 questions set from this chapter. Most repeated first.

  • 2016 AD Model · 1 mark

Which method is used to create session in java?

Answer

The getSession() method of HttpServletRequest is used: HttpSession session = request.getSession(); (or request.getSession(true)). It returns the current session, creating a new one if none exists.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2016 AD Model · 1 mark

What do you mean by delegation model?

Answer

The delegation event model is the Java AWT/Swing event-handling model in which a source component generates an event and delegates its handling to one or more registered listener objects. A listener is registered with the source (e.g. button.addActionListener(listener)) and its handler method is called when the event occurs.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2016 AD Model · 1 mark

What is component?

Answer

A component is an object with a visual representation that can be displayed on the screen and interact with the user, such as a button, label, text field or checkbox. In AWT, java.awt.Component is the abstract base class of all such user-interface elements.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2016 AD Model · 1 mark

How is radio button created in Applet?

Answer

In an applet (AWT), a radio button is created with Checkbox objects that belong to the same CheckboxGroup, so only one can be selected at a time:

CheckboxGroup cbg = new CheckboxGroup();
Checkbox male = new Checkbox("Male", cbg, true);
Checkbox female = new Checkbox("Female", cbg, false);
add(male);
add(female);

(In Swing, JRadioButton objects are grouped using ButtonGroup.)

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2016 AD Model · 1 mark

Write a statement to create a JTable.

Answer

String[] columns = {"ID", "Name", "Age"};
Object[][] data = {{1, "Ram", 20}, {2, "Sita", 21}};
JTable table = new JTable(data, columns);

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2016 AD Model · 1 mark

Write a statement to create a connection object to make connection with database of your choice.

Answer

For MySQL:

Connection con = DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/studentdb", "root", "password");

The driver is loaded beforehand with Class.forName("com.mysql.cj.jdbc.Driver");.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2016 AD Model · 1 mark

What is use of Document Type Definition?

Answer

A Document Type Definition (DTD) defines the structure and the legal elements and attributes of an XML document. It is used to validate that an XML document follows the agreed rules, so that different applications can exchange data in a common format.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2016 AD Model · 1 mark

Which Application Programmer Interface (API) is used to compile servlet?

Answer

The Servlet API (packages javax.servlet and javax.servlet.http, or jakarta.servlet in newer versions) is needed to compile a servlet. Its classes come in the servlet-api.jar supplied with Tomcat, which must be on the classpath: javac -cp servlet-api.jar MyServlet.java.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2016 AD Model · 1 mark

What is use of MouseListener interface?

Answer

MouseListener (package java.awt.event) is used to receive and handle mouse events on a component. It declares five methods: mouseClicked(), mousePressed(), mouseReleased(), mouseEntered() and mouseExited(). A class implements it and is registered with addMouseListener().

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2016 AD Model · 4 marks

Write a program to illustrate how to use session state in servlet.

Answer

A session keeps data about a user across several requests. The servlet below counts how many times the same user has visited, storing the count in the HttpSession.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SessionDemo extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        HttpSession session = request.getSession(true);   // create or get session
        Integer count = (Integer) session.getAttribute("visits");
        if (count == null) {
            count = 1;
        } else {
            count = count + 1;
        }
        session.setAttribute("visits", count);             // store state

        out.println("<html><body>");
        out.println("<h3>Session ID: " + session.getId() + "</h3>");
        out.println("<h3>You have visited this page " + count + " time(s).</h3>");
        out.println("</body></html>");
    }
}

Mapping in web.xml:

<servlet>
    <servlet-name>SessionDemo</servlet-name>
    <servlet-class>SessionDemo</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>SessionDemo</servlet-name>
    <url-pattern>/session</url-pattern>
</servlet-mapping>

Each reload by the same browser increases the count, because the session ID (cookie JSESSIONID) identifies the stored state. session.invalidate() ends the session.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2016 AD Model · 4 marks

Write a program in which user can select one of the options and display the selected option.

Answer

A Swing program with radio buttons: the user selects one option and the choice is displayed.

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

public class OptionDemo extends JFrame implements ActionListener {
    JRadioButton r1, r2, r3;
    JLabel result;

    OptionDemo() {
        setLayout(new FlowLayout());
        r1 = new JRadioButton("Java");
        r2 = new JRadioButton("Python");
        r3 = new JRadioButton("C++");
        ButtonGroup bg = new ButtonGroup();      // only one can be selected
        bg.add(r1); bg.add(r2); bg.add(r3);
        r1.addActionListener(this);
        r2.addActionListener(this);
        r3.addActionListener(this);
        result = new JLabel("No option selected");
        add(r1); add(r2); add(r3); add(result);
        setSize(300, 120);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        result.setText("You selected: " + e.getActionCommand());
    }

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

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2016 AD Model · 4 marks

Write a code to display records of database. (Make your assumptions about database).

Answer

Assumption: MySQL database college with table student(id INT, name VARCHAR(50), address VARCHAR(50)).

import java.sql.*;

public class DisplayRecords {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/college", "root", "password");
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery("SELECT * FROM student");

            System.out.println("ID\tName\tAddress");
            while (rs.next()) {
                System.out.println(rs.getInt("id") + "\t"
                    + rs.getString("name") + "\t" + rs.getString("address"));
            }
            rs.close();
            st.close();
            con.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
}

Steps: load the driver, open a connection, create a Statement, run the query to get a ResultSet, loop with rs.next() to read each row, then close the resources.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2016 AD Model · 4 marks

Write a servlet which displays factorial of a integer.

Answer

The servlet reads an integer from a request parameter n (e.g. /fact?n=5) and prints its factorial.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FactorialServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        try {
            int n = Integer.parseInt(request.getParameter("n"));
            if (n < 0) {
                out.println("<h3>Factorial is not defined for negative numbers.</h3>");
            } else {
                long fact = 1;
                for (int i = 2; i <= n; i++) {
                    fact *= i;
                }
                out.println("<html><body>");
                out.println("<h3>Factorial of " + n + " = " + fact + "</h3>");
                out.println("</body></html>");
            }
        } catch (NumberFormatException e) {
            out.println("<h3>Please supply an integer as parameter n.</h3>");
        }
    }
}

For n=5 the output is Factorial of 5 = 120. (long is accurate up to n=20n=20.)

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2016 AD Model · 4 marks

Write a JSP program to display text "Apache Tomcat".

Answer

index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<head>
    <title>Tomcat</title>
</head>
<body>
    <h2><% out.println("Apache Tomcat"); %></h2>
</body>
</html>

Place it in the web application folder (e.g. webapps/myapp/), start Tomcat and open http://localhost:8080/myapp/index.jsp. The page displays Apache Tomcat. The scriptlet <% ... %> runs Java code; the expression <%= "Apache Tomcat" %> would give the same result.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2016 AD Model · 5 marks

Differentiate between JSP and Servlet. Explain the use of web.xml file with an example.

Answer

Difference between JSP and Servlet

JSPServlet
HTML with embedded Java code (tags, scriptlets)Java class with HTML written via out.println()
Easy to write, suited to presentation/viewHarder for page design, suited to control/business logic
Translated and compiled into a servlet by the container on first requestCompiled by the programmer beforehand
Changes appear automatically on reloadNeeds recompilation and redeployment
Has implicit objects (request, session, out ...)Objects must be obtained explicitly
Can use custom tags and ELNo such tags

Use of web.xml

web.xml is the deployment descriptor of a web application, kept in WEB-INF/. It tells the container how to deploy the app: it maps URLs to servlets, holds initialization parameters, listeners, filters, welcome files, error pages and session timeout.

Example:

<web-app>
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>HelloServlet</servlet-class>
        <init-param>
            <param-name>college</param-name>
            <param-value>ABC College</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
</web-app>

A request to /hello is handled by HelloServlet.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2016 AD Model · 5 marks

Differentiate between Applet and Swing. Explain the BorderLayout manager.

Answer

Difference between Applet and Swing

AppletSwing
Small program embedded in a web page and run in a browser/appletviewerToolkit for building standalone desktop GUI applications
Extends java.applet.Applet (or JApplet)Uses JFrame, JPanel, JButton and so on
Life cycle methods: init(), start(), stop(), destroy()No such life cycle; starts from main()
Restricted by browser security (no local file access by default)No such restrictions
Heavyweight AWT componentsLightweight components, pluggable look and feel
Largely obsolete in modern browsersStill used for desktop GUIs

BorderLayout manager

BorderLayout divides a container into five regions: NORTH, SOUTH, EAST, WEST and CENTER. Each region holds at most one component. NORTH and SOUTH stretch across the width, EAST and WEST take the height between them, and CENTER takes all the remaining space. It is the default layout of JFrame and Frame. If no region is given the component goes to CENTER.

JFrame f = new JFrame("BorderLayout");
f.setLayout(new BorderLayout());
f.add(new JButton("North"), BorderLayout.NORTH);
f.add(new JButton("South"), BorderLayout.SOUTH);
f.add(new JButton("East"), BorderLayout.EAST);
f.add(new JButton("West"), BorderLayout.WEST);
f.add(new JButton("Center"), BorderLayout.CENTER);
f.setSize(300, 200);
f.setVisible(true);

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

Questions from TU BIM Fifth Semester IT 228 Artificial Intelligence Model Question 2024 (Faculty of Management model question 2024, BIM fifth semester, via EducateNepal), TU BIM Fifth Semester IT 242 Software Design and Development Model Question 2024 (Faculty of Management model question 2024, BIM fifth semester, via EducateNepal), TU BIM Fifth Semester IT 243 Programming with Python Model Question 2024 (Faculty of Management model question 2024, BIM fifth semester, via EducateNepal), TU BIM Fifth Semester IT 244 Information Security Model Question 2024 (Faculty of Management model question 2024, BIM fifth semester, via EducateNepal), TU BIM Fifth Semester MKT 201 Fundamentals of Marketing Model Question 2024 (Faculty of Management model question 2024, BIM fifth semester, via EducateNepal), TU BIM Fifth Semester IT 221 Computer Graphics 2016 (model question) (Faculty of Management model question 2016 (old course), via EducateNepal), TU BIM Fifth Semester IT 222 Java Programming II 2016 (model question) (Faculty of Management model question 2016 (old course), via EducateNepal) and TU BIM Fifth Semester IT 223 Advance Internetworking 2016 (model question) (Faculty of Management model question 2016 (old course), via EducateNepal). Answers are written for this site; check them against your class notes.