BTCE | 5th Sem
Adv-Java SubjectExtra questions

Adv-Java Unit 3 & 4: Extra Questions

Generated and Prepared By Thiruselvan (ThiruXD)

SECTION I: MULTIPLE CHOICE QUESTIONS (1 Mark Each)


1. Which JDBC object is primarily used to establish a connection with a database?

  1. Statement | b) DriverManager | c) ResultSet | d) SQLException

Answer: b) DriverManager -> Explanation: DriverManager is the class used to establish connections. It manages JDBC drivers and provides getConnection() method to create a Connection object.


2. Which JDBC driver type converts JDBC calls into calls to the database-specific native API?

  1. Type 1 | b) Type 2 | c) Type 3 | d) Type 4

Answer: b) Type 2 -> Explanation: Type 2 (Native API Driver) converts JDBC calls into database-specific native API calls. It uses native libraries and is faster than Type 1 but platform-dependent.


3. Which package contains the core JDBC interfaces and classes?

  1. java.io | b) java.sql | c) javax.swing | d) org.springframework

Answer: b) java.sql -> Explanation: The java.sql package contains core JDBC classes and interfaces such as Connection, Statement, PreparedStatement, CallableStatement, and ResultSet.


4. Which method is used to execute a SQL SELECT statement and return a ResultSet?

  1. executeUpdate() | b) executeQuery() | c) execute() | d) runQuery()

Answer: b) executeQuery() -> Explanation: executeQuery() is used for SELECT statements. It returns a ResultSet object containing the query results.


5. Which JDBC object represents the tabular data returned by a SELECT query?

  1. Connection | b) Statement | c) ResultSet | d) DatabaseMetaData

Answer: c) ResultSet -> Explanation: ResultSet stores the results of a SQL query in tabular form. It maintains a cursor pointing to the current row and provides methods like next(), getString(), getInt().


6. Which interface is used to control commit and rollback of a JDBC transaction?

  1. ResultSet | b) Connection | c) Driver | d) Statement

Answer: b) Connection -> Explanation: The Connection interface provides commit(), rollback(), and setAutoCommit() methods to control transactions.


7. Which Swing component is commonly used to accept a single line of text?

  1. JLabel | b) JTextField | c) JTextArea | d) JPanel

Answer: b) JTextField -> Explanation: JTextField accepts a single line of text input. JTextArea is for multi-line text; JLabel displays non-editable text.


8. Which Swing component is used as a top-level container for a desktop application?

  1. JButton | b) JFrame | c) JLabel | d) JCheckBox

Answer: b) JFrame -> Explanation: JFrame is the top-level container (main window) in Swing. It holds other components and provides the window frame with title bar, minimize, maximize, and close buttons.


9. Which Spring feature allows an object to receive its dependencies from outside rather than creating them itself?

  1. Inheritance | b) Dependency Injection | c) Encapsulation | d) Overloading

Answer: b) Dependency Injection -> Explanation: Dependency Injection (DI) is the process of providing dependencies to an object from outside, typically by the Spring container. It promotes loose coupling.


10. Which injection technique supplies dependencies through a class constructor?

  1. Field injection | b) Constructor injection | c) Setter injection | d) Method overriding

Answer: b) Constructor injection -> Explanation: Constructor Injection provides dependencies through the class constructor. It ensures mandatory dependencies are provided at object creation and supports immutability.


11. Which Spring MVC annotation maps a web request to a controller method?

  1. @Bean | b) @Autowired | c) @RequestMapping | d) @Component

Answer: c) @RequestMapping -> Explanation: @RequestMapping maps URL requests to controller methods. It can specify the path, HTTP method, parameters, and headers.


12. Which Spring feature defines how long a bean instance exists in the container?

  1. Bean scope | b) Bean validation | c) Request mapping | d) JDBC driver

Answer: a) Bean scope -> Explanation: Bean scope defines the lifecycle and visibility of a bean instance. Common scopes: singleton (default), prototype, request, session, application.


13. Which class is commonly used to obtain a JDBC database connection?

  1. DriverManager | b) ResultSet | c) SQLException | d) JFrame

Answer: a) DriverManager -> Explanation: DriverManager.getConnection(url, user, password) is the standard way to obtain a database connection in JDBC.


14. Which JDBC driver is known as the pure Java driver and directly communicates with the database server?

  1. Type 1 | b) Type 2 | c) Type 3 | d) Type 4

Answer: d) Type 4 -> Explanation: Type 4 (Thin Driver) is a pure Java driver that communicates directly with the database server. It is the fastest, most portable, and most commonly used.


15. Which JDBC interface represents a SQL statement sent to the database?

  1. Connection | b) Statement | c) ResultSet | d) DatabaseMetaData

Answer: b) Statement -> Explanation: The Statement interface represents a SQL statement sent to the database. It is created via con.createStatement() and executed via executeQuery() or executeUpdate().


16. Which method is generally used to execute INSERT, UPDATE or DELETE statements?

  1. executeQuery() | b) executeUpdate() | c) executeSelect() | d) getUpdate()

Answer: b) executeUpdate() -> Explanation: executeUpdate() is used for INSERT, UPDATE, and DELETE statements. It returns an int representing the number of affected rows.


17. Which JDBC object provides information about columns and other properties of query results?

  1. ResultSetMetaData | b) DriverManager | c) Statement | d) Connection

Answer: a) ResultSetMetaData -> Explanation: ResultSetMetaData provides information about columns in a ResultSet: column names, data types, column count, etc.


18. Which method makes the changes made in a transaction permanent?

  1. rollback() | b) commit() | c) close() | d) execute()

Answer: b) commit() -> Explanation: commit() saves all changes made in the current transaction permanently to the database.


19. Which Swing component displays a command button that can generate an action event?

  1. JButton | b) JTextField | c) JLabel | d) JPanel

Answer: a) JButton -> Explanation: JButton displays a clickable button. When clicked, it generates an ActionEvent that can be handled by an ActionListener.


20. Which Swing container can hold other Swing components and is commonly used to organize a GUI?

  1. JPanel | b) JTextField | c) JButton | d) JLabel

Answer: a) JPanel -> Explanation: JPanel is a lightweight container used to group and organize other components. It can have its own layout manager.


21. Which Spring principle states that the framework controls object creation and dependency management?

  1. Inversion of Control | b) Method Overloading | c) Encapsulation | d) Polymorphism

Answer: a) Inversion of Control -> Explanation: Inversion of Control (IoC) means object creation and dependency management are transferred from the programmer to the Spring container.


22. Which annotation is commonly used to inject a dependency into a Spring bean?

  1. @Autowired | b) @RequestMapping | c) @Override | d) @Table

Answer: a) @Autowired -> Explanation: @Autowired is used for automatic dependency injection. It can be applied to constructors, setters, or fields.


23. Which Spring MVC facility provides tags such as form, input and errors for HTML forms?

  1. JDBC API | b) Spring MVC Form Tag Library | c) JSTL SQL tags | d) Swing Controls

Answer: b) Spring MVC Form Tag Library -> Explanation: The Spring MVC Form Tag Library provides JSP tags like <form:form>, <form:input>, <form:errors> for data binding and validation.


24. Which feature of Spring is used to check form data against validation rules?

  1. Spring Validation | b) Bean Scope | c) JDBC Metadata | d) Swing Layout

Answer: a) Spring Validation -> Explanation: Spring Validation uses annotations like @NotNull, @Email, @Size, @Min, @Max to validate form data.


25. What is the main purpose of the JDBC API?

  1. To create graphical interfaces | b) To connect Java applications with databases | c) To compile Java programs | d) To manage Swing layouts

Answer: b) To connect Java applications with databases -> Explanation: JDBC (Java Database Connectivity) is a Java API that allows Java applications to connect to databases, execute SQL queries, and process results.


26. Which JDBC driver uses a middleware server between the Java application and database?

  1. Type 1 | b) Type 2 | c) Type 3 | d) Type 4

Answer: c) Type 3 -> Explanation: Type 3 (Network Protocol Driver) uses a middleware server between the Java application and the database. It is database-independent but requires an additional server.


27. Which object contains the database session established by a JDBC application?

  1. Connection | b) ResultSet | c) Statement | d) Metadata

Answer: a) Connection -> Explanation: The Connection object represents an active session with the database. It is used to create statements and manage transactions.


28. Which method can execute a SQL statement that may return either a ResultSet or an update count?

  1. execute() | b) executeQuery() | c) executeUpdate() | d) run()

Answer: a) execute() -> Explanation: execute() is used when the query type is unknown. It returns true if the result is a ResultSet, false if it is an update count.


29. Which metadata interface provides information about a database, such as supported features and tables?

  1. ResultSetMetaData | b) DatabaseMetaData | c) ConnectionMetaData | d) DriverMetaData

Answer: b) DatabaseMetaData -> Explanation: DatabaseMetaData provides information about the database and DBMS: product name, version, supported features, tables, etc.


30. What is the default JDBC transaction mode in which each statement is committed automatically?

  1. Manual commit | b) Auto-commit | c) Rollback mode | d) Batch mode

Answer: b) Auto-commit -> Explanation: By default, JDBC uses auto-commit mode, where each SQL statement is treated as a transaction and committed automatically.


31. Which Swing component is used to display non-editable text or an image?

  1. JLabel | b) JButton | c) JTextField | d) JComboBox

Answer: a) JLabel -> Explanation: JLabel displays non-editable text or an image. It is commonly used for labels and descriptions.


32. Which Swing component allows the user to select one option from a drop-down list?

  1. JList | b) JComboBox | c) JPanel | d) JFrame

Answer: b) JComboBox -> Explanation: JComboBox provides a drop-down list from which the user can select one option.


33. Which Spring mechanism creates and manages objects called beans?

  1. Spring IoC container | b) JDBC DriverManager | c) Swing Event Queue | d) JSP Engine

Answer: a) Spring IoC container -> Explanation: The Spring IoC container creates and manages objects (beans), injects dependencies, and manages their lifecycle.


34. Which injection method supplies a dependency by assigning it directly to a field?

  1. Constructor injection | b) Setter injection | c) Field injection | d) Interface injection

Answer: c) Field injection -> Explanation: Field Injection uses @Autowired directly on fields. It requires less code but is harder to test than constructor injection.


35. Which annotation can be used at the controller level or method level to map web requests in Spring MVC?

  1. @RequestMapping | b) @Bean | c) @Scope | d) @PostConstruct

Answer: a) @RequestMapping -> Explanation: @RequestMapping can be applied at both class level (base path) and method level (specific endpoint) to map web requests.


36. Which Spring MVC feature is used to report validation errors in form data?

  1. Form validation and BindingResult | b) ResultSet | c) JFrame | d) DriverManager

Answer: a) Form validation and BindingResult -> Explanation: @Valid triggers validation, and BindingResult captures validation errors. Errors are displayed using <form:errors>.


37. Which JDBC interface is responsible for representing a connection to a specific database?

  1. Connection | b) Driver | c) Statement | d) ResultSet

Answer: a) Connection -> Explanation: The Connection interface represents a connection (session) to a specific database. It is obtained via DriverManager.getConnection().


38. Which JDBC driver type translates JDBC calls into a database-independent network protocol used by middleware?

  1. Type 1 | b) Type 2 | c) Type 3 | d) Type 4

Answer: c) Type 3 -> Explanation: Type 3 (Network Protocol Driver) translates JDBC calls into a database-independent network protocol used by a middleware server.


39. Which package provides Swing components such as JFrame and JButton?

  1. java.sql | b) javax.swing | c) java.net | d) org.springframework

Answer: b) javax.swing -> Explanation: The javax.swing package provides Swing components like JFrame, JButton, JLabel, JTextField, etc.


40. Which JDBC method is used to release a Connection resource?

  1. release() | b) dispose() | c) close() | d) disconnect()

Answer: c) close() -> Explanation: close() releases the Connection resource and returns it to the pool or closes it. It should be called in a finally block or try-with-resources.


41. Which object is used to retrieve the values of columns from a ResultSet?

  1. ResultSet | b) Connection | c) DriverManager | d) Statement

Answer: a) ResultSet -> Explanation: ResultSet provides methods like getString(), getInt(), getDate() to retrieve column values from the current row.


42. What is the purpose of rollback() in JDBC?

  1. To permanently save changes | b) To undo the current transaction changes | c) To close the database | d) To create a statement

Answer: b) To undo the current transaction changes -> Explanation: rollback() undoes all changes made in the current transaction, restoring the database to its previous state.


43. Which Swing component is suitable for entering multi-line text?

  1. JTextArea | b) JTextField | c) JLabel | d) JButton

Answer: a) JTextArea -> Explanation: JTextArea allows multi-line text input. JTextField is for single-line input.


44. Which component is generally used to arrange other components in a Swing application?

  1. JPanel | b) JTextField | c) JButton | d) JLabel

Answer: a) JPanel -> Explanation: JPanel is a container used to group and arrange other components. It can have its own layout manager.


45. Which Spring concept enables loose coupling between classes?

  1. Dependency Injection | b) Inheritance | c) Method Overloading | d) Data Hiding

Answer: a) Dependency Injection -> Explanation: Dependency Injection enables loose coupling by providing dependencies from outside rather than creating them internally.


46. Which annotation is commonly used to declare a class as a Spring-managed component?

  1. @Component | b) @RequestMapping | c) @ResultSet | d) @Swing

Answer: a) @Component -> Explanation: @Component is a general-purpose stereotype annotation that marks a class as a Spring-managed bean.


47. Which Spring MVC annotation can map a controller method specifically to an HTTP GET request?

  1. @GetMapping | b) @Bean | c) @Scope | d) @Autowired

Answer: a) @GetMapping -> Explanation: @GetMapping is a specialized annotation for mapping HTTP GET requests to controller methods. It is shorthand for @RequestMapping(method = RequestMethod.GET).


48. Which bean scope creates one bean instance for each HTTP request in a web-aware Spring application?

  1. singleton | b) prototype | c) request | d) session

Answer: c) request -> Explanation: The request scope creates a new bean instance for each HTTP request. It is only valid in a web-aware Spring ApplicationContext.


49. Which JDBC interface is used for executing precompiled SQL statements with parameters?

  1. Statement | b) PreparedStatement | c) CallableStatement | d) ResultSet

Answer: b) PreparedStatement -> Explanation: PreparedStatement is a precompiled SQL statement that can be executed multiple times with different parameters. It prevents SQL injection.


50. Which interface allows execution of stored procedures in JDBC?

  1. CallableStatement | b) PreparedStatement | c) Connection | d) Driver

Answer: a) CallableStatement -> Explanation: CallableStatement is used to execute stored procedures. It is created via con.prepareCall("{call procedureName()}").


51. What type of JDBC driver is the Native-protocol all-Java driver?

  1. Type 1 | b) Type 2 | c) Type 3 | d) Type 4

Answer: d) Type 4 -> Explanation: Type 4 (Thin Driver) is the Native-protocol all-Java driver. It communicates directly with the database using the database’s native protocol.


52. Which method is used to register a JDBC driver manually in older applications?

  1. Class.forName() | b) DriverManager.register() | c) Driver.load() | d) System.load()

Answer: a) Class.forName() -> Explanation: Class.forName("com.mysql.cj.jdbc.Driver") loads and registers the JDBC driver class. Modern JDBC 4.0+ auto-registers drivers.


53. Which exception is thrown by JDBC methods when a database access error occurs?

  1. IOException | b) SQLException | c) ClassNotFoundException | d) RemoteException

Answer: b) SQLException -> Explanation: SQLException is thrown when a database access error occurs. It provides getMessage(), getErrorCode(), and getSQLState() methods.


54. Which method of Statement interface enables batch updates?

  1. addBatch() | b) executeBatch() | c) Both a and b | d) updateBatch()

Answer: c) Both a and b -> Explanation: addBatch() adds statements to the batch, and executeBatch() executes all statements in the batch. Both are needed for batch processing.


55. Which JDBC ResultSet type allows scrolling forward and backward but is not sensitive to changes made by others?

  1. TYPE_FORWARD_ONLY | b) TYPE_SCROLL_INSENSITIVE | c) TYPE_SCROLL_SENSITIVE | d) CONCUR_READ_ONLY

Answer: b) TYPE_SCROLL_INSENSITIVE -> Explanation: TYPE_SCROLL_INSENSITIVE allows scrolling forward and backward but is not sensitive to changes made by others. TYPE_SCROLL_SENSITIVE reflects changes.


56. Which Swing layout places components in a single horizontal or vertical row?

  1. FlowLayout | b) BoxLayout | c) GridLayout | d) CardLayout

Answer: b) BoxLayout -> Explanation: BoxLayout arranges components in a single row or column (horizontal or vertical). FlowLayout wraps components; GridLayout uses a grid.


57. Which method adds a component to a container in Java Swing?

  1. insert() | b) add() | c) put() | d) attach()

Answer: b) add() -> Explanation: add(Component) adds a component to a container. It is the standard method for building Swing GUIs.


58. Which listener interface handles mouse clicks and movements in Swing?

  1. ActionListener | b) MouseListener | c) WindowListener | d) KeyListener

Answer: b) MouseListener -> Explanation: MouseListener handles mouse events: mouseClicked(), mousePressed(), mouseReleased(), mouseEntered(), mouseExited().


59. Which class represents a single-selection check box menu item in Swing?

  1. JCheckBoxMenuItem | b) JMenu | c) JMenuItem | d) JPopupMenu

