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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- @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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- @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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- @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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- @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?
- @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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- @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?
- @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?
- @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?
- 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?
- 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?
- @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?
- 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?
- @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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- @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?
- @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?
- 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?
- @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?
- @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?
- @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?
- @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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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?
- 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:
| Aspect | Constructor Injection | Setter Injection |
|---|---|---|
| Injection Point | Constructor | Setter method |
| Mandatory | Yes | No |
| Immutability | Yes (final) | No |
| Testability | Best | Good |
| Use Case | Mandatory dependencies | Optional 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:
| Method | Purpose |
|---|---|
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:
| Aspect | Setter Injection | Field Injection |
|---|---|---|
| Injection Point | Setter method | Field directly |
| Code | More verbose | Less code |
| Testability | Good | Poor |
| Immutability | No | No |
| Recommended | Yes | No |
| Visibility | Explicit | Hidden |
Advantages of IoC and DI:
- Loose coupling
- Easier testing
- Better maintainability
- Reusability
- 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()); // MySQLResultSetMetaData: 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)); // INTComparison:
| Aspect | DatabaseMetaData | ResultSetMetaData |
|---|---|---|
| Provides info about | Database, DBMS | Query result columns |
| Obtained from | con.getMetaData() | rs.getMetaData() |
| Key Methods | getDatabaseProductName(), getTables() | getColumnCount(), getColumnName() |
| Use Case | Schema inspection | Dynamic 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.
| Scope | Description |
|---|---|
| Singleton | One instance per container (default) |
| Prototype | New instance per request |
| Request | One instance per HTTP request |
| Session | One instance per HTTP session |
Bean Lifecycle:
1. Instantiation
2. Dependency Injection
3. @PostConstruct (init)
4. Bean Ready for Use
5. @PreDestroy (destroy)
6. Bean RemovedLifecycle 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:
- Singleton scope — default, one instance
- Prototype scope — new instance per request
- @PostConstruct — initialization callback
- @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 Type | Java Type |
|---|---|
| INT | int |
| BIGINT | long |
| FLOAT | float |
| DOUBLE | double |
| VARCHAR | String |
| DATE | java.sql.Date |
| TIME | java.sql.Time |
| TIMESTAMP | java.sql.Timestamp |
Example:
int id = rs.getInt("id");
String name = rs.getString("name");
java.sql.Date d = rs.getDate("dob");Role of SQLException:
- Handles database errors
- Provides error codes and SQL state
- Enables exception chaining
Role of Data Types:
- Type mapping between SQL and Java
- Data conversion
- 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:
| Component | Role |
|---|---|
| DispatcherServlet | Front controller; receives all requests |
| HandlerMapping | Maps URL to controller |
| Controller | Handles request; returns view name |
| Model | Holds data for view |
| ViewResolver | Maps view name to JSP |
| View | Renders HTML response |
Flow:
- Browser sends request to
/home - DispatcherServlet receives request
- HandlerMapping finds
HomeController - Controller method executes, returns
"home" - ViewResolver maps
"home"to/WEB-INF/views/home.jsp - JSP renders HTML response
- 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:
| Aspect | Statement | PreparedStatement |
|---|---|---|
| Purpose | Simple SQL queries | Precompiled SQL with parameters |
| Creation | con.createStatement() | con.prepareStatement(sql) |
| Parameters | No parameters | Supports ? placeholders |
| Performance | Slower for repeated execution | Faster (precompiled) |
| SQL Injection | Vulnerable | Prevents SQL injection |
| Reusability | Not reusable | Reusable |
| Use Case | Static queries | Dynamic 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 → DatabaseFeatures:
- 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 → DatabaseExample:
Class.forName("com.mysql.cj.jdbc.Driver");Features:
- Pure Java
- Direct communication with database
- Fastest performance
Advantages:
- Fastest
- Pure Java
- Portable
- Most commonly used
Comparison:
| Aspect | Type 3 | Type 4 |
|---|---|---|
| Architecture | Middleware | Direct |
| Speed | Fast | Fastest |
| Client Installation | None | None |
| Server Required | Yes | No |
| Use Case | Enterprise | Modern 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
SouthComparison:
| Aspect | FlowLayout | BorderLayout |
|---|---|---|
| Arrangement | Left to right | 5 regions |
| Default For | JPanel | JFrame |
| Components | Any number | Max 5 (one per region) |
| Resizing | Wraps | Stretches |
| Use Case | Toolbars | Main 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:
- Less coding
- Override only required methods
- Cleaner code
- Easier maintenance
Common Adapters:
- WindowAdapter
- MouseAdapter
- KeyAdapter
- FocusAdapter
13. Describe the main differences between ApplicationContext and BeanFactory in the Spring IoC container hierarchy.
Answer:
| Feature | BeanFactory | ApplicationContext |
|---|---|---|
| Initialization | Lazy | Eager |
| Annotation Support | No | Yes |
| Event Handling | No | Yes |
| i18n | No | Yes |
| AOP Integration | Basic | Full |
| Memory | Less | More |
| Use Case | Small apps | Enterprise apps |
| Interface | BeanFactory | ApplicationContext |
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:
- ApplicationContext is built on top of BeanFactory
- ApplicationContext supports annotations, events, and i18n
- BeanFactory is lightweight; ApplicationContext is feature-rich
- 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.
| Annotation | Purpose | Layer |
|---|---|---|
| @Component | General-purpose stereotype | Any |
| @Service | Service layer component | Business logic |
| @Repository | Data access component | DAO |
| @Controller | Web controller | Presentation |
Examples:
@Component
public class Student {
}
@Service
public class StudentService {
}
@Repository
public class StudentDAO {
}
@Controller
public class StudentController {
}How They Work:
- Component scanning detects these annotations
- Spring creates bean instances
- Dependencies are injected
- Beans are managed by the container
Benefits:
- Readability — Intent is clear from annotation
- Specialization — @Repository translates exceptions
- Convention — Follows layered architecture
- 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 onceservice()is called for each requestdestroy()is called once before removal- Container manages the lifecycle
16. Compare session tracking mechanisms in J2EE, specifically Cookies versus HttpSession.
Answer:
| Aspect | Cookies | HttpSession |
|---|---|---|
| Storage | Client-side | Server-side |
| Data Type | String only | Any object |
| Size Limit | 4KB per cookie | Unlimited |
| Security | Less secure | More secure |
| Expiration | Set by server | Set by server/timeout |
| API | Cookie class | HttpSession interface |
| Session ID | Stored in cookie | Stored 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:
- Cookies
- HttpSession
- URL Rewriting
- 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-commitCommit: 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:
- User clicks buttons to build expression
- Expression displayed in JTextField
- “=” evaluates the expression
- 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 RemovedExample:
@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. InitOutput (context close):
4. Destroy2. (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") // DELETERequest Flow:
Browser → DispatcherServlet → HandlerMapping → Controller → ViewResolver → ViewExample:
@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:
| Aspect | ResultSetMetaData | DatabaseMetaData |
|---|---|---|
| Provides info about | Query columns | Database/DBMS |
| Obtained from | rs.getMetaData() | con.getMetaData() |
| Key Methods | getColumnCount(), getColumnName() | getDatabaseProductName(), getTables() |
| Use Case | Dynamic reports | Schema 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:
- Use EDT for Swing updates
- Handle exceptions gracefully
- Close DB resources
- 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 → DatabaseFeatures:
- Type 1 driver
- Uses ODBC
- Easy to configure
- Slow performance
Example:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Limitations:
- Platform dependent
- Requires ODBC installation
- Removed after Java 8
Connection URL Components:
jdbc:mysql://host:port/database| Part | Meaning |
|---|---|
jdbc:mysql:// | Protocol |
localhost | Host |
3306 | Port |
test | Database |
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:
- User enters data in JTextField
- User clicks JButton
- ActionListener triggers DAO method
- DAO executes SQL via JDBC
- Result returned to GUI
- 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:
- Use PreparedStatement (prevent SQL injection)
- Close resources (try-with-resources)
- Use SwingUtilities.invokeLater for thread safety
- Handle exceptions with user-friendly messages
- 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 RemovedInjection 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:
| Aspect | Constructor | Setter | Field |
|---|---|---|---|
| Injection Point | Constructor | Setter | Field |
| Mandatory | Yes | No | Yes |
| Testability | Best | Good | Poor |
| Immutability | Yes | No | No |
| Recommended | Yes | Yes | No |
Advantages of IoC and DI:
- Loose coupling
- Easier testing
- Better maintainability
- Reusability
- 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 → ViewSteps:
- Browser sends request
- DispatcherServlet receives request
- HandlerMapping finds controller
- Controller method executes
- Returns view name
- ViewResolver maps to JSP
- JSP renders HTML
- 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:
- User fills form
- Submits POST request
- Spring binds data to Student object
- @Valid triggers validation
- If errors → BindingResult has errors → return to form
- If valid → process → return success
Advantages:
- Automatic data binding
- Declarative validation
- Error display
- Reusable
6. (ii) Explain bean scopes and lifecycle callbacks in Spring 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 |
| Application | One per ServletContext |
| WebSocket | One 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. DestroyLifecycle Phases:
- Instantiation
- Dependency Injection
- @PostConstruct
- Bean Ready
- @PreDestroy
- 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-closeBest Practices:
- Use Type 4 driver
- Use PreparedStatement
- Close resources
- Handle exceptions
- 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)
└── JTableCalculator 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:
- JFrame as top-level container
- JPanel for grouping
- GridLayout for buttons
- ActionListener for events
- 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:
| Aspect | Constructor | Setter | Field |
|---|---|---|---|
| Injection Point | Constructor | Setter | Field |
| Mandatory | Yes | No | Yes |
| Immutability | Yes | No | No |
| Testability | Best | Good | Poor |
| Recommended | Yes | Yes | No |
Advantages of IoC and DI:
- Loose Coupling: Objects don’t create their dependencies
- Easier Testing: Dependencies can be mocked
- Better Maintainability: Changes in one place
- Reusability: Beans can be reused
- Scalability: Container manages resources
- Configuration Flexibility: XML, annotations, Java config
- 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:
- User opens form (GET /form)
- Controller adds empty Student to model
- Form displayed
- User fills form → POST /save
- Spring binds data to Student object
- @Valid triggers validation
- If errors → BindingResult has errors → return to form
- If valid → process data → return success
Advantages:
- Automatic data binding
- Declarative validation
- Error display
- 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); // DisableCommit: 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:
- Disable auto-commit for transactions
- Commit on success
- Rollback on error
- Close resources
- 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 displayedExample:
@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:
- Declarative mapping
- Automatic data binding
- Validation support
- 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); // DisableCommit: 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:
- Use PreparedStatement (prevent SQL injection)
- Close resources (try-with-resources)
- Use SwingUtilities.invokeLater for thread safety
- Handle exceptions with user-friendly messages
- 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:
| Aspect | Constructor | Setter | Field |
|---|---|---|---|
| Injection Point | Constructor | Setter | Field |
| Mandatory | Yes | No | Yes |
| Immutability | Yes | No | No |
| Testability | Best | Good | Poor |
| Recommended | Yes | Yes | No |
Advantages of IoC and DI:
- Loose coupling
- Easier testing
- Better maintainability
- Reusability
- 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:
- User opens /student/form (GET)
- Controller adds empty Student to model
- Form displayed
- User fills form → POST /student/save
- Spring binds data to Student object
- @Valid triggers validation
- If errors → BindingResult has errors → return “form”
- If valid → process data → return “success”
Validation Error Handling:
<form:errors>displays errors- BindingResult contains errors
- CSS class for styling errors
Advantages:
- Automatic data binding
- Declarative validation
- Error display
- 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:
- User opens /student/form
- Controller adds empty Student
- Form displayed
- User fills → POST /student/save
- Spring binds data
- @Valid triggers validation
- If errors → return form
- If valid → return success
Advantages:
- Automatic binding
- Declarative validation
- Error display
- 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:
- Fewer database calls
- Faster execution
- Better scalability
- 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:
- Use PreparedStatement for batch
- Set batch size (e.g., 1000)
- Commit periodically
- Handle exceptions
- 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:
- Payroll processing
- Student result upload
- Bulk data import
- 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:
| Component | Purpose | Use Case |
|---|---|---|
| JTabbedPane | Tabbed panels | Preferences |
| JSplitPane | Resizable split | File explorer |
| JScrollPane | Scrolling | Large 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:
| Concept | Description |
|---|---|
| Aspect | Module encapsulating cross-cutting concern |
| Join Point | Point in program execution (method call) |
| Advice | Action taken at join point |
| Pointcut | Expression matching join points |
| Weaving | Linking 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 methodwithin(com.demo.service.*)— Any method in package@annotation(Loggable)— Methods with annotation
Benefits:
- Separation of concerns
- Reusable aspects
- Cleaner business logic
- 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:
- Simple annotations
- Automatic JSON conversion
- RESTful design
- Easy integration
15. (i) Explain scrollable and updatable ResultSets in JDBC. Discuss TYPE_SCROLL_SENSITIVE and concurrency modes. (2 marks)
Answer:
ResultSet Types:
| Type | Description |
|---|---|
| TYPE_FORWARD_ONLY | Forward only (default) |
| TYPE_SCROLL_INSENSITIVE | Scrollable; not sensitive to changes |
| TYPE_SCROLL_SENSITIVE | Scrollable; 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 positionUpdatable 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:
| Mode | Description |
|---|---|
| CONCUR_READ_ONLY | Read-only (default) |
| CONCUR_UPDATABLE | Updatable |
TYPE_SCROLL_SENSITIVE:
- Scrollable
- Reflects changes made by others
- More overhead
Comparison:
| Feature | TYPE_SCROLL_INSENSITIVE | TYPE_SCROLL_SENSITIVE |
|---|---|---|
| Scrollable | Yes | Yes |
| Sensitive to changes | No | Yes |
| Performance | Faster | Slower |
| Use Case | Read-only reports | Real-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:
| Method | Purpose |
|---|---|
| drawRect() | Rectangle outline |
| fillRect() | Filled rectangle |
| drawOval() | Circle/ellipse outline |
| fillOval() | Filled circle/ellipse |
| drawLine() | Line |
| drawString() | Text |
| drawImage() | Image |
Use Cases:
- Charts and graphs
- Games
- Custom UI components
- Image editors
- Data visualizations
Best Practices:
- Always call
super.paintComponent(g) - Use Graphics2D for advanced features
- Enable anti-aliasing
- Avoid heavy operations in paintComponent
- 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:
- Reduces duplication
- Centralized configuration
- 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:
- Logging
- Validation
- Custom annotation processing
- AOP proxies
- 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: student16. (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:
- Use @ControllerAdvice for global handling
- Create custom exceptions
- Log exceptions
- Provide user-friendly messages
- Don’t expose stack traces
- 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 ConnectionEach request creates a new connection (slow).
With Pooling:
Request → Connection Pool → DatabaseConnections are reused (fast).
Advantages:
- Faster Performance — No connection creation overhead
- Reduced Overhead — Reuse existing connections
- Better Scalability — Handle more concurrent requests
- Resource Management — Limit total connections
- 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:
| Pool | Provider | Features |
|---|---|---|
| HikariCP | Brett Wooldridge | Fast, lightweight |
| Tomcat JDBC | Apache | Feature-rich |
| DBCP | Apache | Mature |
| C3P0 | Mchange | Legacy |
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:
- Use connection pooling in production
- Set appropriate pool sizes
- Close connections in try-with-resources
- Monitor pool metrics
- 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:
| Component | Role |
|---|---|
| Source | Component that generates event (JButton) |
| Event Object | Contains event information (ActionEvent) |
| Listener | Receives 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 → ListenerEvent Dispatching:
- User interacts with component
- Event object created
- Event added to queue
- EDT processes event
- 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:
| Listener | Method | Event |
|---|---|---|
| ActionListener | actionPerformed() | Button click |
| MouseListener | mouseClicked() | Mouse click |
| KeyListener | keyPressed() | Key press |
| WindowListener | windowClosing() | Window close |
| ListSelectionListener | valueChanged() | 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:
- Delegation model separates source from handler
- Events queued in EDT
- Listeners handle events
- Adapters reduce coding
- 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 → DatabaseTypes 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:
| Aspect | Stateless | Stateful | Message-Driven |
|---|---|---|---|
| State | No | Yes | No |
| Pooling | Yes | No | Yes |
| Scalability | High | Low | High |
| Communication | Sync | Sync | Async |
| Use Case | Business logic | Shopping cart | Messaging |
Session Bean Lifecycle:
1. Creation
2. Dependency Injection
3. @PostConstruct
4. Business Methods
5. @PreDestroy
6. RemovalBenefits:
- Declarative transactions
- Security
- Scalability
- Clustering
- 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:
| Directive | Purpose | Example |
|---|---|---|
| page | Page-level settings | <%@ page language="java" %> |
| include | Include file at translation | <%@ include file="header.jsp" %> |
| taglib | Use 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:
| Object | Purpose |
|---|---|
| request | Client request |
| response | Server response |
| out | Output stream |
| session | Session management |
| application | Application context |
| exception | Exception 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:
- Avoid scriptlets (use JSTL/EL)
- Use custom tags
- Separate concerns (MVC)
- Handle exceptions
- 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:
| Type | Method | Purpose |
|---|---|---|
| IN | setInt(), setString() | Input value |
| OUT | registerOutParameter() | Output value |
| INOUT | Both | Both |
Advantages:
- Executes stored procedures
- Better performance
- Reduced network traffic
- Reusable business logic
- Security (permissions)
Best Practices:
- Use CallableStatement for procedures
- Register OUT parameters before execute
- Close resources
- Handle SQLException
- 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:
| Component | Purpose |
|---|---|
| JTable | Visual component |
| TableModel | Data model |
| TableCellRenderer | Renders cells |
| TableCellEditor | Edits 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:
- Sorting
- Filtering
- Column resizing
- Row selection
- Cell editing
Best Practices:
- Use custom TableModel for complex data
- Use JScrollPane for scrolling
- Handle selection events
- Validate edited values
- 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 → ResourceComponents:
| Component | Purpose |
|---|---|
| SecurityFilterChain | Chain of filters |
| AuthenticationManager | Authenticates users |
| AuthenticationProvider | Provides authentication |
| UserDetailsService | Loads user details |
| AccessDecisionManager | Authorization 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 rolesConfiguration:
@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:
| Annotation | Purpose |
|---|---|
| @PreAuthorize | Before method |
| @PostAuthorize | After method |
| @Secured | Role-based |
| @RolesAllowed | JSR-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:
| Provider | Purpose |
|---|---|
| DaoAuthenticationProvider | Database users |
| LdapAuthenticationProvider | LDAP |
| JwtAuthenticationProvider | JWT tokens |
| OAuth2AuthenticationProvider | OAuth2 |
Filters:
- UsernamePasswordAuthenticationFilter
- BasicAuthenticationFilter
- RememberMeAuthenticationFilter
- AnonymousAuthenticationFilter
- ExceptionTranslationFilter
Best Practices:
- Use BCrypt for passwords
- Enable HTTPS
- Use CSRF protection
- Implement role-based access
- Use method-level security
- 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 applicationmessages_fr.properties:
greeting=Bonjour
welcome=Bienvenue dans notre applicationmessages_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:
- Multi-language support
- Regional formatting
- User-friendly
- Easy maintenance
- Global reach
Best Practices:
- Externalize all messages
- Use UTF-8 encoding
- Support RTL languages
- Format numbers/dates by locale
- 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:
- Dynamic reports
- Database analysis
- Admin tools
- Data migration
- 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:
| Component | Purpose |
|---|---|
| JPopupMenu | Right-click menu |
| JToolBar | Quick action buttons |
| JMenuBar | Main menu |
| JMenu | Dropdown menu |
| JMenuItem | Menu item |
| Accelerator | Keyboard shortcut |
| Mnemonic | Alt+key shortcut |
Benefits:
- Quick access to actions
- Professional look
- Keyboard efficiency
- Context-sensitive menus
- 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:
- Authentication
- Logging
- Compression
- Character encoding
- CORS
Listener Classes: React to application events.
Types:
| Listener | Event |
|---|---|
| ServletContextListener | Context init/destroy |
| HttpSessionListener | Session create/destroy |
| ServletRequestListener | Request init/destroy |
| ServletContextAttributeListener | Attribute changes |
| HttpSessionAttributeListener | Session 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 → ResponseBest Practices:
- Use filters for cross-cutting concerns
- Use listeners for lifecycle events
- Keep filters lightweight
- Handle exceptions in filters
- 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:
@SpringBootApplicationtriggers auto-configuration- Spring Boot examines classpath
- Applies conditional configuration
- Creates beans automatically
@SpringBootApplication:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}Equivalent to:
@Configuration
@EnableAutoConfiguration
@ComponentScanAuto-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=trueStarter Dependencies:
| Starter | Purpose |
|---|---|
| spring-boot-starter-web | Web applications |
| spring-boot-starter-data-jpa | JPA/Hibernate |
| spring-boot-starter-security | Security |
| spring-boot-starter-test | Testing |
| spring-boot-starter-actuator | Monitoring |
| spring-boot-starter-thymeleaf | Thymeleaf templates |
| spring-boot-starter-validation | Validation |
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:
- Independent deployment
- Embedded server (Tomcat)
- Externalized configuration
- Service discovery (Eureka)
- API gateway
- Circuit breakers (Hystrix)
- 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:
- Rapid development
- Minimal configuration
- Production-ready
- Microservice-friendly
- Cloud-native
Best Practices:
- Use starters
- Externalize configuration
- Use profiles
- Enable actuator
- 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:
| Propagation | Description |
|---|---|
| REQUIRED | Join existing or create new (default) |
| REQUIRES_NEW | Always create new |
| SUPPORTS | Join if exists; else no transaction |
| NOT_SUPPORTED | Execute without transaction |
| MANDATORY | Must have existing; else exception |
| NEVER | Must not have existing; else exception |
| NESTED | Nested 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:
| Isolation | Description | Dirty Read | Non-Repeatable Read | Phantom Read |
|---|---|---|---|---|
| DEFAULT | Database default | - | - | - |
| READ_UNCOMMITTED | Lowest | Yes | Yes | Yes |
| READ_COMMITTED | Read only committed | No | Yes | Yes |
| REPEATABLE_READ | Same read → same result | No | No | Yes |
| SERIALIZABLE | Highest | No | No | No |
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:
| Attribute | Purpose |
|---|---|
| propagation | How transactions relate |
| isolation | Concurrency control |
| timeout | Max duration |
| readOnly | Optimization hint |
| rollbackFor | Exceptions triggering rollback |
| noRollbackFor | Exceptions not triggering rollback |
Best Practices:
- Use REQUIRED (default) for most cases
- Use REQUIRES_NEW for independent operations
- Use READ_COMMITTED for most applications
- Use SERIALIZABLE only when necessary
- Specify rollbackFor explicitly
- 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:
| Operation | Method |
|---|---|
| Add node | parent.add(child) |
| Remove node | parent.remove(child) |
| Get user object | node.getUserObject() |
| Get parent | node.getParent() |
| Get children | node.children() |
| Check leaf | node.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:
- File explorers
- Organization charts
- XML viewers
- Category browsers
- Menu structures
Best Practices:
- Use DefaultMutableTreeNode for mutable trees
- Add TreeSelectionListener for selection
- Use JScrollPane for scrolling
- Customize cell renderer for icons
- 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:
| Aspect | web.xml/ejb-jar.xml | Annotations |
|---|---|---|
| Configuration | XML | Java code |
| Readability | Verbose | Concise |
| Type Safety | No | Yes |
| Compile-time Check | No | Yes |
| Refactoring | Manual | IDE support |
| External Config | Yes | Limited |
| Legacy Support | Yes | Modern |
Best Practices:
- Use annotations for new applications
- Use web.xml for external configuration
- Combine both when needed
- Keep descriptors minimal
- 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 InputComponents:
| Component | Role | Swing Example |
|---|---|---|
| Model | Data and state | TableModel, ListModel |
| View | Visual representation | JTable, JList |
| Controller | Handles input | Listeners |
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:
- Separation of concerns
- Reusable models
- Multiple views for same model
- Easy testing
- Automatic view updates
Swing MVC Examples:
| Component | Model | View | Controller |
|---|---|---|---|
| JTable | TableModel | JTable | Listeners |
| JList | ListModel | JList | Listeners |
| JTree | TreeModel | JTree | Listeners |
| JComboBox | ComboBoxModel | JComboBox | Listeners |
| JTextArea | Document | JTextArea | DocumentListener |
Best Practices:
- Separate model from view
- Use fireXxx() methods to notify views
- Add listeners for coordination
- Keep controller logic separate
- Use PropertyChangeSupport for beans
SUMMARY
This Master Question Bank covers:
| Section | Count | Topics |
|---|---|---|
| MCQ | 96 | JDBC, Swing, Spring, IoC, DI, Bean Scope, Lifecycle, Spring MVC, Validation, EJB, JSP, Servlets |
| Short Answer | 16 | JDBC process, DI, Statement/ResultSet, IoC, Metadata, Bean scope, Exceptions, Spring MVC, PreparedStatement, Drivers, Layouts, Adapters, Containers, Stereotypes, Servlet lifecycle, Session tracking |
| Long Answer | 24 | JDBC 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 |