Answer: a) JCheckBoxMenuItem -> Explanation: JCheckBoxMenuItem is a menu item with a check box. It can be selected/deselected and is used in menus.


60. Which Swing component is used to show a progress bar indicating task status?

  1. JSlider | b) JProgressBar | c) JScrollBar | d) JSpinner

Answer: b) JProgressBar -> Explanation: JProgressBar displays progress of a task. It can be determinate (shows percentage) or indeterminate (animated).


61. Which method packs the components within a window to their preferred sizes?

  1. resize() | b) pack() | c) fit() | d) validate()

Answer: b) pack() -> Explanation: pack() sizes the window to fit the preferred sizes and layouts of its components. It is called before setVisible(true).


62. Which Swing component allows tabular presentation of data with rows and columns?

  1. JList | b) JTable | c) JTree | d) JComboBox

Answer: b) JTable -> Explanation: JTable displays data in a tabular format with rows and columns. It uses a TableModel to manage data.


63. Which package contains standard Swing event classes?

  1. java.awt.event | b) javax.swing.event | c) java.sql | d) java.net

Answer: b) javax.swing.event -> Explanation: The javax.swing.event package contains Swing-specific event classes like ListSelectionEvent, TreeSelectionEvent, etc. java.awt.event contains AWT events.


64. Which Spring annotation is specialized for defining service layer components?

  1. @Repository | b) @Service | c) @Controller | d) @Component

Answer: b) @Service -> Explanation: @Service is a specialized annotation for service-layer components. It is a stereotype annotation that marks a class as a Spring bean.


65. Which Spring annotation marks a data access persistence component?

  1. @Repository | b) @Service | c) @Configuration | d) @Bean

Answer: a) @Repository -> Explanation: @Repository marks a data access component (DAO). It also translates database exceptions into Spring’s DataAccessException hierarchy.


66. Which annotation configures a class to act as a Spring configuration source?

  1. @Configuration | b) @Bean | c) @Autowired | d) @Module

Answer: a) @Configuration -> Explanation: @Configuration marks a class as a source of bean definitions. Methods annotated with @Bean in this class define Spring beans.


67. What is the default bean scope in Spring framework?

  1. prototype | b) singleton | c) request | d) session

Answer: b) singleton -> Explanation: Singleton is the default bean scope. Only one instance of the bean is created per Spring container.


68. Which Spring module supports Aspect-Oriented Programming?

  1. Spring JDBC | b) Spring AOP | c) Spring MVC | d) Spring ORM

Answer: b) Spring AOP -> Explanation: Spring AOP supports Aspect-Oriented Programming, allowing separation of cross-cutting concerns like logging, security, and transactions.


69. Which annotation maps HTTP POST requests specifically in Spring MVC?

  1. @GetMapping | b) @PostMapping | c) @PutMapping | d) @RequestMapping

Answer: b) @PostMapping -> Explanation: @PostMapping is a specialized annotation for mapping HTTP POST requests to controller methods. It is shorthand for @RequestMapping(method = RequestMethod.POST).


70. Which class or interface binds form data and handles validation results in Spring MVC?

  1. BindingResult | b) ModelMap | c) HttpSession | d) HttpServletRequest

Answer: a) BindingResult -> Explanation: BindingResult holds the results of data binding and validation. It is used with @Valid to check for errors in form data.


71. Which Spring annotation extracts path variables from URI templates?

  1. @RequestParam | b) @PathVariable | c) @RequestBody | d) @ModelAttribute

Answer: b) @PathVariable -> Explanation: @PathVariable extracts values from URI template variables. Example: /student/{id} with @PathVariable int id.


72. Which JDBC method turns off auto-commit mode?

  1. setAutoCommit(false) | b) commit(false) | c) disableAutoCommit() | d) setManualCommit(true)

Answer: a) setAutoCommit(false) -> Explanation: con.setAutoCommit(false) disables auto-commit mode, allowing manual transaction control via commit() and rollback().


73. Which database metadata method checks if the database is read-only?

  1. isReadOnly() | b) checkReadOnly() | c) getReadOnly() | d) readOnlyStatus()

Answer: a) isReadOnly() -> Explanation: DatabaseMetaData.isReadOnly() returns true if the database is in read-only mode.


74. Which method returns the number of columns in a ResultSet object?

  1. getColumnCount() | b) getColumns() | c) countColumns() | d) size()

Answer: a) getColumnCount() -> Explanation: ResultSetMetaData.getColumnCount() returns the number of columns in the ResultSet.


75. Which interface represents a database connection pool configuration in enterprise frameworks?

  1. DataSource | b) ConnectionPool | c) DBManager | d) SessionFactory

Answer: a) DataSource -> Explanation: javax.sql.DataSource represents a connection pool configuration. It is preferred over DriverManager for enterprise applications.


76. Which Swing component is used to present multiple tabs for switching panels?

  1. JTabbedPane | b) JSplitPane | c) JScrollPane | d) JDesktopPane

Answer: a) JTabbedPane -> Explanation: JTabbedPane presents multiple tabs, each containing a panel. Users can switch between tabs to view different content.


77. Which layout manager flips through multiple component cards like a deck of cards?

  1. CardLayout | b) FlowLayout | c) GridBagLayout | d) SpringLayout

Answer: a) CardLayout -> Explanation: CardLayout arranges components as stacked cards, showing only one at a time. It is used for wizards and tab-like interfaces.


78. Which method registers an action listener with a button?

  1. addActionListener() | b) registerListener() | c) setActionListener() | d) attachListener()

Answer: a) addActionListener() -> Explanation: button.addActionListener(listener) registers an ActionListener to handle button clicks.


79. Which component provides a popup menu when right-clicked?

  1. JPopupMenu | b) JMenu | c) JMenuBar | d) JMenuItem

Answer: a) JPopupMenu -> Explanation: JPopupMenu is a floating menu that appears when the user right-clicks. It contains JMenuItem components.


80. Which class is used to handle multiple text lines with scrolling support in Swing?

  1. JTextField | b) JTextArea | c) JLabel | d) JPasswordBox

Answer: b) JTextArea -> Explanation: JTextArea handles multiple lines of text. When wrapped in a JScrollPane, it provides scrolling support.


81. Which interface listens for value changes in lists or tables in Swing?

  1. ListSelectionListener | b) ActionListener | c) ItemListener | d) ChangeListener

Answer: a) ListSelectionListener -> Explanation: ListSelectionListener listens for selection changes in JList and JTable components.


82. Which Spring annotation is a general-purpose stereotype for any Spring-managed bean?

  1. @Component | b) @Bean | c) @Service | d) @Inject

Answer: a) @Component -> Explanation: @Component is the general-purpose stereotype annotation. @Service, @Repository, and @Controller are specializations of @Component.


83. Which annotation is used to inject values from properties files into Spring beans?

  1. @Value | b) @Inject | c) @Autowired | d) @Property

Answer: a) @Value -> Explanation: @Value("${property.name}") injects values from properties files into Spring bean fields.


84. Which container interface represents the advanced Spring IoC container with internationalization support?

  1. ApplicationContext | b) BeanFactory | c) WebApplicationContext | d) ContainerContext

Answer: a) ApplicationContext -> Explanation: ApplicationContext is the advanced IoC container. It extends BeanFactory and adds support for internationalization, event propagation, and annotation-based configuration.


85. Which method initializes a bean lifecycle callback explicitly in Spring?

  1. @PostConstruct | b) @PreDestroy | c) @Init | d) @Start

Answer: a) @PostConstruct -> Explanation: @PostConstruct marks a method to be executed after bean initialization. It is used for initialization logic.


86. Which method cleans up a bean during destruction in Spring?

  1. @PreDestroy | b) @PostConstruct | c) @Destroy | d) @Clean

Answer: a) @PreDestroy -> Explanation: @PreDestroy marks a method to be executed before bean destruction. It is used for cleanup logic.


87. Which Spring annotation binds request body data directly to a method parameter object?

  1. @RequestBody | b) @ResponseBody | c) @RequestParam | d) @PathVariable

Answer: a) @RequestBody -> Explanation: @RequestBody binds the HTTP request body (e.g., JSON) directly to a method parameter object.


88. Which annotation serializes controller method return values directly to JSON/XML responses?

  1. @ResponseBody | b) @RequestBody | c) @JsonView | d) @RestResponse

Answer: a) @ResponseBody -> Explanation: @ResponseBody serializes the return value of a controller method directly to the HTTP response body (JSON/XML).


89. Which servlet method is called once when the servlet is first loaded?

  1. init() | b) service() | c) destroy() | d) doGet()

Answer: a) init() -> Explanation: init() is called once when the servlet is first loaded. It is used for initialization logic.


90. Which interface handles client requests and responses in Java Servlets?

  1. ServletRequest / ServletResponse | b) HttpServlet / HttpSession | c) Connection / Statement | d) Filter / Chain

Answer: a) ServletRequest / ServletResponse -> Explanation: ServletRequest and ServletResponse are the core interfaces for handling client requests and responses in servlets.


91. Which mechanism maintains state across multiple HTTP requests in J2EE?

  1. Session tracking | b) JDBC Commit | c) Dependency Injection | d) Event Handling

Answer: a) Session tracking -> Explanation: Session tracking maintains state across multiple HTTP requests. Techniques include cookies, HttpSession, URL rewriting, and hidden form fields.


92. Which EJB type handles business logic without maintaining client state across calls?

  1. Stateless Session Bean | b) Stateful Session Bean | c) Message-Driven Bean | d) Entity Bean

Answer: a) Stateless Session Bean -> Explanation: Stateless Session Beans handle business logic without maintaining client state across method calls. They are pooled and reusable.


93. Which EJB type maintains conversational state for a specific client?

  1. Stateful Session Bean | b) Stateless Session Bean | c) Singleton Bean | d) Entity Bean

Answer: a) Stateful Session Bean -> Explanation: Stateful Session Beans maintain conversational state for a specific client across multiple method calls.


94. Which file acts as the primary deployment descriptor for a traditional Java web application?

  1. web.xml | b) spring.xml | c) pom.xml | d) bean.xml

Answer: a) web.xml -> Explanation: web.xml is the primary deployment descriptor for a traditional Java web application. It defines servlets, filters, listeners, and URL mappings.


95. Which Java technology combines HTML and embedded Java code for server-side rendering?

  1. JSP (JavaServer Pages) | b) JDBC | c) Swing | d) EJB

Answer: a) JSP (JavaServer Pages) -> Explanation: JSP combines HTML with embedded Java code for server-side rendering. JSP pages are compiled into servlets.


96. Which architectural pattern separates data, user interface, and control logic in web and desktop applications?

  1. MVC (Model-View-Controller) | b) Singleton | c) Factory | d) Observer

Answer: a) MVC (Model-View-Controller) -> Explanation: MVC separates data (Model), user interface (View), and control logic (Controller). It is used in both web and desktop applications.


SECTION II: SHORT ANSWER QUESTIONS (3 Marks Each)


1. Explain the JDBC process from loading/registering a driver to executing a SQL query and processing the ResultSet.

Answer:

The JDBC process consists of five steps:

Step 1: Load/Register Driver

Class.forName("com.mysql.cj.jdbc.Driver");

Loads the JDBC driver class into memory.

Step 2: Establish Connection

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

Step 3: Create Statement and Execute Query

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");

Step 4: Process ResultSet

while (rs.next()) {
    System.out.println(rs.getString("name"));
}

Step 5: Close Resources

rs.close();
stmt.close();
con.close();

Complete Example:

import java.sql.*;

public class JdbcExample {
    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection con = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/test", "root", "root");
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM student");
        while (rs.next()) {
            System.out.println(rs.getString("name"));
        }
        con.close();
    }
}

2. Explain the concept of Dependency Injection in Spring. Differentiate between constructor injection and setter injection with suitable examples.

Answer:

Dependency Injection (DI) is the process of providing dependencies to an object from outside rather than creating them internally. It promotes loose coupling and testability.

Constructor Injection: Dependencies are injected through the constructor.

public class StudentService {
    private StudentDAO dao;

    public StudentService(StudentDAO dao) {
        this.dao = dao;
    }
}

XML Configuration:

<bean id="service" class="StudentService">
    <constructor-arg ref="dao"/>
</bean>

Setter Injection: Dependencies are injected through setter methods.

public class StudentService {
    private StudentDAO dao;

    public void setDao(StudentDAO dao) {
        this.dao = dao;
    }
}

XML Configuration:

<property name="dao" ref="dao"/>

Comparison:

AspectConstructor InjectionSetter Injection
Injection PointConstructorSetter method
MandatoryYesNo
ImmutabilityYes (final)No
TestabilityBestGood
Use CaseMandatory dependenciesOptional dependencies

3. Explain JDBC Statement objects and ResultSet. Mention the purpose of executeQuery(), executeUpdate() and next().

Answer:

Statement Objects:

  • Statement: Executes simple SQL queries.
  • PreparedStatement: Precompiled SQL with parameters.
  • CallableStatement: Calls stored procedures.

ResultSet: Stores the results of a SQL query in tabular form. It maintains a cursor pointing to the current row.

Methods:

MethodPurpose
executeQuery()Executes SELECT; returns ResultSet
executeUpdate()Executes INSERT/UPDATE/DELETE; returns int (affected rows)
next()Moves cursor to next row; returns true if row exists

Example:

Statement stmt = con.createStatement();

// executeQuery()
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while (rs.next()) {                        // next()
    System.out.println(rs.getString("name"));
}

// executeUpdate()
int rows = stmt.executeUpdate("DELETE FROM student");
System.out.println(rows + " rows deleted");

4. Explain Inversion of Control and Dependency Injection in Spring. Compare setter injection and field injection.

Answer:

Inversion of Control (IoC): Object creation and dependency management are transferred from the programmer to the Spring container.

Dependency Injection (DI): The process of providing dependencies to an object from outside.

Setter Injection:

public class StudentService {
    private StudentDAO dao;
    public void setDao(StudentDAO dao) {
        this.dao = dao;
    }
}

Field Injection:

@Service
public class StudentService {
    @Autowired
    private StudentDAO dao;
}

Comparison:

AspectSetter InjectionField Injection
Injection PointSetter methodField directly
CodeMore verboseLess code
TestabilityGoodPoor
ImmutabilityNoNo
RecommendedYesNo
VisibilityExplicitHidden

Advantages of IoC and DI:

  1. Loose coupling
  2. Easier testing
  3. Better maintainability
  4. Reusability
  5. Scalability

5. Explain JDBC metadata. Differentiate between DatabaseMetaData and ResultSetMetaData.

Answer:

JDBC Metadata means “data about data.” It provides information about the database structure, tables, columns, and query results.

DatabaseMetaData: Provides information about the database and DBMS.

DatabaseMetaData dm = con.getMetaData();
System.out.println(dm.getDatabaseProductName());  // MySQL

ResultSetMetaData: Provides information about columns in a ResultSet.

ResultSetMetaData meta = rs.getMetaData();
System.out.println(meta.getColumnCount());  // 4
System.out.println(meta.getColumnName(1));  // id
System.out.println(meta.getColumnTypeName(1));  // INT

Comparison:

AspectDatabaseMetaDataResultSetMetaData
Provides info aboutDatabase, DBMSQuery result columns
Obtained fromcon.getMetaData()rs.getMetaData()
Key MethodsgetDatabaseProductName(), getTables()getColumnCount(), getColumnName()
Use CaseSchema inspectionDynamic report generation

6. Explain Spring bean scope and bean lifecycle. Mention any four commonly used bean scopes/lifecycle concepts.

Answer:

Bean Scope: Defines how long a bean instance exists in the container.

ScopeDescription
SingletonOne instance per container (default)
PrototypeNew instance per request
RequestOne instance per HTTP request
SessionOne instance per HTTP session

Bean Lifecycle:

1. Instantiation
2. Dependency Injection
3. @PostConstruct (init)
4. Bean Ready for Use
5. @PreDestroy (destroy)
6. Bean Removed

Lifecycle Callbacks:

@Component
public class Student {
    @PostConstruct
    public void init() {
        System.out.println("Bean initialized");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("Bean destroyed");
    }
}

Four Commonly Used Concepts:

  1. Singleton scope — default, one instance
  2. Prototype scope — new instance per request
  3. @PostConstruct — initialization callback
  4. @PreDestroy — destruction callback

7. Explain JDBC exceptions and data types. Discuss the role of SQLException and SQL data types while processing database values in Java.

Answer:

JDBC Exceptions:SQLException is the main exception class in JDBC. It is thrown when database operations fail.

try {
    Connection con = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
    System.out.println(e.getMessage());
    System.out.println(e.getErrorCode());
    System.out.println(e.getSQLState());
}

JDBC Data Types: JDBC maps SQL data types to Java data types.

SQL TypeJava Type
INTint
BIGINTlong
FLOATfloat
DOUBLEdouble
VARCHARString
DATEjava.sql.Date
TIMEjava.sql.Time
TIMESTAMPjava.sql.Timestamp

Example:

int id = rs.getInt("id");
String name = rs.getString("name");
java.sql.Date d = rs.getDate("dob");

Role of SQLException:

  1. Handles database errors
  2. Provides error codes and SQL state
  3. Enables exception chaining

Role of Data Types:

  1. Type mapping between SQL and Java
  2. Data conversion
  3. Type-safe data retrieval

8. Explain the basic architecture of Spring MVC. Describe the roles of Controller, Model and View in processing a client request.

Answer:

Spring MVC Architecture:

Browser → DispatcherServlet → HandlerMapping → Controller → ViewResolver → View (JSP)

Components:

ComponentRole
DispatcherServletFront controller; receives all requests
HandlerMappingMaps URL to controller
ControllerHandles request; returns view name
ModelHolds data for view
ViewResolverMaps view name to JSP
ViewRenders HTML response

Flow:

  1. Browser sends request to /home
  2. DispatcherServlet receives request
  3. HandlerMapping finds HomeController
  4. Controller method executes, returns "home"
  5. ViewResolver maps "home" to /WEB-INF/views/home.jsp
  6. JSP renders HTML response
  7. Response sent back to browser

Example:

@Controller
public class HomeController {
    @RequestMapping("/home")
    public String home(Model model) {
        model.addAttribute("message", "Welcome");
        return "home";
    }
}

9. Explain the difference between Statement and PreparedStatement in JDBC, highlighting performance and security advantages.

Answer:

AspectStatementPreparedStatement
PurposeSimple SQL queriesPrecompiled SQL with parameters
Creationcon.createStatement()con.prepareStatement(sql)
ParametersNo parametersSupports ? placeholders
PerformanceSlower for repeated executionFaster (precompiled)
SQL InjectionVulnerablePrevents SQL injection
ReusabilityNot reusableReusable
Use CaseStatic queriesDynamic queries

Statement Example:

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");

PreparedStatement Example:

PreparedStatement ps = con.prepareStatement(
    "SELECT * FROM student WHERE id=?");
ps.setInt(1, 101);
ResultSet rs = ps.executeQuery();

Security Advantage: PreparedStatement prevents SQL injection by escaping parameters. User input is treated as data, not SQL code.

Performance Advantage: PreparedStatement is precompiled, so repeated execution is faster than Statement.


10. Explain the role of Type 3 and Type 4 JDBC drivers in database connectivity architectures.

Answer:

Type 3: Network Protocol Driver

Architecture:

Java → Middleware Server → Database

Features:

  • Uses middleware server
  • Database independent
  • No client-side installation

Advantages:

  • Database independent
  • No client-side installation
  • Good for web applications

Disadvantages:

  • Additional server required
  • Extra network hop adds latency

Type 4: Thin Driver (Pure Java)

Architecture:

Java → Database

Example:

Class.forName("com.mysql.cj.jdbc.Driver");

Features:

  • Pure Java
  • Direct communication with database
  • Fastest performance

Advantages:

  1. Fastest
  2. Pure Java
  3. Portable
  4. Most commonly used

Comparison:

AspectType 3Type 4
ArchitectureMiddlewareDirect
SpeedFastFastest
Client InstallationNoneNone
Server RequiredYesNo
Use CaseEnterpriseModern apps

11. Describe the function of Layout Managers in Java Swing and contrast FlowLayout with BorderLayout.

Answer:

Layout Managers control how components are arranged in a container.

FlowLayout: Arranges components left to right, wrapping to the next line when needed.

frame.setLayout(new FlowLayout());

Example:

[A] [B] [C]
[D] [E]

BorderLayout: Divides the container into five regions: North, South, East, West, Center.

frame.setLayout(new BorderLayout());
frame.add(new JButton("North"), BorderLayout.NORTH);
frame.add(new JButton("Center"), BorderLayout.CENTER);

Example:

        North
West    Center    East
        South

Comparison:

AspectFlowLayoutBorderLayout
ArrangementLeft to right5 regions
Default ForJPanelJFrame
ComponentsAny numberMax 5 (one per region)
ResizingWrapsStretches
Use CaseToolbarsMain windows

12. Explain the purpose of event adapters in Java Swing and why they are useful when implementing listener interfaces.

Answer:

Event Adapters provide default implementations of listener methods. They are useful because listener interfaces have multiple methods, and you often need only one.

Example — WindowAdapter:

public class Demo extends WindowAdapter {
    public void windowClosing(WindowEvent e) {
        System.exit(0);
    }
}

Without Adapter:

public class Demo implements WindowListener {
    public void windowClosing(WindowEvent e) { System.exit(0); }
    public void windowOpened(WindowEvent e) { }      // Empty
    public void windowClosed(WindowEvent e) { }       // Empty
    public void windowIconified(WindowEvent e) { }    // Empty
    public void windowDeiconified(WindowEvent e) { }  // Empty
    public void windowActivated(WindowEvent e) { }    // Empty
    public void windowDeactivated(WindowEvent e) { }  // Empty
}

Benefits:

  1. Less coding
  2. Override only required methods
  3. Cleaner code
  4. Easier maintenance

Common Adapters:

  • WindowAdapter
  • MouseAdapter
  • KeyAdapter
  • FocusAdapter

13. Describe the main differences between ApplicationContext and BeanFactory in the Spring IoC container hierarchy.

Answer:

FeatureBeanFactoryApplicationContext
InitializationLazyEager
Annotation SupportNoYes
Event HandlingNoYes
i18nNoYes
AOP IntegrationBasicFull
MemoryLessMore
Use CaseSmall appsEnterprise apps
InterfaceBeanFactoryApplicationContext

BeanFactory Example:

BeanFactory factory = new XmlBeanFactory(
    new ClassPathResource("beans.xml"));
Student student = (Student) factory.getBean("student");

ApplicationContext Example:

ApplicationContext context =
    new ClassPathXmlApplicationContext("beans.xml");
Student student = context.getBean("student", Student.class);

Key Differences:

  1. ApplicationContext is built on top of BeanFactory
  2. ApplicationContext supports annotations, events, and i18n
  3. BeanFactory is lightweight; ApplicationContext is feature-rich
  4. ApplicationContext eagerly initializes beans

14. Explain the function of Spring Stereotype annotations (@Component, @Service, @Repository, @Controller).

Answer:

Spring stereotype annotations mark classes as Spring-managed beans.

AnnotationPurposeLayer
@ComponentGeneral-purpose stereotypeAny
@ServiceService layer componentBusiness logic
@RepositoryData access componentDAO
@ControllerWeb controllerPresentation

Examples:

@Component
public class Student {
}

@Service
public class StudentService {
}

@Repository
public class StudentDAO {
}

@Controller
public class StudentController {
}

How They Work:

  1. Component scanning detects these annotations
  2. Spring creates bean instances
  3. Dependencies are injected
  4. Beans are managed by the container

Benefits:

  1. Readability — Intent is clear from annotation
  2. Specialization — @Repository translates exceptions
  3. Convention — Follows layered architecture
  4. Reduced Configuration — No XML needed

15. Explain servlet lifecycle phases (init, service, destroy) in a standard J2EE web container environment.

Answer:

The servlet lifecycle has three main phases:

1. init() Called once when the servlet is first loaded.

public void init() {
    System.out.println("Servlet Initialized");
}

2. service() Called for every request. Dispatches to doGet() or doPost().

public void service(ServletRequest req, ServletResponse res) {
    System.out.println("Processing Request");
}

3. destroy() Called before the servlet is removed.

public void destroy() {
    System.out.println("Servlet Destroyed");
}

Lifecycle Flow:

Servlet Loaded → init() → service() → service() → ... → destroy()

Example:

import jakarta.servlet.*;

public class LifeCycleDemo extends GenericServlet {
    public void init() {
        System.out.println("init()");
    }
    public void service(ServletRequest req, ServletResponse res) {
        System.out.println("service()");
    }
    public void destroy() {
        System.out.println("destroy()");
    }
}

Key Points:

  • init() is called once
  • service() is called for each request
  • destroy() is called once before removal
  • Container manages the lifecycle

16. Compare session tracking mechanisms in J2EE, specifically Cookies versus HttpSession.

Answer:

AspectCookiesHttpSession
StorageClient-sideServer-side
Data TypeString onlyAny object
Size Limit4KB per cookieUnlimited
SecurityLess secureMore secure
ExpirationSet by serverSet by server/timeout
APICookie classHttpSession interface
Session IDStored in cookieStored in cookie or URL

Cookie Example:

Cookie c = new Cookie("user", "Rahul");
c.setMaxAge(60 * 60 * 24);  // 1 day
response.addCookie(c);

// Reading
Cookie[] cookies = request.getCookies();
for (Cookie ck : cookies) {
    if (ck.getName().equals("user")) {
        String user = ck.getValue();
    }
}

HttpSession Example:

HttpSession session = request.getSession();
session.setAttribute("user", "Rahul");

// Reading
String user = (String) session.getAttribute("user");

When to Use:

  • Cookies: Small, non-sensitive data (preferences, theme)
  • HttpSession: Sensitive data (login, cart, user info)

Session Tracking Techniques:

  1. Cookies
  2. HttpSession
  3. URL Rewriting
  4. Hidden Form Fields

SECTION III: LONG ANSWER QUESTIONS (4 Marks Each)


1. (i) Explain JDBC transaction processing and exception handling. Discuss commit(), rollback(), auto-commit mode and SQLException with suitable examples. (2 marks)

Answer:

Transaction Processing: A transaction is a group of SQL operations executed as a single unit.

ACID Properties:

  • Atomicity: All operations succeed or fail together
  • Consistency: Database remains valid
  • Isolation: Transactions execute independently
  • Durability: Changes remain permanent

Auto-commit Mode: By default, JDBC uses auto-commit mode, where each statement is committed automatically.

con.setAutoCommit(false);   // Disable auto-commit

Commit: Saves changes permanently.

con.commit();

Rollback: Undoes changes.

con.rollback();

Complete Example:

try {
    con.setAutoCommit(false);
    stmt.executeUpdate("UPDATE account SET balance=balance-1000 WHERE id=1");
    stmt.executeUpdate("UPDATE account SET balance=balance+1000 WHERE id=2");
    con.commit();
    System.out.println("Transfer successful");
} catch (SQLException e) {
    con.rollback();
    System.out.println("Transfer failed: " + e.getMessage());
}

SQLException: Main exception class in JDBC.

catch (SQLException e) {
    System.out.println("Message: " + e.getMessage());
    System.out.println("Error Code: " + e.getErrorCode());
    System.out.println("SQL State: " + e.getSQLState());
}

Savepoints: Partial rollback points.

Savepoint sp = con.setSavepoint();
con.rollback(sp);

1. (ii) Explain Swing containers and controls. Describe the working of a front-end calculator application using suitable components. (2 marks)

Answer:

Swing Containers:

  • JFrame: Top-level container (main window)
  • JPanel: Grouping container
  • JScrollPane: Scrollable container
  • JTabbedPane: Tabbed container

Swing Controls:

  • JLabel: Display text/image
  • JTextField: Single-line input
  • JButton: Clickable button
  • JCheckBox: Multiple selections
  • JComboBox: Drop-down list

Calculator Application:

Components:

  • JTextField for display
  • JButtons for digits (0-9) and operations (+, -, *, /, =)
  • GridLayout for button arrangement

Layout:

[        10        ]
[7] [8] [9] [ / ]
[4] [5] [6] [ * ]
[1] [2] [3] [ - ]
[0] [.] [=] [ + ]

Code:

JFrame frame = new JFrame("Calculator");
JTextField display = new JTextField();
display.setEditable(false);

JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4, 5, 5));

String[] buttons = {
    "7", "8", "9", "/",
    "4", "5", "6", "*",
    "1", "2", "3", "-",
    "0", ".", "=", "+"
};

for (String text : buttons) {
    JButton btn = new JButton(text);
    btn.addActionListener(e -> {
        // Handle button click
    });
    panel.add(btn);
}

frame.add(display, BorderLayout.NORTH);
frame.add(panel, BorderLayout.CENTER);

Event Handling:

btn.addActionListener(e -> {
    String cmd = btn.getText();
    if (cmd.equals("=")) {
        // Evaluate expression
    } else {
        // Append to expression
    }
});

Working:

  1. User clicks buttons to build expression
  2. Expression displayed in JTextField
  3. “=” evaluates the expression
  4. Result displayed

2. (i) Explain Spring architecture and Inversion of Control. Discuss bean scope and bean lifecycle, including the major stages from bean creation to destruction. (2 marks)

Answer:

Spring Architecture:

Application
    |
--------------------------------
| Core Container               |
| Data Access Layer            |
| Web Layer                    |
| Integration Layer            |
--------------------------------

Core Container:

  • BeanFactory
  • ApplicationContext
  • IoC Container

Inversion of Control (IoC): Object creation and dependency management transferred to Spring container.

Traditional:

StudentDAO dao = new StudentDAO();

Spring:

@Autowired
StudentDAO dao;

Bean Scope: | Scope | Description | |——-|————-| | Singleton | One instance (default) | | Prototype | New instance per request | | Request | One per HTTP request | | Session | One per HTTP session |

Bean Lifecycle:

1. Instantiation
2. Dependency Injection
3. @PostConstruct (init)
4. Bean Ready for Use
5. @PreDestroy (destroy)
6. Bean Removed

Example:

@Component
public class Student {
    public Student() {
        System.out.println("1. Constructor");
    }

    @Autowired
    public void setDao(StudentDAO dao) {
        System.out.println("2. Setter");
    }

    @PostConstruct
    public void init() {
        System.out.println("3. Init");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("4. Destroy");
    }
}

Output (context start):

1. Constructor
2. Setter
3. Init

Output (context close):

4. Destroy

2. (ii) Explain the configuration of Spring MVC and the role of @RequestMapping in handling client requests. (2 marks)

Answer:

Spring MVC Configuration:

1. DispatcherServlet (web.xml):

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

2. Component Scanning:

<context:component-scan base-package="com.demo"/>

3. View Resolver:

<bean class="InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>
</bean>

@RequestMapping: Maps URL requests to controller methods.

Class Level:

@Controller
@RequestMapping("/student")
public class StudentController {
}

Method Level:

@RequestMapping("/list")
public String list() {
    return "list";
}

With HTTP Method:

@RequestMapping(value="/save", method=RequestMethod.POST)
public String save() {
    return "success";
}

Specialized Annotations:

@GetMapping("/list")     // GET
@PostMapping("/save")    // POST
@PutMapping("/update")   // PUT
@DeleteMapping("/delete") // DELETE

Request Flow:

Browser → DispatcherServlet → HandlerMapping → Controller → ViewResolver → View

Example:

@Controller
public class HomeController {
    @RequestMapping("/home")
    public String home(Model model) {
        model.addAttribute("message", "Welcome");
        return "home";
    }
}

URL: http://localhost:8080/home → home.jsp


3. (i) Explain ResultSet and JDBC metadata. Discuss ResultSetMetaData and DatabaseMetaData with suitable examples. (2 marks)

Answer:

ResultSet: Stores the results of a SQL query. Maintains a cursor pointing to the current row.

ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while (rs.next()) {
    System.out.println(rs.getString("name"));
}

ResultSetMetaData: Provides information about columns in a ResultSet.

ResultSetMetaData meta = rs.getMetaData();
int count = meta.getColumnCount();
for (int i = 1; i <= count; i++) {
    System.out.println("Column: " + meta.getColumnName(i));
    System.out.println("Type: " + meta.getColumnTypeName(i));
}

Output:

Column: id
Type: INT
Column: name
Type: VARCHAR
...

DatabaseMetaData: Provides information about the database and DBMS.

DatabaseMetaData dm = con.getMetaData();
System.out.println(dm.getDatabaseProductName());  // MySQL
System.out.println(dm.getDatabaseProductVersion());
System.out.println(dm.getDriverName());

Listing Tables:

ResultSet tables = dm.getTables(null, null, "%", null);
while (tables.next()) {
    System.out.println(tables.getString("TABLE_NAME"));
}

Comparison:

AspectResultSetMetaDataDatabaseMetaData
Provides info aboutQuery columnsDatabase/DBMS
Obtained fromrs.getMetaData()con.getMetaData()
Key MethodsgetColumnCount(), getColumnName()getDatabaseProductName(), getTables()
Use CaseDynamic reportsSchema inspection

3. (ii) Explain the role of Swing controls and containers in a calculator application. Discuss event handling and basic database connectivity considerations. (2 marks)

Answer:

Swing Controls in Calculator:

  • JTextField: Display area
  • JButton: Digits and operations
  • JPanel: Button grouping

Swing Containers:

  • JFrame: Main window
  • JPanel: Button panel with GridLayout

Layout:

JFrame frame = new JFrame("Calculator");
JTextField display = new JTextField();
display.setEditable(false);

JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4, 5, 5));

String[] buttons = {
    "7", "8", "9", "/",
    "4", "5", "6", "*",
    "1", "2", "3", "-",
    "0", ".", "=", "+"
};

for (String text : buttons) {
    JButton btn = new JButton(text);
    btn.addActionListener(e -> handleClick(btn.getText()));
    panel.add(btn);
}

Event Handling:

private void handleClick(String cmd) {
    if (cmd.equals("=")) {
        try {
            double result = evaluate(expression);
            display.setText(String.valueOf(result));
        } catch (Exception e) {
            display.setText("Error");
        }
    } else {
        expression += cmd;
        display.setText(expression);
    }
}

Database Connectivity Considerations:

  • Calculator typically doesn’t need DB
  • If storing history:
    • Use JDBC to save calculations
    • Table: history(id, expression, result, timestamp)
    • Use PreparedStatement for insertion
PreparedStatement ps = con.prepareStatement(
    "INSERT INTO history(expression, result) VALUES(?, ?)");
ps.setString(1, expression);
ps.setDouble(2, result);
ps.executeUpdate();

Key Considerations:

  1. Use EDT for Swing updates
  2. Handle exceptions gracefully
  3. Close DB resources
  4. Validate input

4. (i) Describe database connection creation in JDBC using DriverManager and Connection. Explain JDBC packages, driver registration and the role of the JDBC/ODBC bridge. (2 marks)

Answer:

DriverManager: Class used to create database connections.

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

Connection: Represents an active session with the database.

Connection con = DriverManager.getConnection(url, user, password);

JDBC Packages: | Package | Purpose | |———|———| | java.sql | Core JDBC classes and interfaces | | javax.sql | Advanced features (connection pooling, DataSource) |

Driver Registration:

Class.forName("com.mysql.cj.jdbc.Driver");

Modern JDBC 4.0+ auto-registers drivers found on the classpath.

JDBC/ODBC Bridge:

Java → JDBC → ODBC → Database

Features:

  • Type 1 driver
  • Uses ODBC
  • Easy to configure
  • Slow performance

Example:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Limitations:

  1. Platform dependent
  2. Requires ODBC installation
  3. Removed after Java 8

Connection URL Components:

jdbc:mysql://host:port/database
PartMeaning
jdbc:mysql://Protocol
localhostHost
3306Port
testDatabase

4. (ii) Explain the design of a database application using Java Swing. Describe how the GUI communicates with a database. (2 marks)

Answer:

Design:

┌─────────────────┐
│   Swing UI      │
└────────┬────────┘
         ↓
┌─────────────────┐
│   DAO Layer     │
└────────┬────────┘
         ↓
┌─────────────────┐
│   Database      │
└─────────────────┘

Components:

  • JFrame: Main window
  • JTextField: Input fields
  • JButton: Actions (Save, Update, Delete)
  • JTable: Display records

GUI Design:

JFrame f = new JFrame("Student Management");
JLabel l1 = new JLabel("Name:");
JTextField tf1 = new JTextField();
JLabel l2 = new JLabel("Age:");
JTextField tf2 = new JTextField();
JButton save = new JButton("Save");
JTable table = new JTable(model);

Communication Flow:

  1. User enters data in JTextField
  2. User clicks JButton
  3. ActionListener triggers DAO method
  4. DAO executes SQL via JDBC
  5. Result returned to GUI
  6. JTable/JOptionPane displays result

Example:

save.addActionListener(e -> {
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection con = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/school", "root", "root");

        PreparedStatement ps = con.prepareStatement(
            "INSERT INTO student(name, age) VALUES(?, ?)");
        ps.setString(1, tf1.getText());
        ps.setInt(2, Integer.parseInt(tf2.getText()));
        ps.executeUpdate();

        JOptionPane.showMessageDialog(f, "Saved!");
        con.close();
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(f, "Error: " + ex.getMessage());
    }
});

Best Practices:

  1. Use PreparedStatement (prevent SQL injection)
  2. Close resources (try-with-resources)
  3. Use SwingUtilities.invokeLater for thread safety
  4. Handle exceptions with user-friendly messages
  5. Use connection pooling for performance

5. (i) Explain the Spring bean lifecycle and different bean scopes. Describe constructor injection, setter injection and field injection with suitable examples. (2 marks)

Answer:

Bean Scopes: | Scope | Description | |——-|————-| | Singleton | One instance per container (default) | | Prototype | New instance per request | | Request | One per HTTP request | | Session | One per HTTP session |

Bean Lifecycle:

1. Instantiation
2. Dependency Injection
3. @PostConstruct
4. Bean Ready
5. @PreDestroy
6. Bean Removed

Injection Types:

Constructor Injection:

public class StudentService {
    private final StudentDAO dao;

    public StudentService(StudentDAO dao) {
        this.dao = dao;
    }
}

Setter Injection:

public class StudentService {
    private StudentDAO dao;

    public void setDao(StudentDAO dao) {
        this.dao = dao;
    }
}

Field Injection:

@Service
public class StudentService {
    @Autowired
    private StudentDAO dao;
}

Comparison:

AspectConstructorSetterField
Injection PointConstructorSetterField
MandatoryYesNoYes
TestabilityBestGoodPoor
ImmutabilityYesNoNo
RecommendedYesYesNo

Advantages of IoC and DI:

  1. Loose coupling
  2. Easier testing
  3. Better maintainability
  4. Reusability
  5. Scalability

5. (ii) Explain Spring MVC request processing and @RequestMapping. Discuss the basic configuration required for an MVC application. (2 marks)

Answer:

Request Processing Flow:

Browser → DispatcherServlet → HandlerMapping → Controller → ViewResolver → View

Steps:

  1. Browser sends request
  2. DispatcherServlet receives request
  3. HandlerMapping finds controller
  4. Controller method executes
  5. Returns view name
  6. ViewResolver maps to JSP
  7. JSP renders HTML
  8. Response sent to browser

@RequestMapping: Maps URL requests to controller methods.

Class Level:

@Controller
@RequestMapping("/student")
public class StudentController {
}

Method Level:

@RequestMapping("/list")
public String list() {
    return "list";
}

With HTTP Method:

@RequestMapping(value="/save", method=RequestMethod.POST)

Specialized:

@GetMapping("/list")
@PostMapping("/save")
@PutMapping("/update")
@DeleteMapping("/delete")

Basic Configuration:

web.xml:

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Spring Config:

<context:component-scan base-package="com.demo"/>

<bean class="InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>
</bean>

Controller:

@Controller
public class HomeController {
    @RequestMapping("/home")
    public String home(Model model) {
        model.addAttribute("message", "Welcome");
        return "home";
    }
}

6. (i) Explain Spring MVC form handling using the Form Tag Library and validation support. (2 marks)

Answer:

Form Tag Library:

<%@ taglib prefix="form"
    uri="http://www.springframework.org/tags/form"%>

Form Tags: | Tag | Purpose | |—–|———| | <form:form> | Form container | | <form:input> | Text input | | <form:password> | Password input | | <form:textarea> | Multi-line text | | <form:checkbox> | Checkbox | | <form:radiobutton> | Radio button | | <form:select> | Dropdown | | <form:errors> | Display errors |

Example Form:

<form:form modelAttribute="student" action="save" method="post">
    Name: <form:input path="name"/>
    <form:errors path="name" cssClass="error"/><br/>

    Email: <form:input path="email"/>
    <form:errors path="email" cssClass="error"/><br/>

    Age: <form:input path="age"/>
    <form:errors path="age" cssClass="error"/><br/>

    <input type="submit" value="Save"/>
</form:form>

Validation Annotations:

public class Student {
    @NotEmpty(message = "Name is required")
    private String name;

    @Email(message = "Invalid email")
    private String email;

    @Min(value = 18, message = "Age must be at least 18")
    private int age;
}

Controller:

@PostMapping("/save")
public String save(@Valid @ModelAttribute("student") Student student,
                   BindingResult result) {
    if (result.hasErrors()) {
        return "form";
    }
    return "success";
}

Flow:

  1. User fills form
  2. Submits POST request
  3. Spring binds data to Student object
  4. @Valid triggers validation
  5. If errors → BindingResult has errors → return to form
  6. If valid → process → return success

Advantages:

  1. Automatic data binding
  2. Declarative validation
  3. Error display
  4. Reusable

6. (ii) Explain bean scopes and lifecycle callbacks in Spring with suitable examples. (2 marks)

Answer:

Bean Scopes:

ScopeDescription
SingletonOne instance per container (default)
PrototypeNew instance per request
RequestOne per HTTP request
SessionOne per HTTP session
ApplicationOne per ServletContext
WebSocketOne per WebSocket session

Example:

@Component
@Scope("singleton")
public class Student {
}

@Component
@Scope("prototype")
public class Employee {
}

Lifecycle Callbacks:

@PostConstruct: Called after bean initialization.

@PostConstruct
public void init() {
    System.out.println("Bean initialized");
}

@PreDestroy: Called before bean destruction.

@PreDestroy
public void destroy() {
    System.out.println("Bean destroyed");
}

Complete Example:

@Component
@Scope("singleton")
public class Student {

    public Student() {
        System.out.println("1. Constructor");
    }

    @Autowired
    public void setDao(StudentDAO dao) {
        System.out.println("2. Setter");
    }

    @PostConstruct
    public void init() {
        System.out.println("3. Init");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("4. Destroy");
    }
}

Output:

1. Constructor
2. Setter
3. Init
(bean in use)
4. Destroy

Lifecycle Phases:

  1. Instantiation
  2. Dependency Injection
  3. @PostConstruct
  4. Bean Ready
  5. @PreDestroy
  6. Bean Removed

7. (i) Explain the complete JDBC database access procedure, including connection establishment, Statement creation, SQL execution, ResultSet processing, closing resources and exception handling. (2 marks)

Answer:

Complete JDBC Procedure:

Step 1: Load Driver

Class.forName("com.mysql.cj.jdbc.Driver");

Step 2: Establish Connection

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

Step 3: Create Statement

Statement stmt = con.createStatement();

Step 4: Execute Query

ResultSet rs = stmt.executeQuery("SELECT * FROM student");

Step 5: Process ResultSet

while (rs.next()) {
    System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}

Step 6: Close Resources

rs.close();
stmt.close();
con.close();

Step 7: Exception Handling

try {
    // JDBC operations
} catch (SQLException e) {
    e.printStackTrace();
} catch (ClassNotFoundException e) {
    System.out.println("Driver not found");
}

Complete Program:

import java.sql.*;

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

                while (rs.next()) {
                    System.out.println(rs.getInt("id") + " " + rs.getString("name"));
                }
            }
        } catch (ClassNotFoundException e) {
            System.out.println("Driver not found");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

try-with-resources: Automatically closes resources.

try (Connection con = ...;
     Statement stmt = ...;
     ResultSet rs = ...) {
    // Use resources
}   // Auto-close

Best Practices:

  1. Use Type 4 driver
  2. Use PreparedStatement
  3. Close resources
  4. Handle exceptions
  5. Use connection pooling

7. (ii) Explain the structure of a Java Swing front-end application. Describe a calculator case study using containers, controls and event handling. (2 marks)

Answer:

Swing Application Structure:

JFrame (Main Window)
    ├── JPanel (Container)
    │   ├── JLabel
    │   ├── JTextField
    │   └── JButton
    └── JPanel (Another Container)
        └── JTable

Calculator Case Study:

Components:

  • JFrame: Main window
  • JTextField: Display
  • JButton: Digits and operations
  • JPanel: Button grouping
  • GridLayout: Button arrangement

Code:

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

public class Calculator {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Calculator");
        JTextField display = new JTextField();
        display.setEditable(false);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(4, 4, 5, 5));

        String[] buttons = {
            "7", "8", "9", "/",
            "4", "5", "6", "*",
            "1", "2", "3", "-",
            "0", ".", "=", "+"
        };

        StringBuilder expression = new StringBuilder();

        for (String text : buttons) {
            JButton btn = new JButton(text);
            btn.addActionListener(e -> {
                String cmd = btn.getText();
                if (cmd.equals("=")) {
                    try {
                        double result = evaluate(expression.toString());
                        display.setText(String.valueOf(result));
                        expression.setLength(0);
                    } catch (Exception ex) {
                        display.setText("Error");
                    }
                } else {
                    expression.append(cmd);
                    display.setText(expression.toString());
                }
            });
            panel.add(btn);
        }

        frame.add(display, BorderLayout.NORTH);
        frame.add(panel, BorderLayout.CENTER);
        frame.setSize(300, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

Event Handling:

  • Each button has an ActionListener
  • Lambda expression handles clicks
  • = evaluates expression
  • Other buttons append to expression

Layout:

[        10        ]
[7] [8] [9] [ / ]
[4] [5] [6] [ * ]
[1] [2] [3] [ - ]
[0] [.] [=] [ + ]

Key Concepts:

  1. JFrame as top-level container
  2. JPanel for grouping
  3. GridLayout for buttons
  4. ActionListener for events
  5. JTextField for display

8. (i) Explain Dependency Injection in Spring with constructor, setter and field injection. State the advantages of using IoC and DI in application development. (2 marks)

Answer:

Dependency Injection (DI): Process of providing dependencies to an object from outside.

Constructor Injection:

public class StudentService {
    private final StudentDAO dao;

    public StudentService(StudentDAO dao) {
        this.dao = dao;
    }
}

Setter Injection:

public class StudentService {
    private StudentDAO dao;

    public void setDao(StudentDAO dao) {
        this.dao = dao;
    }
}

Field Injection:

@Service
public class StudentService {
    @Autowired
    private StudentDAO dao;
}

Comparison:

AspectConstructorSetterField
Injection PointConstructorSetterField
MandatoryYesNoYes
ImmutabilityYesNoNo
TestabilityBestGoodPoor
RecommendedYesYesNo

Advantages of IoC and DI:

  1. Loose Coupling: Objects don’t create their dependencies
  2. Easier Testing: Dependencies can be mocked
  3. Better Maintainability: Changes in one place
  4. Reusability: Beans can be reused
  5. Scalability: Container manages resources
  6. Configuration Flexibility: XML, annotations, Java config
  7. Lifecycle Management: Container manages bean lifecycle

Example:

// Without DI (tight coupling)
public class StudentService {
    private StudentDAO dao = new StudentDAO();
}

// With DI (loose coupling)
@Service
public class StudentService {
    @Autowired
    private StudentDAO dao;
}

8. (ii) Explain Spring MVC Form Tag Library and Spring Validation. Describe how a form is submitted and validated in a controller. (2 marks)

Answer:

Form Tag Library:

<%@ taglib prefix="form"
    uri="http://www.springframework.org/tags/form"%>

Tags: | Tag | Purpose | |—–|———| | <form:form> | Form container | | <form:input> | Text input | | <form:errors> | Display errors | | <form:select> | Dropdown | | <form:checkbox> | Checkbox |

Form Example:

<form:form modelAttribute="student" action="save" method="post">
    Name: <form:input path="name"/>
    <form:errors path="name" cssClass="error"/><br/>

    Email: <form:input path="email"/>
    <form:errors path="email" cssClass="error"/><br/>

    <input type="submit" value="Save"/>
</form:form>

Validation Annotations:

public class Student {
    @NotEmpty(message = "Name is required")
    private String name;

    @Email(message = "Invalid email")
    private String email;

    @Min(value = 18, message = "Age must be at least 18")
    private int age;
}

Controller:

@PostMapping("/save")
public String save(@Valid @ModelAttribute("student") Student student,
                   BindingResult result) {
    if (result.hasErrors()) {
        return "form";
    }
    return "success";
}

Form Submission Flow:

  1. User opens form (GET /form)
  2. Controller adds empty Student to model
  3. Form displayed
  4. User fills form → POST /save
  5. Spring binds data to Student object
  6. @Valid triggers validation
  7. If errors → BindingResult has errors → return to form
  8. If valid → process data → return success

Advantages:

  1. Automatic data binding
  2. Declarative validation
  3. Error display
  4. Type safety

9. (i) Explain JDBC transaction processing and exception handling. Discuss commit(), rollback() and SQLException. (2 marks)

Answer:

Transaction Processing: A transaction is a group of SQL operations executed as a single unit.

ACID Properties:

  • Atomicity: All operations succeed or fail together
  • Consistency: Database remains valid
  • Isolation: Transactions execute independently
  • Durability: Changes remain permanent

Auto-commit Mode: By default, JDBC uses auto-commit mode.

con.setAutoCommit(false);  // Disable

Commit: Saves changes permanently.

con.commit();

Rollback: Undoes changes.

con.rollback();

Example:

try {
    con.setAutoCommit(false);
    stmt.executeUpdate("UPDATE account SET balance=balance-1000 WHERE id=1");
    stmt.executeUpdate("UPDATE account SET balance=balance+1000 WHERE id=2");
    con.commit();
    System.out.println("Transfer successful");
} catch (SQLException e) {
    con.rollback();
    System.out.println("Transfer failed: " + e.getMessage());
}

SQLException: Main exception class in JDBC.

catch (SQLException e) {
    System.out.println("Message: " + e.getMessage());
    System.out.println("Error Code: " + e.getErrorCode());
    System.out.println("SQL State: " + e.getSQLState());
}

Savepoints: Partial rollback points.

Savepoint sp = con.setSavepoint();
con.rollback(sp);

Best Practices:

  1. Disable auto-commit for transactions
  2. Commit on success
  3. Rollback on error
  4. Close resources
  5. Handle SQLException

9. (ii) Explain Spring MVC request mapping and form validation with a suitable application flow. (2 marks)

Answer:

Request Mapping: Maps URL requests to controller methods.

Class Level:

@Controller
@RequestMapping("/student")
public class StudentController {
}

Method Level:

@RequestMapping("/list")
public String list() {
    return "list";
}

Specialized:

@GetMapping("/list")
@PostMapping("/save")
@PutMapping("/update")
@DeleteMapping("/delete")

Form Validation:

public class Student {
    @NotEmpty(message = "Name is required")
    private String name;

    @Email(message = "Invalid email")
    private String email;
}

Controller:

@PostMapping("/save")
public String save(@Valid @ModelAttribute("student") Student student,
                   BindingResult result) {
    if (result.hasErrors()) {
        return "form";
    }
    return "success";
}

Application Flow:

1. User opens /student/form (GET)
2. Controller adds empty Student to model
3. Form displayed with form tags
4. User fills form → POST /student/save
5. Spring binds data to Student object
6. @Valid triggers validation
7. If errors → BindingResult has errors → return "form"
8. If valid → process data → return "success"
9. ViewResolver maps to success.jsp
10. Success page displayed

Example:

@Controller
@RequestMapping("/student")
public class StudentController {

    @GetMapping("/form")
    public String showForm(Model model) {
        model.addAttribute("student", new Student());
        return "form";
    }

    @PostMapping("/save")
    public String save(@Valid @ModelAttribute("student") Student student,
                       BindingResult result) {
        if (result.hasErrors()) {
            return "form";
        }
        return "success";
    }
}

Advantages:

  1. Declarative mapping
  2. Automatic data binding
  3. Validation support
  4. Error handling

10. (i) Explain JDBC transaction management with a suitable example. Discuss auto-commit, commit, rollback and exception handling in a database application. (2 marks)

Answer:

Transaction Management: A transaction is a group of SQL operations executed as a single unit.

Auto-commit: By default, each statement is committed automatically.

con.setAutoCommit(false);  // Disable

Commit: Saves changes permanently.

con.commit();

Rollback: Undoes changes.

con.rollback();

Example — Bank Transfer:

import java.sql.*;

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

            con.setAutoCommit(false);

            try {
                PreparedStatement debit = con.prepareStatement(
                    "UPDATE account SET balance=balance-? WHERE id=?");
                debit.setDouble(1, 1000);
                debit.setInt(2, 1);
                debit.executeUpdate();

                PreparedStatement credit = con.prepareStatement(
                    "UPDATE account SET balance=balance+? WHERE id=?");
                credit.setDouble(1, 1000);
                credit.setInt(2, 2);
                credit.executeUpdate();

                con.commit();
                System.out.println("Transfer successful");
            } catch (SQLException e) {
                con.rollback();
                System.out.println("Transfer failed. Rolled back.");
            }

            con.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Exception Handling:

catch (SQLException e) {
    System.out.println("Error: " + e.getMessage());
    System.out.println("Code: " + e.getErrorCode());
    System.out.println("State: " + e.getSQLState());
}

ACID Properties:

  • Atomicity: Both updates succeed or fail together
  • Consistency: Total balance remains unchanged
  • Isolation: Transaction is independent
  • Durability: Changes persist after commit

Savepoints:

Savepoint sp = con.setSavepoint();
con.rollback(sp);

10. (ii) Explain a Swing-based database application. Describe the steps for creating a GUI, accepting user input and performing database operations. (2 marks)

Answer:

Swing-Based Database Application:

Steps:

Step 1: Create GUI

JFrame f = new JFrame("Student Management");
JLabel l1 = new JLabel("Name:");
JTextField tf1 = new JTextField();
JLabel l2 = new JLabel("Age:");
JTextField tf2 = new JTextField();
JButton save = new JButton("Save");
JButton view = new JButton("View All");
JTable table = new JTable(model);

Step 2: Layout Components

f.setLayout(new BorderLayout());
JPanel formPanel = new JPanel(new GridLayout(3, 2));
formPanel.add(l1); formPanel.add(tf1);
formPanel.add(l2); formPanel.add(tf2);
formPanel.add(save);
f.add(formPanel, BorderLayout.NORTH);
f.add(new JScrollPane(table), BorderLayout.CENTER);

Step 3: Accept User Input

String name = tf1.getText();
int age = Integer.parseInt(tf2.getText());

Step 4: Perform Database Operations

save.addActionListener(e -> {
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection con = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/school", "root", "root");

        PreparedStatement ps = con.prepareStatement(
            "INSERT INTO student(name, age) VALUES(?, ?)");
        ps.setString(1, tf1.getText());
        ps.setInt(2, Integer.parseInt(tf2.getText()));
        ps.executeUpdate();

        JOptionPane.showMessageDialog(f, "Saved!");
        con.close();
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(f, "Error: " + ex.getMessage());
    }
});

Step 5: Display Data in JTable

String[] columns = {"ID", "Name", "Age"};
DefaultTableModel model = new DefaultTableModel(columns, 0);
JTable table = new JTable(model);

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while (rs.next()) {
    model.addRow(new Object[]{
        rs.getInt("id"),
        rs.getString("name"),
        rs.getInt("age")
    });
}

Best Practices:

  1. Use PreparedStatement (prevent SQL injection)
  2. Close resources (try-with-resources)
  3. Use SwingUtilities.invokeLater for thread safety
  4. Handle exceptions with user-friendly messages
  5. Use connection pooling for performance

11. (i) Explain Spring IoC container, Dependency Injection and bean configuration. Compare constructor, setter and field injection with suitable examples. (2 marks)

Answer:

IoC Container: The IoC container creates and manages objects (beans) and injects dependencies.

Types:

  • BeanFactory: Basic container
  • ApplicationContext: Advanced container

Example:

ApplicationContext context =
    new ClassPathXmlApplicationContext("beans.xml");
Student student = context.getBean("student", Student.class);

Bean Configuration:

XML:

<bean id="student" class="com.demo.Student">
    <property name="name" value="Rahul"/>
</bean>

Annotations:

@Component
public class Student {
    @Value("Rahul")
    private String name;
}

Dependency Injection Types:

Constructor Injection:

public class StudentService {
    private final StudentDAO dao;

    public StudentService(StudentDAO dao) {
        this.dao = dao;
    }
}

Setter Injection:

public class StudentService {
    private StudentDAO dao;

    public void setDao(StudentDAO dao) {
        this.dao = dao;
    }
}

Field Injection:

@Service
public class StudentService {
    @Autowired
    private StudentDAO dao;
}

Comparison:

AspectConstructorSetterField
Injection PointConstructorSetterField
MandatoryYesNoYes
ImmutabilityYesNoNo
TestabilityBestGoodPoor
RecommendedYesYesNo

Advantages of IoC and DI:

  1. Loose coupling
  2. Easier testing
  3. Better maintainability
  4. Reusability
  5. Scalability

11. (ii) Explain Spring MVC Form Tag Library and validation. Discuss request mapping, form submission and validation error handling. (2 marks)

Answer:

Form Tag Library:

<%@ taglib prefix="form"
    uri="http://www.springframework.org/tags/form"%>

Form Tags: | Tag | Purpose | |—–|———| | <form:form> | Form container | | <form:input> | Text input | | <form:errors> | Display errors | | <form:select> | Dropdown |

Form Example:

<form:form modelAttribute="student" action="save" method="post">
    Name: <form:input path="name"/>
    <form:errors path="name" cssClass="error"/><br/>

    Email: <form:input path="email"/>
    <form:errors path="email" cssClass="error"/><br/>

    <input type="submit" value="Save"/>
</form:form>

Validation Annotations:

public class Student {
    @NotEmpty(message = "Name is required")
    private String name;

    @Email(message = "Invalid email")
    private String email;

    @Min(value = 18, message = "Age must be at least 18")
    private int age;
}

Request Mapping:

@Controller
@RequestMapping("/student")
public class StudentController {

    @GetMapping("/form")
    public String showForm(Model model) {
        model.addAttribute("student", new Student());
        return "form";
    }

    @PostMapping("/save")
    public String save(@Valid @ModelAttribute("student") Student student,
                       BindingResult result) {
        if (result.hasErrors()) {
            return "form";
        }
        return "success";
    }
}

Form Submission Flow:

  1. User opens /student/form (GET)
  2. Controller adds empty Student to model
  3. Form displayed
  4. User fills form → POST /student/save
  5. Spring binds data to Student object
  6. @Valid triggers validation
  7. If errors → BindingResult has errors → return “form”
  8. If valid → process data → return “success”

Validation Error Handling:

  • <form:errors> displays errors
  • BindingResult contains errors
  • CSS class for styling errors

Advantages:

  1. Automatic data binding
  2. Declarative validation
  3. Error display
  4. Type safety

12. (i) Explain the working of a Swing front-end application and the steps involved in developing a custom graphical calculator or data entry form using Swing. (2 marks)

Answer:

Swing Front-End Application: A Swing application consists of:

  • JFrame: Main window
  • JPanel: Container for grouping
  • Components: JLabel, JTextField, JButton, etc.
  • Layout Managers: FlowLayout, BorderLayout, GridLayout
  • Event Listeners: ActionListener, MouseListener

Steps to Develop Calculator:

Step 1: Create JFrame

JFrame frame = new JFrame("Calculator");
frame.setSize(300, 400);
frame.setLayout(new BorderLayout());

Step 2: Create Display

JTextField display = new JTextField();
display.setHorizontalAlignment(JTextField.RIGHT);
display.setEditable(false);
frame.add(display, BorderLayout.NORTH);

Step 3: Create Buttons Panel

JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4, 5, 5));

Step 4: Add Buttons

String[] buttons = {
    "7", "8", "9", "/",
    "4", "5", "6", "*",
    "1", "2", "3", "-",
    "0", ".", "=", "+"
};

for (String text : buttons) {
    JButton btn = new JButton(text);
    panel.add(btn);
}
frame.add(panel, BorderLayout.CENTER);

Step 5: Event Handling

for (Component c : panel.getComponents()) {
    JButton btn = (JButton) c;
    btn.addActionListener(e -> {
        String cmd = btn.getText();
        if (cmd.equals("=")) {
            // Evaluate
        } else {
            // Append
        }
    });
}

Step 6: Make Visible

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

Complete Code:

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

public class Calculator {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Calculator");
        JTextField display = new JTextField();
        display.setEditable(false);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(4, 4, 5, 5));

        String[] buttons = {
            "7", "8", "9", "/",
            "4", "5", "6", "*",
            "1", "2", "3", "-",
            "0", ".", "=", "+"
        };

        StringBuilder expression = new StringBuilder();

        for (String text : buttons) {
            JButton btn = new JButton(text);
            btn.addActionListener(e -> {
                String cmd = btn.getText();
                if (cmd.equals("=")) {
                    try {
                        double result = evaluate(expression.toString());
                        display.setText(String.valueOf(result));
                        expression.setLength(0);
                    } catch (Exception ex) {
                        display.setText("Error");
                    }
                } else {
                    expression.append(cmd);
                    display.setText(expression.toString());
                }
            });
            panel.add(btn);
        }

        frame.add(display, BorderLayout.NORTH);
        frame.add(panel, BorderLayout.CENTER);
        frame.setSize(300, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

Data Entry Form: Similar steps but with:

  • JLabel for field names
  • JTextField for input
  • JButton for submit
  • JTable for display
  • JDBC for database operations

12. (ii) Explain Spring MVC configuration, @RequestMapping and Spring Validation with suitable examples. (2 marks)

Answer:

Spring MVC Configuration:

web.xml:

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Spring Config:

<context:component-scan base-package="com.demo"/>

<bean class="InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>
</bean>

@RequestMapping:

@Controller
@RequestMapping("/student")
public class StudentController {

    @GetMapping("/form")
    public String showForm(Model model) {
        model.addAttribute("student", new Student());
        return "form";
    }

    @PostMapping("/save")
    public String save(@Valid @ModelAttribute("student") Student student,
                       BindingResult result) {
        if (result.hasErrors()) {
            return "form";
        }
        return "success";
    }
}

Spring Validation:

public class Student {
    @NotEmpty(message = "Name is required")
    private String name;

    @Email(message = "Invalid email")
    private String email;

    @Min(value = 18, message = "Age must be at least 18")
    private int age;
}

Form:

<form:form modelAttribute="student" action="save" method="post">
    Name: <form:input path="name"/>
    <form:errors path="name" cssClass="error"/><br/>

    Email: <form:input path="email"/>
    <form:errors path="email" cssClass="error"/><br/>

    Age: <form:input path="age"/>
    <form:errors path="age" cssClass="error"/><br/>

    <input type="submit" value="Save"/>
</form:form>

Flow:

  1. User opens /student/form
  2. Controller adds empty Student
  3. Form displayed
  4. User fills → POST /student/save
  5. Spring binds data
  6. @Valid triggers validation
  7. If errors → return form
  8. If valid → return success

Advantages:

  1. Automatic binding
  2. Declarative validation
  3. Error display
  4. Type safety

13. (i) Explain batch processing in JDBC using Statement and PreparedStatement. Discuss the execution of bulk updates and performance tuning. (2 marks)

Answer:

Batch Processing: Executes multiple SQL statements together in one trip to the database.

Using Statement:

Statement stmt = con.createStatement();
stmt.addBatch("INSERT INTO student VALUES(1,'A')");
stmt.addBatch("INSERT INTO student VALUES(2,'B')");
stmt.addBatch("INSERT INTO student VALUES(3,'C')");
int[] result = stmt.executeBatch();

Using PreparedStatement:

PreparedStatement ps = con.prepareStatement(
    "INSERT INTO student VALUES(?,?)");

ps.setInt(1, 1);
ps.setString(2, "A");
ps.addBatch();

ps.setInt(1, 2);
ps.setString(2, "B");
ps.addBatch();

ps.setInt(1, 3);
ps.setString(2, "C");
ps.addBatch();

int[] result = ps.executeBatch();

Benefits:

  1. Fewer database calls
  2. Faster execution
  3. Better scalability
  4. Reduced network traffic

Performance Tuning: | Technique | Benefit | |———–|———| | Batch Processing | Reduces round trips | | PreparedStatement | Precompiled, faster | | Connection Pooling | Reuses connections | | Proper Indexing | Faster queries |

Best Practices:

  1. Use PreparedStatement for batch
  2. Set batch size (e.g., 1000)
  3. Commit periodically
  4. Handle exceptions
  5. Close resources

Example — Bulk Insert:

PreparedStatement ps = con.prepareStatement(
    "INSERT INTO student VALUES(?,?)");

for (int i = 1; i <= 10000; i++) {
    ps.setInt(1, i);
    ps.setString(2, "Student" + i);
    ps.addBatch();

    if (i % 1000 == 0) {
        ps.executeBatch();
    }
}
ps.executeBatch();

Applications:

  1. Payroll processing
  2. Student result upload
  3. Bulk data import
  4. Inventory updates

13. (ii) Explain advanced Swing container panes such as JTabbedPane, JSplitPane, and JScrollPane with practical UI use cases. (2 marks)

Answer:

JTabbedPane: Presents multiple tabs for switching panels.

JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Home", new JPanel());
tabbedPane.addTab("Profile", new JPanel());
tabbedPane.addTab("Settings", new JPanel());

Use Cases:

  • Preferences dialogs
  • Multi-step forms
  • Dashboard with sections

JSplitPane: Divides area into two resizable parts.

JSplitPane splitPane = new JSplitPane(
    JSplitPane.HORIZONTAL_SPLIT,
    new JList<>(items),
    new JTextArea());

Use Cases:

  • File explorer (tree + content)
  • Email client (list + message)
  • IDE (editor + console)

JScrollPane: Provides scrolling for components.

JTextArea textArea = new JTextArea(20, 40);
JScrollPane scrollPane = new JScrollPane(textArea);

Use Cases:

  • Long text areas
  • Large tables
  • Image viewers

Comparison:

ComponentPurposeUse Case
JTabbedPaneTabbed panelsPreferences
JSplitPaneResizable splitFile explorer
JScrollPaneScrollingLarge content

Complete Example:

JFrame frame = new JFrame("Advanced Containers");
frame.setSize(600, 400);

// JTabbedPane
JTabbedPane tabs = new JTabbedPane();
tabs.addTab("Tab 1", new JLabel("Content 1"));
tabs.addTab("Tab 2", new JLabel("Content 2"));

// JSplitPane
JSplitPane split = new JSplitPane(
    JSplitPane.HORIZONTAL_SPLIT,
    new JList<>(new String[]{"A", "B", "C"}),
    new JTextArea("Details"));

// JScrollPane
JScrollPane scroll = new JScrollPane(
    new JTextArea(20, 40));

frame.add(tabs, BorderLayout.NORTH);
frame.add(split, BorderLayout.CENTER);
frame.setVisible(true);

14. (i) Explain Spring AOP (Aspect-Oriented Programming) concepts including aspects, join points, advice, and pointcuts with code illustrations. (2 marks)

Answer:

Spring AOP: Aspect-Oriented Programming separates cross-cutting concerns (logging, security, transactions) from business logic.

Key Concepts:

ConceptDescription
AspectModule encapsulating cross-cutting concern
Join PointPoint in program execution (method call)
AdviceAction taken at join point
PointcutExpression matching join points
WeavingLinking aspects with objects

Types of Advice: | Advice | When | |——–|——| | @Before | Before method | | @After | After method | | @AfterReturning | After successful return | | @AfterThrowing | After exception | | @Around | Around method |

Example:

@Aspect
@Component
public class LoggingAspect {

    @Before("execution(* com.demo.service.*.*(..))")
    public void logBefore(JoinPoint jp) {
        System.out.println("Calling: " + jp.getSignature());
    }

    @AfterReturning(pointcut = "execution(* com.demo.service.*.*(..))",
                    returning = "result")
    public void logAfter(JoinPoint jp, Object result) {
        System.out.println("Result: " + result);
    }

    @Around("execution(* com.demo.service.*.*(..))")
    public Object logTime(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        long time = System.currentTimeMillis() - start;
        System.out.println("Time: " + time + "ms");
        return result;
    }
}

Pointcut Expressions:

  • execution(* com.demo.*.*(..)) — Any method
  • within(com.demo.service.*) — Any method in package
  • @annotation(Loggable) — Methods with annotation

Benefits:

  1. Separation of concerns
  2. Reusable aspects
  3. Cleaner business logic
  4. Centralized logging/security

14. (ii) Explain RESTful web services in Spring Boot using @RestController, @GetMapping, and @PostMapping annotations. (2 marks)

Answer:

RESTful Web Services: Representational State Transfer — architectural style for web services.

@RestController: Combines @Controller and @ResponseBody.

@RestController
@RequestMapping("/api/students")
public class StudentRestController {
}

@GetMapping: Handles HTTP GET requests.

@GetMapping
public List<Student> getAll() {
    return studentService.findAll();
}

@GetMapping("/{id}")
public Student getById(@PathVariable int id) {
    return studentService.findById(id);
}

@PostMapping: Handles HTTP POST requests.

@PostMapping
public Student create(@RequestBody Student student) {
    return studentService.save(student);
}

@PutMapping:

@PutMapping("/{id}")
public Student update(@PathVariable int id, @RequestBody Student student) {
    student.setId(id);
    return studentService.update(student);
}

@DeleteMapping:

@DeleteMapping("/{id}")
public void delete(@PathVariable int id) {
    studentService.delete(id);
}

Complete Example:

@RestController
@RequestMapping("/api/students")
public class StudentRestController {

    @Autowired
    private StudentService service;

    @GetMapping
    public List<Student> getAll() {
        return service.findAll();
    }

    @GetMapping("/{id}")
    public ResponseEntity<Student> getById(@PathVariable int id) {
        Student s = service.findById(id);
        return s != null ? ResponseEntity.ok(s) : ResponseEntity.notFound().build();
    }

    @PostMapping
    public Student create(@RequestBody Student student) {
        return service.save(student);
    }

    @PutMapping("/{id}")
    public Student update(@PathVariable int id, @RequestBody Student student) {
        student.setId(id);
        return service.update(student);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable int id) {
        service.delete(id);
        return ResponseEntity.noContent().build();
    }
}

Benefits:

  1. Simple annotations
  2. Automatic JSON conversion
  3. RESTful design
  4. Easy integration

15. (i) Explain scrollable and updatable ResultSets in JDBC. Discuss TYPE_SCROLL_SENSITIVE and concurrency modes. (2 marks)

Answer:

ResultSet Types:

TypeDescription
TYPE_FORWARD_ONLYForward only (default)
TYPE_SCROLL_INSENSITIVEScrollable; not sensitive to changes
TYPE_SCROLL_SENSITIVEScrollable; sensitive to changes

Creating Scrollable ResultSet:

Statement stmt = con.createStatement(
    ResultSet.TYPE_SCROLL_SENSITIVE,
    ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("SELECT * FROM student");

Cursor Navigation:

rs.first();      // First row
rs.last();       // Last row
rs.next();       // Next row
rs.previous();   // Previous row
rs.absolute(3);  // Absolute position
rs.relative(-1); // Relative position

Updatable ResultSet:

Statement stmt = con.createStatement(
    ResultSet.TYPE_SCROLL_SENSITIVE,
    ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT * FROM student");

rs.absolute(1);
rs.updateString("name", "Amit");
rs.updateRow();

Concurrency Modes:

ModeDescription
CONCUR_READ_ONLYRead-only (default)
CONCUR_UPDATABLEUpdatable

TYPE_SCROLL_SENSITIVE:

  • Scrollable
  • Reflects changes made by others
  • More overhead

Comparison:

FeatureTYPE_SCROLL_INSENSITIVETYPE_SCROLL_SENSITIVE
ScrollableYesYes
Sensitive to changesNoYes
PerformanceFasterSlower
Use CaseRead-only reportsReal-time data

Example:

Statement stmt = con.createStatement(
    ResultSet.TYPE_SCROLL_SENSITIVE,
    ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT * FROM student");

rs.last();
System.out.println("Last row: " + rs.getString("name"));

rs.absolute(2);
rs.updateString("name", "Updated");
rs.updateRow();

15. (ii) Explain custom painting and graphics rendering in Java Swing using JPanel and paintComponent(). (2 marks)

Answer:

Custom Painting: Drawing custom graphics on Swing components by overriding paintComponent().

Steps:

Step 1: Create Custom JPanel

public class MyPanel extends JPanel {
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        // Custom drawing here
    }
}

Step 2: Draw Shapes

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    // Set color
    g.setColor(Color.RED);

    // Draw rectangle
    g.drawRect(50, 50, 100, 50);
    g.fillRect(50, 50, 100, 50);

    // Draw circle
    g.setColor(Color.BLUE);
    g.drawOval(200, 50, 80, 80);
    g.fillOval(200, 50, 80, 80);

    // Draw line
    g.drawLine(50, 150, 300, 150);

    // Draw text
    g.setColor(Color.BLACK);
    g.drawString("Hello Swing", 100, 200);
}

Step 3: Use in JFrame

JFrame frame = new JFrame("Custom Painting");
frame.add(new MyPanel());
frame.setSize(400, 300);
frame.setVisible(true);

Graphics2D for Advanced Rendering:

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;

    // Anti-aliasing
    g2d.setRenderingHint(
        RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);

    // Gradient
    GradientPaint gp = new GradientPaint(
        0, 0, Color.RED,
        100, 100, Color.BLUE);
    g2d.setPaint(gp);
    g2d.fillRect(50, 50, 200, 100);
}

Common Methods:

MethodPurpose
drawRect()Rectangle outline
fillRect()Filled rectangle
drawOval()Circle/ellipse outline
fillOval()Filled circle/ellipse
drawLine()Line
drawString()Text
drawImage()Image

Use Cases:

  1. Charts and graphs
  2. Games
  3. Custom UI components
  4. Image editors
  5. Data visualizations

Best Practices:

  1. Always call super.paintComponent(g)
  2. Use Graphics2D for advanced features
  3. Enable anti-aliasing
  4. Avoid heavy operations in paintComponent
  5. Use repaint() to trigger redraw

16. (i) Explain bean definition inheritance and post-processors (BeanPostProcessor) in the Spring framework container. (2 marks)

Answer:

Bean Definition Inheritance: A child bean inherits configuration from a parent bean.

XML Example:

<bean id="parentStudent" class="com.demo.Student" abstract="true">
    <property name="college" value="ABC College"/>
    <property name="city" value="Mumbai"/>
</bean>

<bean id="student1" parent="parentStudent">
    <property name="name" value="Rahul"/>
</bean>

<bean id="student2" parent="parentStudent">
    <property name="name" value="Amit"/>
</bean>

Benefits:

  1. Reduces duplication
  2. Centralized configuration
  3. Easy maintenance

BeanPostProcessor: Interface that allows custom modification of bean instances.

Interface:

public interface BeanPostProcessor {
    Object postProcessBeforeInitialization(Object bean, String beanName);
    Object postProcessAfterInitialization(Object bean, String beanName);
}

Example:

@Component
public class CustomBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(
            Object bean, String beanName) {
        System.out.println("Before init: " + beanName);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(
            Object bean, String beanName) {
        System.out.println("After init: " + beanName);
        return bean;
    }
}

Bean Lifecycle with PostProcessor:

1. Instantiation
2. Dependency Injection
3. postProcessBeforeInitialization()
4. @PostConstruct / afterPropertiesSet()
5. postProcessAfterInitialization()
6. Bean Ready
7. @PreDestroy / destroy()

Use Cases:

  1. Logging
  2. Validation
  3. Custom annotation processing
  4. AOP proxies
  5. Security checks

Complete Example:

@Component
public class Student {
    public Student() {
        System.out.println("1. Constructor");
    }

    @PostConstruct
    public void init() {
        System.out.println("2. @PostConstruct");
    }
}

@Component
public class MyPostProcessor implements BeanPostProcessor {
    public Object postProcessBeforeInitialization(Object bean, String name) {
        System.out.println("Before init: " + name);
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String name) {
        System.out.println("After init: " + name);
        return bean;
    }
}

Output:

1. Constructor
Before init: student
2. @PostConstruct
After init: student

16. (ii) Explain exception handling and global error mapping strategies in a Spring MVC web application. (2 marks)

Answer:

Exception Handling in Spring MVC:

1. @ExceptionHandler (Local): Handles exceptions within a controller.

@Controller
public class StudentController {

    @ExceptionHandler(SQLException.class)
    public String handleSQLException(SQLException e, Model model) {
        model.addAttribute("error", e.getMessage());
        return "error";
    }
}

2. @ControllerAdvice (Global): Handles exceptions across all controllers.

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLException.class)
    public String handleSQLException(SQLException e, Model model) {
        model.addAttribute("error", "Database error: " + e.getMessage());
        return "error";
    }

    @ExceptionHandler(Exception.class)
    public String handleException(Exception e, Model model) {
        model.addAttribute("error", "Unexpected error: " + e.getMessage());
        return "error";
    }
}

3. @ResponseStatus: Maps exception to HTTP status code.

@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException(String message) {
        super(message);
    }
}

4. ResponseEntityExceptionHandler: Extend for REST API error handling.

@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<Object> handleNotFound(
            ResourceNotFoundException e) {
        return new ResponseEntity<>(
            e.getMessage(), HttpStatus.NOT_FOUND);
    }
}

5. Error Pages (web.xml):

<error-page>
    <error-code>404</error-code>
    <location>/error/404</location>
</error-page>
<error-page>
    <error-code>500</error-code>
    <location>/error/500</location>
</error-page>

Error Page (error.jsp):

<html>
<body>
    <h2>Error Occurred</h2>
    <p>${error}</p>
</body>
</html>

Best Practices:

  1. Use @ControllerAdvice for global handling
  2. Create custom exceptions
  3. Log exceptions
  4. Provide user-friendly messages
  5. Don’t expose stack traces
  6. Use appropriate HTTP status codes

Complete Example:

@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger =
        LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(SQLException.class)
    public String handleSQL(SQLException e, Model model) {
        logger.error("Database error", e);
        model.addAttribute("error", "Database error occurred");
        return "error";
    }

    @ExceptionHandler(Exception.class)
    public String handleAll(Exception e, Model model) {
        logger.error("Unexpected error", e);
        model.addAttribute("error", "Unexpected error occurred");
        return "error";
    }
}

17. (i) Explain connection pooling concepts and DataSource implementations in enterprise Java applications. (2 marks)

Answer:

Connection Pooling: A pool of reusable database connections.

Without Pooling:

Request → Create Connection → Execute Query → Close Connection

Each request creates a new connection (slow).

With Pooling:

Request → Connection Pool → Database

Connections are reused (fast).

Advantages:

  1. Faster Performance — No connection creation overhead
  2. Reduced Overhead — Reuse existing connections
  3. Better Scalability — Handle more concurrent requests
  4. Resource Management — Limit total connections
  5. Connection Recovery — Handle stale connections

DataSource:javax.sql.DataSource represents a connection pool configuration.

Implementation — HikariCP (Spring Boot default):

@Configuration
public class DataSourceConfig {

    @Bean
    public DataSource dataSource() {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl("jdbc:mysql://localhost:3306/test");
        config.setUsername("root");
        config.setPassword("root");
        config.setMaximumPoolSize(10);
        config.setMinimumIdle(5);
        config.setConnectionTimeout(30000);
        return new HikariDataSource(config);
    }
}

Using DataSource:

@Autowired
private DataSource dataSource;

public void query() throws SQLException {
    try (Connection con = dataSource.getConnection();
         Statement stmt = con.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT * FROM student")) {
        while (rs.next()) {
            System.out.println(rs.getString("name"));
        }
    }
}

Popular Connection Pools:

PoolProviderFeatures
HikariCPBrett WooldridgeFast, lightweight
Tomcat JDBCApacheFeature-rich
DBCPApacheMature
C3P0MchangeLegacy

Configuration Parameters: | Parameter | Purpose | |———–|———| | maxPoolSize | Maximum connections | | minIdle | Minimum idle connections | | connectionTimeout | Wait time for connection | | idleTimeout | Idle connection timeout | | maxLifetime | Maximum connection age |

Best Practices:

  1. Use connection pooling in production
  2. Set appropriate pool sizes
  3. Close connections in try-with-resources
  4. Monitor pool metrics
  5. Handle connection failures

17. (ii) Explain the delegation event model in Java Swing, detailing how events are queued, dispatched, and handled by listeners. (2 marks)

Answer:

Delegation Event Model: Swing follows the Delegation Event Model, where the event source delegates event handling to a listener.

Components:

ComponentRole
SourceComponent that generates event (JButton)
Event ObjectContains event information (ActionEvent)
ListenerReceives and handles event (ActionListener)

Flow:

Button → ActionEvent → ActionListener → actionPerformed()

Event Queue: Events are queued in the Event Dispatch Thread (EDT).

User Click → Event Queue → EDT → Listener

Event Dispatching:

  1. User interacts with component
  2. Event object created
  3. Event added to queue
  4. EDT processes event
  5. Listener’s method called

Listener Registration:

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        System.out.println("Clicked");
    }
});

Using Lambda:

button.addActionListener(e -> System.out.println("Clicked"));

Common Listeners:

ListenerMethodEvent
ActionListeneractionPerformed()Button click
MouseListenermouseClicked()Mouse click
KeyListenerkeyPressed()Key press
WindowListenerwindowClosing()Window close
ListSelectionListenervalueChanged()List selection

Event Adapters: Provide default implementations.

public class Demo extends WindowAdapter {
    public void windowClosing(WindowEvent e) {
        System.exit(0);
    }
}

Thread Safety:

  • All Swing updates must be on EDT
  • Use SwingUtilities.invokeLater() for updates from other threads
SwingUtilities.invokeLater(() -> {
    label.setText("Updated");
});

Complete Example:

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

public class EventDemo {
    public static void main(String[] args) {
        JFrame f = new JFrame("Event Demo");
        JButton b = new JButton("Click Me");
        b.setBounds(100, 100, 120, 40);

        b.addActionListener(e ->
            JOptionPane.showMessageDialog(f, "Button Clicked!"));

        f.add(b);
        f.setSize(300, 250);
        f.setLayout(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

Key Points:

  1. Delegation model separates source from handler
  2. Events queued in EDT
  3. Listeners handle events
  4. Adapters reduce coding
  5. Thread safety via invokeLater

18. (i) Explain Enterprise JavaBeans (EJB) architecture, distinguishing between stateless, stateful, and message-driven beans. (2 marks)

Answer:

EJB Architecture: Enterprise JavaBeans (EJB) is a server-side component architecture for building enterprise applications.

Components:

Client → EJB Container → EJB → Database

Types of EJB:

1. Stateless Session Bean: Handles business logic without maintaining client state.

@Stateless
public class CalculatorBean {
    public int add(int a, int b) {
        return a + b;
    }
}

Features:

  • No client state
  • Pooled and reusable
  • Scalable
  • Use: Business logic, calculations

2. Stateful Session Bean: Maintains conversational state for a specific client.

@Stateful
public class ShoppingCartBean {
    private List<String> items = new ArrayList<>();

    public void addItem(String item) {
        items.add(item);
    }

    public List<String> getItems() {
        return items;
    }
}

Features:

  • Maintains client state
  • Not pooled
  • Less scalable
  • Use: Shopping carts, wizards

3. Message-Driven Bean: Processes asynchronous messages.

@MessageDriven(activationConfig = {
    @ActivationConfigProperty(
        propertyName = "destination",
        propertyValue = "java:/jms/queue/OrderQueue")
})
public class OrderProcessorBean implements MessageListener {
    public void onMessage(Message message) {
        // Process message
    }
}

Features:

  • Asynchronous
  • JMS-based
  • No client state
  • Use: Order processing, notifications

Comparison:

AspectStatelessStatefulMessage-Driven
StateNoYesNo
PoolingYesNoYes
ScalabilityHighLowHigh
CommunicationSyncSyncAsync
Use CaseBusiness logicShopping cartMessaging

Session Bean Lifecycle:

1. Creation
2. Dependency Injection
3. @PostConstruct
4. Business Methods
5. @PreDestroy
6. Removal

Benefits:

  1. Declarative transactions
  2. Security
  3. Scalability
  4. Clustering
  5. Asynchronous processing

18. (ii) Explain JavaServer Pages (JSP) directives, scripting elements, and custom tag libraries in enterprise web development. (2 marks)

Answer:

JSP Directives: Provide instructions to the JSP container.

Types:

DirectivePurposeExample
pagePage-level settings<%@ page language="java" %>
includeInclude file at translation<%@ include file="header.jsp" %>
taglibUse custom tags<%@ taglib uri="..." prefix="c" %>

Page Directive:

<%@ page language="java" contentType="text/html"
    pageEncoding="UTF-8" errorPage="error.jsp"%>

Include Directive:

<%@ include file="header.jsp"%>

Taglib Directive:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

Scripting Elements:

1. Scriptlet:

<%
    int a = 10;
    int b = 20;
    out.println(a + b);
%>

2. Expression:

<%= 10 + 20 %>

3. Declaration:

<%! int count = 0; %>

Implicit Objects:

ObjectPurpose
requestClient request
responseServer response
outOutput stream
sessionSession management
applicationApplication context
exceptionException handling

Custom Tag Libraries (JSTL):

Core Tags:

<c:out value="Hello"/>
<c:set var="name" value="Java"/>
<c:if test="${10 > 5}">Valid</c:if>
<c:forEach begin="1" end="3" var="i">
    ${i}
</c:forEach>

Formatting Tags:

<fmt:formatNumber value="12345.67" type="currency"/>
<fmt:formatDate value="${today}" pattern="dd-MM-yyyy"/>

SQL Tags:

<sql:query dataSource="${db}" var="result">
    SELECT * FROM student
</sql:query>
<c:forEach var="row" items="${result.rows}">
    ${row.name}
</c:forEach>

JSP Life Cycle:

1. Translation (JSP → Servlet)
2. Compilation (Servlet → .class)
3. Loading
4. Instantiation
5. jspInit()
6. _jspService()
7. jspDestroy()

Best Practices:

  1. Avoid scriptlets (use JSTL/EL)
  2. Use custom tags
  3. Separate concerns (MVC)
  4. Handle exceptions
  5. Use JSTL for logic

19. (i) Explain CallableStatement utilization for executing stored procedures with input, output, and in/out parameters in JDBC. (2 marks)

Answer:

CallableStatement: Used to execute stored procedures in the database.

Creating CallableStatement:

CallableStatement cs = con.prepareCall("{call procedureName(?, ?)}");

Input Parameters:

CallableStatement cs = con.prepareCall("{call getStudent(?)}");
cs.setInt(1, 101);
ResultSet rs = cs.executeQuery();

Output Parameters:

CallableStatement cs = con.prepareCall("{call getStudentCount(?)}");
cs.registerOutParameter(1, Types.INTEGER);
cs.execute();
int count = cs.getInt(1);

IN/OUT Parameters:

CallableStatement cs = con.prepareCall("{call updateAndGet(?, ?)}");
cs.setString(1, "Rahul");                    // IN
cs.registerOutParameter(2, Types.VARCHAR);   // OUT
cs.execute();
String result = cs.getString(2);

Stored Procedure Example:

CREATE PROCEDURE getStudents()
BEGIN
    SELECT * FROM student;
END;

CREATE PROCEDURE getStudentById(IN sid INT)
BEGIN
    SELECT * FROM student WHERE id = sid;
END;

CREATE PROCEDURE getCount(OUT total INT)
BEGIN
    SELECT COUNT(*) INTO total FROM student;
END;

Java Code:

// No parameters
CallableStatement cs1 = con.prepareCall("{call getStudents()}");
ResultSet rs1 = cs1.executeQuery();

// IN parameter
CallableStatement cs2 = con.prepareCall("{call getStudentById(?)}");
cs2.setInt(1, 101);
ResultSet rs2 = cs2.executeQuery();

// OUT parameter
CallableStatement cs3 = con.prepareCall("{call getCount(?)}");
cs3.registerOutParameter(1, Types.INTEGER);
cs3.execute();
int count = cs3.getInt(1);
System.out.println("Total: " + count);

Parameter Types:

TypeMethodPurpose
INsetInt(), setString()Input value
OUTregisterOutParameter()Output value
INOUTBothBoth

Advantages:

  1. Executes stored procedures
  2. Better performance
  3. Reduced network traffic
  4. Reusable business logic
  5. Security (permissions)

Best Practices:

  1. Use CallableStatement for procedures
  2. Register OUT parameters before execute
  3. Close resources
  4. Handle SQLException
  5. Use try-with-resources

19. (ii) Explain JTable component architecture in Java Swing, including TableModel, cell rendering, and editing. (2 marks)

Answer:

JTable Architecture: JTable displays data in a tabular format using the MVC pattern.

JTable (View)
    ↓
TableModel (Model)
    ↓
Data (Array/List/DB)

Components:

ComponentPurpose
JTableVisual component
TableModelData model
TableCellRendererRenders cells
TableCellEditorEdits cells

DefaultTableModel:

String[] columns = {"ID", "Name", "Age"};
Object[][] data = {
    {1, "Rahul", 20},
    {2, "Amit", 22}
};
DefaultTableModel model = new DefaultTableModel(data, columns);
JTable table = new JTable(model);

Custom TableModel:

public class StudentTableModel extends AbstractTableModel {
    private String[] columns = {"ID", "Name", "Age"};
    private List<Student> students = new ArrayList<>();

    @Override
    public int getRowCount() { return students.size(); }

    @Override
    public int getColumnCount() { return columns.length; }

    @Override
    public String getColumnName(int col) { return columns[col]; }

    @Override
    public Object getValueAt(int row, int col) {
        Student s = students.get(row);
        switch (col) {
            case 0: return s.getId();
            case 1: return s.getName();
            case 2: return s.getAge();
            default: return null;
        }
    }

    @Override
    public boolean isCellEditable(int row, int col) {
        return col != 0;   // ID not editable
    }

    @Override
    public void setValueAt(Object value, int row, int col) {
        Student s = students.get(row);
        switch (col) {
            case 1: s.setName((String) value); break;
            case 2: s.setAge((int) value); break;
        }
        fireTableCellUpdated(row, col);
    }
}

Cell Rendering:

table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
    @Override
    public Component getTableCellRendererComponent(
            JTable table, Object value, boolean isSelected,
            boolean hasFocus, int row, int col) {
        Component c = super.getTableCellRendererComponent(
            table, value, isSelected, hasFocus, row, col);
        if (row % 2 == 0) {
            c.setBackground(Color.LIGHT_GRAY);
        } else {
            c.setBackground(Color.WHITE);
        }
        return c;
    }
});

Cell Editing:

JComboBox<String> comboBox = new JComboBox<>(
    new String[]{"CSE", "ECE", "MECH"});
table.getColumnModel().getColumn(3).setCellEditor(
    new DefaultCellEditor(comboBox));

Selection Listener:

table.getSelectionModel().addListSelectionListener(e -> {
    int row = table.getSelectedRow();
    if (row != -1) {
        System.out.println("Selected: " + table.getValueAt(row, 1));
    }
});

Loading from Database:

String[] columns = {"ID", "Name", "Age"};
DefaultTableModel model = new DefaultTableModel(columns, 0);

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while (rs.next()) {
    model.addRow(new Object[]{
        rs.getInt("id"),
        rs.getString("name"),
        rs.getInt("age")
    });
}

JTable table = new JTable(model);
JScrollPane scroll = new JScrollPane(table);

Features:

  1. Sorting
  2. Filtering
  3. Column resizing
  4. Row selection
  5. Cell editing

Best Practices:

  1. Use custom TableModel for complex data
  2. Use JScrollPane for scrolling
  3. Handle selection events
  4. Validate edited values
  5. Use renderers for formatting

20. (i) Explain Spring Security architecture basics, including authentication providers, filters, and role-based access control. (2 marks)

Answer:

Spring Security Architecture:

Request → Security Filter Chain → Authentication → Authorization → Resource

Components:

ComponentPurpose
SecurityFilterChainChain of filters
AuthenticationManagerAuthenticates users
AuthenticationProviderProvides authentication
UserDetailsServiceLoads user details
AccessDecisionManagerAuthorization decisions

Authentication Flow:

1. User submits credentials
2. AuthenticationFilter intercepts
3. AuthenticationManager authenticates
4. AuthenticationProvider validates
5. UserDetailsService loads user
6. SecurityContext stores authentication
7. Authorization checks roles

Configuration:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/", "/login").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .requestMatchers("/user/**").hasAnyRole("USER", "ADMIN")
                .anyRequest().authenticated()
            )
            .formLogin(form -> form
                .loginPage("/login")
                .defaultSuccessUrl("/home")
                .permitAll()
            )
            .logout(logout -> logout
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login")
            );
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.builder()
            .username("user")
            .password(passwordEncoder().encode("password"))
            .roles("USER")
            .build();

        UserDetails admin = User.builder()
            .username("admin")
            .password(passwordEncoder().encode("admin"))
            .roles("ADMIN")
            .build();

        return new InMemoryUserDetailsManager(user, admin);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

Role-Based Access Control:

AnnotationPurpose
@PreAuthorizeBefore method
@PostAuthorizeAfter method
@SecuredRole-based
@RolesAllowedJSR-250

Example:

@PreAuthorize("hasRole('ADMIN')")
public void deleteStudent(int id) {
    // Only ADMIN can delete
}

@PreAuthorize("hasAnyRole('USER', 'ADMIN')")
public List<Student> getAll() {
    return studentService.findAll();
}

Authentication Providers:

ProviderPurpose
DaoAuthenticationProviderDatabase users
LdapAuthenticationProviderLDAP
JwtAuthenticationProviderJWT tokens
OAuth2AuthenticationProviderOAuth2

Filters:

  • UsernamePasswordAuthenticationFilter
  • BasicAuthenticationFilter
  • RememberMeAuthenticationFilter
  • AnonymousAuthenticationFilter
  • ExceptionTranslationFilter

Best Practices:

  1. Use BCrypt for passwords
  2. Enable HTTPS
  3. Use CSRF protection
  4. Implement role-based access
  5. Use method-level security
  6. Log security events

20. (ii) Explain internationalization (i18n) and localization support using MessageSource in Spring applications. (2 marks)

Answer:

Internationalization (i18n): Adapting applications to different languages and regions.

Localization (l10n): Adapting to a specific locale.

MessageSource: Spring interface for resolving messages.

Configuration:

@Configuration
public class MessageConfig {

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource =
            new ResourceBundleMessageSource();
        messageSource.setBasename("messages");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver resolver = new SessionLocaleResolver();
        resolver.setDefaultLocale(Locale.US);
        return resolver;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
        interceptor.setParamName("lang");
        return interceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }
}

Properties Files:

messages.properties          (default - English)
messages_fr.properties       (French)
messages_de.properties       (German)
messages_hi.properties       (Hindi)

messages.properties:

greeting=Hello
welcome=Welcome to our application

messages_fr.properties:

greeting=Bonjour
welcome=Bienvenue dans notre application

messages_hi.properties:

greeting=नमस्ते
welcome=हमारे एप्लिकेशन में आपका स्वागत है

Using MessageSource:

@Autowired
private MessageSource messageSource;

public String getMessage(String code, Locale locale) {
    return messageSource.getMessage(code, null, locale);
}

In JSP:

<%@ taglib prefix="spring"
    uri="http://www.springframework.org/tags"%>

<spring:message code="greeting"/>
<spring:message code="welcome"/>

Locale Change:

<a href="?lang=en">English</a>
<a href="?lang=fr">French</a>
<a href="?lang=hi">Hindi</a>

Controller:

@GetMapping("/greet")
public String greet(Model model, Locale locale) {
    String greeting = messageSource.getMessage(
        "greeting", null, locale);
    model.addAttribute("greeting", greeting);
    return "greet";
}

Number Formatting:

<fmt:formatNumber value="12345.67" type="currency"/>

Date Formatting:

<fmt:formatDate value="${today}" pattern="dd-MM-yyyy"/>

Benefits:

  1. Multi-language support
  2. Regional formatting
  3. User-friendly
  4. Easy maintenance
  5. Global reach

Best Practices:

  1. Externalize all messages
  2. Use UTF-8 encoding
  3. Support RTL languages
  4. Format numbers/dates by locale
  5. Test with multiple locales

21. (i) Explain database metadata extraction techniques using DatabaseMetaData for schema inspection and driver compatibility. (2 marks)

Answer:

DatabaseMetaData: Provides information about the database and DBMS.

Obtaining DatabaseMetaData:

DatabaseMetaData dm = con.getMetaData();

Schema Inspection:

Get Database Info:

System.out.println("Product: " + dm.getDatabaseProductName());
System.out.println("Version: " + dm.getDatabaseProductVersion());
System.out.println("Driver: " + dm.getDriverName());
System.out.println("Driver Version: " + dm.getDriverVersion());
System.out.println("URL: " + dm.getURL());
System.out.println("User: " + dm.getUserName());

List Tables:

ResultSet tables = dm.getTables(null, null, "%", new String[]{"TABLE"});
while (tables.next()) {
    System.out.println("Table: " + tables.getString("TABLE_NAME"));
}

List Columns:

ResultSet columns = dm.getColumns(null, null, "student", "%");
while (columns.next()) {
    System.out.println("Column: " + columns.getString("COLUMN_NAME"));
    System.out.println("Type: " + columns.getString("TYPE_NAME"));
    System.out.println("Size: " + columns.getInt("COLUMN_SIZE"));
    System.out.println("Nullable: " + columns.getString("IS_NULLABLE"));
}

Primary Keys:

ResultSet pks = dm.getPrimaryKeys(null, null, "student");
while (pks.next()) {
    System.out.println("PK: " + pks.getString("COLUMN_NAME"));
}

Foreign Keys:

ResultSet fks = dm.getImportedKeys(null, null, "student");
while (fks.next()) {
    System.out.println("FK: " + fks.getString("FKCOLUMN_NAME"));
    System.out.println("References: " + fks.getString("PKTABLE_NAME"));
}

Driver Compatibility:

Check Supported Features:

System.out.println("Supports transactions: " + dm.supportsTransactions());
System.out.println("Supports batch updates: " + dm.supportsBatchUpdates());
System.out.println("Supports stored procedures: " + dm.supportsStoredProcedures());
System.out.println("Supports scrollable ResultSet: " + dm.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE));
System.out.println("Max connections: " + dm.getMaxConnections());
System.out.println("Max table name length: " + dm.getMaxTableNameLength());

Check SQL Support:

System.out.println("Supports SELECT: " + dm.supportsSelectForUpdate());
System.out.println("Supports JOIN: " + dm.supportsOuterJoins());
System.out.println("Supports UNION: " + dm.supportsUnion());

Complete Example:

import java.sql.*;

public class MetadataExample {
    public static void main(String[] args) {
        try {
            Connection con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/test", "root", "root");

            DatabaseMetaData dm = con.getMetaData();

            // Database info
            System.out.println("Database: " + dm.getDatabaseProductName());
            System.out.println("Version: " + dm.getDatabaseProductVersion());

            // Tables
            System.out.println("\nTables:");
            ResultSet tables = dm.getTables(null, null, "%", null);
            while (tables.next()) {
                System.out.println("  " + tables.getString("TABLE_NAME"));
            }

            // Columns
            System.out.println("\nColumns of student:");
            ResultSet cols = dm.getColumns(null, null, "student", "%");
            while (cols.next()) {
                System.out.println("  " + cols.getString("COLUMN_NAME") +
                    " (" + cols.getString("TYPE_NAME") + ")");
            }

            con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Applications:

  1. Dynamic reports
  2. Database analysis
  3. Admin tools
  4. Data migration
  5. Schema documentation

21. (ii) Explain the implementation of popup menus, toolbars, and keyboard accelerators in Java Swing applications. (2 marks)

Answer:

Popup Menus (JPopupMenu): Floating menu that appears on right-click.

JPopupMenu popupMenu = new JPopupMenu();
JMenuItem cutItem = new JMenuItem("Cut");
JMenuItem copyItem = new JMenuItem("Copy");
JMenuItem pasteItem = new JMenuItem("Paste");

popupMenu.add(cutItem);
popupMenu.add(copyItem);
popupMenu.add(pasteItem);

// Show on right-click
textArea.addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
        if (e.isPopupTrigger()) {
            popupMenu.show(e.getComponent(), e.getX(), e.getY());
        }
    }
    public void mouseReleased(MouseEvent e) {
        if (e.isPopupTrigger()) {
            popupMenu.show(e.getComponent(), e.getX(), e.getY());
        }
    }
});

Toolbars (JToolBar): Container for commonly used actions.

JToolBar toolBar = new JToolBar();
toolBar.setFloatable(false);

JButton newBtn = new JButton("New");
JButton openBtn = new JButton("Open");
JButton saveBtn = new JButton("Save");

toolBar.add(newBtn);
toolBar.add(openBtn);
toolBar.addSeparator();
toolBar.add(saveBtn);

frame.add(toolBar, BorderLayout.NORTH);

Keyboard Accelerators: Key combinations that trigger actions.

JMenuItem saveItem = new JMenuItem("Save");
saveItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK));
saveItem.addActionListener(e -> saveFile());

JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_Q, InputEvent.CTRL_DOWN_MASK));
exitItem.addActionListener(e -> System.exit(0));

Menu Bar with Accelerators:

JMenuBar menuBar = new JMenuBar();

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

JMenuItem newItem = new JMenuItem("New");
newItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK));

JMenuItem openItem = new JMenuItem("Open");
openItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK));

JMenuItem saveItem = new JMenuItem("Save");
saveItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK));

JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_Q, InputEvent.CTRL_DOWN_MASK));

fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.addSeparator();
fileMenu.add(exitItem);

menuBar.add(fileMenu);
frame.setJMenuBar(menuBar);

Complete Example:

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

public class MenuDemo {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Menu Demo");

        // Menu Bar
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        fileMenu.setMnemonic(KeyEvent.VK_F);

        JMenuItem newItem = new JMenuItem("New");
        newItem.setAccelerator(KeyStroke.getKeyStroke(
            KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK));

        JMenuItem exitItem = new JMenuItem("Exit");
        exitItem.setAccelerator(KeyStroke.getKeyStroke(
            KeyEvent.VK_Q, InputEvent.CTRL_DOWN_MASK));
        exitItem.addActionListener(e -> System.exit(0));

        fileMenu.add(newItem);
        fileMenu.addSeparator();
        fileMenu.add(exitItem);
        menuBar.add(fileMenu);
        frame.setJMenuBar(menuBar);

        // Toolbar
        JToolBar toolBar = new JToolBar();
        toolBar.add(new JButton("New"));
        toolBar.add(new JButton("Open"));
        toolBar.add(new JButton("Save"));
        frame.add(toolBar, BorderLayout.NORTH);

        // Popup Menu
        JPopupMenu popup = new JPopupMenu();
        popup.add(new JMenuItem("Cut"));
        popup.add(new JMenuItem("Copy"));
        popup.add(new JMenuItem("Paste"));

        JTextArea textArea = new JTextArea();
        textArea.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger())
                    popup.show(e.getComponent(), e.getX(), e.getY());
            }
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger())
                    popup.show(e.getComponent(), e.getX(), e.getY());
            }
        });

        frame.add(new JScrollPane(textArea), BorderLayout.CENTER);
        frame.setSize(500, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

Key Concepts:

ComponentPurpose
JPopupMenuRight-click menu
JToolBarQuick action buttons
JMenuBarMain menu
JMenuDropdown menu
JMenuItemMenu item
AcceleratorKeyboard shortcut
MnemonicAlt+key shortcut

Benefits:

  1. Quick access to actions
  2. Professional look
  3. Keyboard efficiency
  4. Context-sensitive menus
  5. Standard UI patterns

22. (i) Explain Java Servlet filters and listener classes, detailing how they intercept requests and manage application events. (2 marks)

Answer:

Servlet Filters: Intercept requests and responses to perform preprocessing/postprocessing.

Filter Interface:

public interface Filter {
    void init(FilterConfig config);
    void doFilter(ServletRequest req, ServletResponse res, FilterChain chain);
    void destroy();
}

Filter Example:

public class LoggingFilter implements Filter {

    public void init(FilterConfig config) {
        System.out.println("Filter initialized");
    }

    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        System.out.println("Request: " + request.getRequestURI());

        long start = System.currentTimeMillis();

        chain.doFilter(req, res);   // Pass to next filter/servlet

        long time = System.currentTimeMillis() - start;
        System.out.println("Time: " + time + "ms");
    }

    public void destroy() {
        System.out.println("Filter destroyed");
    }
}

Filter Configuration (web.xml):

<filter>
    <filter-name>loggingFilter</filter-name>
    <filter-class>com.demo.LoggingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>loggingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Filter Annotation:

@WebFilter("/*")
public class LoggingFilter implements Filter {
}

Common Filter Uses:

  1. Authentication
  2. Logging
  3. Compression
  4. Character encoding
  5. CORS

Listener Classes: React to application events.

Types:

ListenerEvent
ServletContextListenerContext init/destroy
HttpSessionListenerSession create/destroy
ServletRequestListenerRequest init/destroy
ServletContextAttributeListenerAttribute changes
HttpSessionAttributeListenerSession attribute changes

ServletContextListener Example:

public class AppListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent e) {
        System.out.println("Application started");
        // Initialize resources (DB connection pool, etc.)
    }

    public void contextDestroyed(ServletContextEvent e) {
        System.out.println("Application stopped");
        // Cleanup resources
    }
}

HttpSessionListener Example:

public class SessionListener implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent e) {
        System.out.println("Session created: " + e.getSession().getId());
    }

    public void sessionDestroyed(HttpSessionEvent e) {
        System.out.println("Session destroyed: " + e.getSession().getId());
    }
}

Listener Configuration (web.xml):

<listener>
    <listener-class>com.demo.AppListener</listener-class>
</listener>
<listener>
    <listener-class>com.demo.SessionListener</listener-class>
</listener>

Listener Annotation:

@WebListener
public class AppListener implements ServletContextListener {
}

Filter Chain:

Request → Filter1 → Filter2 → Servlet → Response

Best Practices:

  1. Use filters for cross-cutting concerns
  2. Use listeners for lifecycle events
  3. Keep filters lightweight
  4. Handle exceptions in filters
  5. Order filters carefully

22. (ii) Explain Spring Boot auto-configuration mechanism and starter dependencies in modern microservice architecture. (2 marks)

Answer:

Spring Boot Auto-Configuration: Automatically configures Spring beans based on classpath and properties.

How It Works:

  1. @SpringBootApplication triggers auto-configuration
  2. Spring Boot examines classpath
  3. Applies conditional configuration
  4. Creates beans automatically

@SpringBootApplication:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Equivalent to:

@Configuration
@EnableAutoConfiguration
@ComponentScan

Auto-Configuration Example:

If spring-boot-starter-data-jpa is on classpath:

  • DataSource auto-configured
  • EntityManagerFactory auto-configured
  • TransactionManager auto-configured

application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

Starter Dependencies:

StarterPurpose
spring-boot-starter-webWeb applications
spring-boot-starter-data-jpaJPA/Hibernate
spring-boot-starter-securitySecurity
spring-boot-starter-testTesting
spring-boot-starter-actuatorMonitoring
spring-boot-starter-thymeleafThymeleaf templates
spring-boot-starter-validationValidation

pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

Auto-Configuration Classes:

  • DataSourceAutoConfiguration
  • JpaRepositoriesAutoConfiguration
  • WebMvcAutoConfiguration
  • SecurityAutoConfiguration

Conditional Annotations:

@ConditionalOnClass(DataSource.class)
@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnProperty(name = "spring.datasource.url")

Microservice Architecture:

Spring Boot for Microservices:

@SpringBootApplication
@EnableEurekaClient
public class StudentServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(StudentServiceApplication.class, args);
    }
}

Microservice Features:

  1. Independent deployment
  2. Embedded server (Tomcat)
  3. Externalized configuration
  4. Service discovery (Eureka)
  5. API gateway
  6. Circuit breakers (Hystrix)
  7. Distributed tracing

Example Microservice:

@RestController
@RequestMapping("/api/students")
public class StudentController {

    @Autowired
    private StudentService service;

    @GetMapping
    public List<Student> getAll() {
        return service.findAll();
    }

    @PostMapping
    public Student create(@RequestBody Student student) {
        return service.save(student);
    }
}

Benefits:

  1. Rapid development
  2. Minimal configuration
  3. Production-ready
  4. Microservice-friendly
  5. Cloud-native

Best Practices:

  1. Use starters
  2. Externalize configuration
  3. Use profiles
  4. Enable actuator
  5. Implement health checks

23. (i) Explain transaction propagation levels and isolation levels supported by Spring’s declarative transaction management (@Transactional). (2 marks)

Answer:

@Transactional: Declarative transaction management in Spring.

@Transactional
public void transferMoney(int from, int to, double amount) {
    // Both operations in one transaction
}

Propagation Levels:

PropagationDescription
REQUIREDJoin existing or create new (default)
REQUIRES_NEWAlways create new
SUPPORTSJoin if exists; else no transaction
NOT_SUPPORTEDExecute without transaction
MANDATORYMust have existing; else exception
NEVERMust not have existing; else exception
NESTEDNested transaction with savepoint

Example:

@Transactional(propagation = Propagation.REQUIRED)
public void methodA() {
    methodB();
}

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void methodB() {
    // Always new transaction
}

Isolation Levels:

IsolationDescriptionDirty ReadNon-Repeatable ReadPhantom Read
DEFAULTDatabase default---
READ_UNCOMMITTEDLowestYesYesYes
READ_COMMITTEDRead only committedNoYesYes
REPEATABLE_READSame read → same resultNoNoYes
SERIALIZABLEHighestNoNoNo

Example:

@Transactional(isolation = Isolation.READ_COMMITTED)
public void readData() {
    // Read only committed data
}

Complete Example:

@Service
public class BankService {

    @Transactional(
        propagation = Propagation.REQUIRED,
        isolation = Isolation.READ_COMMITTED,
        timeout = 30,
        rollbackFor = Exception.class
    )
    public void transfer(int from, int to, double amount) {
        accountDao.debit(from, amount);
        accountDao.credit(to, amount);
    }
}

@Transactional Attributes:

AttributePurpose
propagationHow transactions relate
isolationConcurrency control
timeoutMax duration
readOnlyOptimization hint
rollbackForExceptions triggering rollback
noRollbackForExceptions not triggering rollback

Best Practices:

  1. Use REQUIRED (default) for most cases
  2. Use REQUIRES_NEW for independent operations
  3. Use READ_COMMITTED for most applications
  4. Use SERIALIZABLE only when necessary
  5. Specify rollbackFor explicitly
  6. Keep transactions short

23. (ii) Explain tree component structures in Java Swing using JTree, DefaultMutableTreeNode, and tree selection listeners. (2 marks)

Answer:

JTree: Displays hierarchical data as a tree.

DefaultMutableTreeNode: Represents a node in the tree.

DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Child 1");
DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Child 2");

root.add(child1);
root.add(child2);

JTree tree = new JTree(root);

Complete Example:

import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;

public class TreeDemo {
    public static void main(String[] args) {
        // Create root
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Company");

        // Departments
        DefaultMutableTreeNode hr = new DefaultMutableTreeNode("HR");
        DefaultMutableTreeNode it = new DefaultMutableTreeNode("IT");
        DefaultMutableTreeNode finance = new DefaultMutableTreeNode("Finance");

        // Employees
        hr.add(new DefaultMutableTreeNode("Rahul"));
        hr.add(new DefaultMutableTreeNode("Priya"));

        it.add(new DefaultMutableTreeNode("Amit"));
        it.add(new DefaultMutableTreeNode("Neha"));

        finance.add(new DefaultMutableTreeNode("Sara"));

        root.add(hr);
        root.add(it);
        root.add(finance);

        JTree tree = new JTree(root);
        JScrollPane scroll = new JScrollPane(tree);

        // Selection listener
        tree.addTreeSelectionListener(e -> {
            DefaultMutableTreeNode node =
                (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            if (node != null) {
                System.out.println("Selected: " + node.getUserObject());
            }
        });

        JFrame frame = new JFrame("Tree Demo");
        frame.add(scroll);
        frame.setSize(400, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

Tree Selection Listener:

tree.addTreeSelectionListener(new TreeSelectionListener() {
    public void valueChanged(TreeSelectionEvent e) {
        DefaultMutableTreeNode node =
            (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        if (node == null) return;

        if (node.isLeaf()) {
            System.out.println("Leaf: " + node.getUserObject());
        } else {
            System.out.println("Node: " + node.getUserObject());
        }
    }
});

Common Operations:

OperationMethod
Add nodeparent.add(child)
Remove nodeparent.remove(child)
Get user objectnode.getUserObject()
Get parentnode.getParent()
Get childrennode.children()
Check leafnode.isLeaf()

Custom Tree Cell Renderer:

tree.setCellRenderer(new DefaultTreeCellRenderer() {
    @Override
    public Component getTreeCellRendererComponent(
            JTree tree, Object value, boolean selected,
            boolean expanded, boolean leaf, int row, boolean hasFocus) {
        Component c = super.getTreeCellRendererComponent(
            tree, value, selected, expanded, leaf, row, hasFocus);
        if (leaf) {
            setIcon(new ImageIcon("leaf.png"));
        } else {
            setIcon(new ImageIcon("folder.png"));
        }
        return c;
    }
});

Applications:

  1. File explorers
  2. Organization charts
  3. XML viewers
  4. Category browsers
  5. Menu structures

Best Practices:

  1. Use DefaultMutableTreeNode for mutable trees
  2. Add TreeSelectionListener for selection
  3. Use JScrollPane for scrolling
  4. Customize cell renderer for icons
  5. Handle large trees with lazy loading

24. (i) Explain enterprise deployment descriptors (web.xml, ejb-jar.xml) and their evolution toward annotation-based configuration. (2 marks)

Answer:

Deployment Descriptors: XML files that configure Java EE applications.

web.xml: Deployment descriptor for web applications.

<web-app>
    <display-name>My App</display-name>

    <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>com.demo.HelloServlet</servlet-class>
        <init-param>
            <param-name>message</param-name>
            <param-value>Hello World</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>LoggingFilter</filter-name>
        <filter-class>com.demo.LoggingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>LoggingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>com.demo.AppListener</listener-class>
    </listener>

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

    <error-page>
        <error-code>404</error-code>
        <location>/error/404</location>
    </error-page>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

ejb-jar.xml: Deployment descriptor for EJBs.

<ejb-jar>
    <enterprise-beans>
        <session>
            <ejb-name>CalculatorBean</ejb-name>
            <home>com.demo.CalculatorHome</home>
            <remote>com.demo.Calculator</remote>
            <ejb-class>com.demo.CalculatorBean</ejb-class>
            <session-type>Stateless</session-type>
            <transaction-type>Container</transaction-type>
        </session>
    </enterprise-beans>
</ejb-jar>

Evolution to Annotations:

Servlet Annotations:

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req,
                         HttpServletResponse res) {
        // ...
    }
}

@WebFilter("/*")
public class LoggingFilter implements Filter {
}

@WebListener
public class AppListener implements ServletContextListener {
}

EJB Annotations:

@Stateless
public class CalculatorBean {
    public int add(int a, int b) {
        return a + b;
    }
}

@Stateful
public class ShoppingCartBean {
}

@MessageDriven
public class OrderProcessorBean implements MessageListener {
}

Comparison:

Aspectweb.xml/ejb-jar.xmlAnnotations
ConfigurationXMLJava code
ReadabilityVerboseConcise
Type SafetyNoYes
Compile-time CheckNoYes
RefactoringManualIDE support
External ConfigYesLimited
Legacy SupportYesModern

Best Practices:

  1. Use annotations for new applications
  2. Use web.xml for external configuration
  3. Combine both when needed
  4. Keep descriptors minimal
  5. Use annotations for simplicity

24. (ii) Explain MVC architectural separation in Java Swing components and how properties/events coordinate view updates. (2 marks)

Answer:

MVC in Swing: Swing components follow the Model-View-Controller pattern.

Model ← → View ← → Controller
   ↑        ↑         ↑
Data    Display    Input

Components:

ComponentRoleSwing Example
ModelData and stateTableModel, ListModel
ViewVisual representationJTable, JList
ControllerHandles inputListeners

Example — JTable:

TableModel (Model)
    ↓
JTable (View)
    ↓
Listeners (Controller)

Model:

public class StudentTableModel extends AbstractTableModel {
    private List<Student> students = new ArrayList<>();

    public int getRowCount() { return students.size(); }
    public int getColumnCount() { return 3; }

    public Object getValueAt(int row, int col) {
        Student s = students.get(row);
        switch (col) {
            case 0: return s.getId();
            case 1: return s.getName();
            case 2: return s.getAge();
            default: return null;
        }
    }

    public void addStudent(Student s) {
        students.add(s);
        fireTableRowsInserted(students.size() - 1, students.size() - 1);
    }
}

View:

JTable table = new JTable(model);
JScrollPane scroll = new JScrollPane(table);

Controller:

table.getSelectionModel().addListSelectionListener(e -> {
    int row = table.getSelectedRow();
    if (row != -1) {
        // Update form fields
        nameField.setText((String) model.getValueAt(row, 1));
    }
});

Property Change Support:

public class Student {
    private PropertyChangeSupport support = new PropertyChangeSupport(this);
    private String name;

    public void setName(String name) {
        String old = this.name;
        this.name = name;
        support.firePropertyChange("name", old, name);
    }

    public void addPropertyChangeListener(PropertyChangeListener l) {
        support.addPropertyChangeListener(l);
    }
}

Event Coordination:

model.addTableModelListener(e -> {
    // View updates automatically via fireTableDataChanged()
    System.out.println("Table updated");
});

Complete Example:

import javax.swing.*;
import javax.swing.table.*;
import java.util.*;

public class MvcDemo {
    public static void main(String[] args) {
        // Model
        DefaultTableModel model = new DefaultTableModel(
            new String[]{"ID", "Name", "Age"}, 0);

        // View
        JTable table = new JTable(model);
        JScrollPane scroll = new JScrollPane(table);

        // Controller
        JButton addBtn = new JButton("Add");
        addBtn.addActionListener(e -> {
            model.addRow(new Object[]{
                model.getRowCount() + 1, "Student", 20
            });
        });

        JFrame frame = new JFrame("MVC Demo");
        frame.setLayout(new BorderLayout());
        frame.add(scroll, BorderLayout.CENTER);
        frame.add(addBtn, BorderLayout.SOUTH);
        frame.setSize(400, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

Benefits of MVC in Swing:

  1. Separation of concerns
  2. Reusable models
  3. Multiple views for same model
  4. Easy testing
  5. Automatic view updates

Swing MVC Examples:

ComponentModelViewController
JTableTableModelJTableListeners
JListListModelJListListeners
JTreeTreeModelJTreeListeners
JComboBoxComboBoxModelJComboBoxListeners
JTextAreaDocumentJTextAreaDocumentListener

Best Practices:

  1. Separate model from view
  2. Use fireXxx() methods to notify views
  3. Add listeners for coordination
  4. Keep controller logic separate
  5. Use PropertyChangeSupport for beans

SUMMARY

This Master Question Bank covers:

SectionCountTopics
MCQ96JDBC, Swing, Spring, IoC, DI, Bean Scope, Lifecycle, Spring MVC, Validation, EJB, JSP, Servlets
Short Answer16JDBC process, DI, Statement/ResultSet, IoC, Metadata, Bean scope, Exceptions, Spring MVC, PreparedStatement, Drivers, Layouts, Adapters, Containers, Stereotypes, Servlet lifecycle, Session tracking
Long Answer24JDBC transactions, Swing calculator, Spring architecture, ResultSet metadata, Database connectivity, Bean lifecycle, Form handling, Complete JDBC, DI, Spring MVC config, Batch processing, AOP, REST, ResultSet types, Custom painting, BeanPostProcessor, Exception handling, Connection pooling, EJB, JSP, CallableStatement, JTable, Spring Security, i18n, DatabaseMetaData, Popup menus, Servlet filters, Spring Boot, Transactions, JTree, Deployment descriptors, MVC in Swing

On this page