Adv-Java Unit 3: Questions & Answers
Unit 4: Java Swings & Spring -> Generated and Prepared By Thiruselvan (ThiruXD)
SECTION A: MULTIPLE CHOICE QUESTIONS (50 MCQs)
Introduction to Java Swings
Q1. What does Swing provide in Java?
- Database connectivity
- GUI components for desktop applications
- Web server functionality
- Network programming
Answer: B) GUI components for desktop applications -> Explanation: Java Swing is a GUI (Graphical User Interface) toolkit used to create desktop applications. It is part of the Java Foundation Classes (JFC).
Q2. Swing is part of which Java class library?
- Java Database Connectivity
- Java Foundation Classes (JFC)
- Java Server Pages
- Java Networking
Answer: B) Java Foundation Classes (JFC) -> Explanation: Swing is part of the Java Foundation Classes (JFC), which provide a comprehensive set of GUI components for building desktop applications.
Q3. Which of the following is NOT a Swing component?
- JFrame
- JButton
- JTextField
- JDatabase
Answer: D) JDatabase -> Explanation: JFrame, JButton, and JTextField are Swing components. JDatabase is not a Swing component — it does not exist in the Swing API.
Q4. Swing components are called “lightweight” because:
- They use less memory
- They are implemented in Java, not OS-dependent
- They are faster
- They have fewer features
Answer: B) They are implemented in Java, not OS-dependent -> Explanation: Swing components are called lightweight because they are implemented in Java rather than relying directly on the operating system’s GUI components.
Q5. Which package contains Swing components?
java.awtjavax.swingjava.swingjavax.awt
Answer: B) javax.swing -> Explanation: Swing components are in the javax.swing package. AWT components are in java.awt.
Q6. Which is the top-level container in Swing?
- JPanel
- JFrame
- JButton
- JLabel
Answer: B) JFrame -> Explanation: JFrame is the top-level container (main window) in Swing. JPanel is a grouping container, and JButton/JLabel are components.
Swing Components
Q7. Which component displays text or images?
- JTextField
- JLabel
- JButton
- JCheckBox
Answer: B) JLabel -> Explanation: JLabel displays text or images. It is a non-interactive component used for labels.
Q8. Which component is used for user text input?
- JLabel
- JTextField
- JButton
- JPanel
Answer: B) JTextField -> Explanation: JTextField is used for user input. It allows the user to type a single line of text.
Q9. Which component represents a clickable button?
- JLabel
- JTextField
- JButton
- JCheckBox
Answer: C) JButton -> Explanation: JButton represents a clickable button. When clicked, it generates an ActionEvent.
Q10. Which component allows multiple selections?
- JRadioButton
- JCheckBox
- JButton
- JLabel
Answer: B) JCheckBox -> Explanation: JCheckBox allows multiple selections (check/uncheck). JRadioButton allows only one selection from a group.
Q11. Which component is used to display tabular data?
- JTable
- JList
- JComboBox
- JTextArea
Answer: A) JTable -> Explanation: JTable displays tabular data in rows and columns. It is commonly used in database applications.
Q12. Which component creates a drop-down list?
- JList
- JComboBox
- JCheckBox
- JTextField
Answer: B) JComboBox -> Explanation: JComboBox creates a drop-down list from which the user can select one option.
Containers and Layout Managers
Q13. Which container is used to group components?
- JFrame
- JPanel
- JButton
- JLabel
Answer: B) JPanel -> Explanation: JPanel is used to group components. It is a lightweight container that can hold other components.
Q14. Which layout arranges components left to right?
- BorderLayout
- GridLayout
- FlowLayout
- CardLayout
Answer: C) FlowLayout -> Explanation: FlowLayout arranges components left to right, wrapping to the next line when needed. It is the default layout for JPanel.
Q15. Which layout has five regions: North, South, East, West, Center?
- FlowLayout
- GridLayout
- BorderLayout
- CardLayout
Answer: C) BorderLayout -> Explanation: BorderLayout divides the container into five regions: North, South, East, West, and Center. It is the default layout for JFrame.
Q16. Which layout arranges components in a grid of rows and columns?
- FlowLayout
- BorderLayout
- GridLayout
- CardLayout
Answer: C) GridLayout -> Explanation: GridLayout arranges components in a grid of rows and columns. Example: new GridLayout(2, 2) creates a 2×2 grid.
Q17. What is the default layout for JFrame?
- FlowLayout
- BorderLayout
- GridLayout
- null
Answer: B) BorderLayout -> Explanation: The default layout for JFrame is BorderLayout. You can change it using frame.setLayout().
Event Handling
Q18. Which model does Swing event handling follow?
- Observer model
- Delegation Event Model
- Producer-Consumer model
- Singleton model
Answer: B) Delegation Event Model -> Explanation: Swing follows the Delegation Event Model, where the event source delegates event handling to a listener.
Q19. Which listener handles button clicks?
- MouseListener
- KeyListener
- ActionListener
- WindowListener
Answer: C) ActionListener -> Explanation: ActionListener handles button clicks. It has one method: actionPerformed(ActionEvent e).
Q20. Which method must be implemented in ActionListener?
actionEvent()actionPerformed()performAction()handleAction()
Answer: B) actionPerformed() -> Explanation: ActionListener has one method: actionPerformed(ActionEvent e). It is called when a button is clicked.
Q21. What is an event adapter?
- A class that generates events
- A class providing default implementations of listener methods
- A class that blocks events
- A class that logs events
Answer: B) A class providing default implementations of listener methods -> Explanation: Event adapters provide default (empty) implementations of listener methods, so you can override only the methods you need.
Q22. Which method sets the size of a JFrame?
setDimension()setSize()setBounds()setFrameSize()
Answer: B) setSize() -> Explanation: setSize(width, height) sets the size of a JFrame. Example: frame.setSize(400, 300).
Q23. Which method makes a JFrame visible?
show()display()setVisible(true)setShow(true)
Answer: C) setVisible(true) -> Explanation: setVisible(true) makes a JFrame visible on the screen. By default, JFrame is not visible.
Q24. Which method sets the close operation for a JFrame?
setClose()setDefaultCloseOperation()setExit()closeOperation()
Answer: B) setDefaultCloseOperation() -> Explanation: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) specifies what happens when the user closes the window.
IDE and Debugging
Q25. What does IDE stand for?
- Integrated Development Environment
- Internal Debugging Engine
- Interactive Design Editor
- Integrated Debugging Environment
Answer: A) Integrated Development Environment -> Explanation: IDE stands for Integrated Development Environment. It is software used to write, compile, run, and debug Java programs.
Q26. Which of the following is NOT an IDE?
- Eclipse
- NetBeans
- IntelliJ IDEA
- JFrame
Answer: D) JFrame -> Explanation: JFrame is a Swing component, not an IDE. Eclipse, NetBeans, and IntelliJ IDEA are popular Java IDEs.
Q27. What is a breakpoint used for?
- Breaking the program permanently
- Pausing program execution for debugging
- Closing the program
- Restarting the program
Answer: B) Pausing program execution for debugging -> Explanation: A breakpoint pauses program execution at a specific line, allowing the developer to inspect variables and step through code.
Q28. Which feature suggests methods and classes automatically in an IDE?
- Syntax highlighting
- Auto completion
- Error detection
- Debugging
Answer: B) Auto completion -> Explanation: Auto completion suggests methods and classes automatically as you type, improving coding speed and accuracy.
Desktop Application Development
Q29. Which components are used in a Calculator Swing application?
- JTextField and JButton
- JTable and JTree
- JMenu and JMenuItem
- JSlider and JProgressBar
Answer: A) JTextField and JButton -> Explanation: A Calculator application uses JTextField for displaying numbers and JButton for digits and operations.
Q30. Which method converts a String to an int in a Calculator app?
Integer.parse()Integer.parseInt()Integer.valueOfInt()Integer.toInt()
Answer: B) Integer.parseInt() -> Explanation: Integer.parseInt(String) converts a String to an int. Example: int a = Integer.parseInt(t1.getText()).
Q31. Which method sets text in a JTextField?
setText()setValue()setString()setContent()
Answer: A) setText() -> Explanation: setText(String) sets the text displayed in a JTextField. Example: result.setText(String.valueOf(sum)).
Q32. Which JDBC method is used to connect Swing with a database?
DriverManager.getConnection()Connection.open()Database.connect()JDBC.connect()
Answer: A) DriverManager.getConnection() -> Explanation: DriverManager.getConnection(url, user, password) is used to establish a database connection from a Swing application.
Spring Framework Fundamentals
Q33. What is the full form of IoC in Spring?
- Input/Output Control
- Inversion of Control
- Internal Object Creation
- Integrated Object Container
Answer: B) Inversion of Control -> Explanation: IoC stands for Inversion of Control. It means object creation and dependency management are transferred from the programmer to the Spring container.
Q34. What is the full form of DI in Spring?
- Direct Integration
- Dependency Injection
- Dynamic Inheritance
- Data Interface
Answer: B) Dependency Injection -> Explanation: DI stands for Dependency Injection. It is the process of providing dependencies to an object, typically by the Spring container.
Q35. Which annotation is used to mark a class as a Spring bean?
@Bean@Component@Service- All of the above
Answer: D) All of the above -> Explanation: @Component, @Service, @Repository, and @Controller are stereotype annotations that mark a class as a Spring bean. @Bean is used in configuration classes.
Q36. Which annotation is used for automatic dependency injection?
@Inject@Autowired@Resource@Dependency
Answer: B) @Autowired -> Explanation: @Autowired is the primary annotation for automatic dependency injection in Spring. It can be applied to constructors, setters, or fields.
Q37. Which is NOT a feature of the Spring Framework?
- Lightweight
- Modular design
- Tight coupling
- Dependency management
Answer: C) Tight coupling -> Explanation: Spring promotes loose coupling through Dependency Injection. Tight coupling is the opposite of what Spring encourages.
Q38. Which module of Spring provides database support?
- Spring MVC
- Spring JDBC
- Spring Security
- Spring AOP
Answer: B) Spring JDBC -> Explanation: Spring JDBC provides database support, including JdbcTemplate and transaction management. Spring MVC is for web applications; Spring Security is for authentication.
Q39. What is a Spring bean?
- A JavaBean component
- An object managed by the Spring container
- A configuration file
- A database table
Answer: B) An object managed by the Spring container -> Explanation: A Spring bean is an object managed by the Spring container. The container handles its creation, dependency injection, and lifecycle.
Q40. Which file is commonly used for Spring XML configuration?
spring.xmlbeans.xmlconfig.xmlapplication.xml
Answer: B) beans.xml -> Explanation: beans.xml is a commonly used name for Spring XML configuration files, though any name can be used. It defines beans and their dependencies.
Dependency Injection
Q41. Which type of dependency injection uses a constructor?
- Setter Injection
- Constructor Injection
- Field Injection
- Method Injection
Answer: B) Constructor Injection -> Explanation: Constructor Injection provides dependencies through the constructor. It ensures mandatory dependencies are provided at object creation.
Q42. Which type of dependency injection uses setter methods?
- Constructor Injection
- Setter Injection
- Field Injection
- Method Injection
Answer: B) Setter Injection -> Explanation: Setter Injection provides dependencies through setter methods. It allows optional dependencies and flexible configuration.
Q43. Which type of dependency injection uses @Autowired on fields?
- Constructor Injection
- Setter Injection
- Field Injection
- Method 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.
Q44. Which DI type is best for mandatory dependencies?
- Setter Injection
- Constructor Injection
- Field Injection
- All are equal
Answer: B) Constructor Injection -> Explanation: Constructor Injection is best for mandatory dependencies because they must be provided at object creation. The object cannot be created without them.
Bean Scope and Lifecycle
Q45. What is the default bean scope in Spring?
- Prototype
- Singleton
- Request
- Session
Answer: B) Singleton -> Explanation: Singleton is the default bean scope in Spring. Only one instance of the bean is created per Spring container.
Q46. Which scope creates a new bean instance every time?
- Singleton
- Prototype
- Request
- Session
Answer: B) Prototype -> Explanation: Prototype scope creates a new bean instance every time it is requested from the container.
Q47. Which annotation is used for bean initialization?
@Init@PostConstruct@AfterConstruct@Start
Answer: B) @PostConstruct -> Explanation: @PostConstruct marks a method to be executed after bean initialization. It is used for initialization logic.
Q48. Which annotation is used for bean destruction?
@Destroy@PreDestroy@BeforeDestroy@End
Answer: B) @PreDestroy -> Explanation: @PreDestroy marks a method to be executed before bean destruction. It is used for cleanup logic.
Spring MVC and Validation
Q49. Which is the front controller in Spring MVC?
- Controller
- DispatcherServlet
- ViewResolver
- HandlerMapping
Answer: B) DispatcherServlet -> Explanation: DispatcherServlet is the front controller in Spring MVC. It receives all requests and dispatches them to appropriate controllers.
Q50. Which annotation is used to validate an email?
@Email@ValidEmail@EmailAddress@Mail
Answer: A) @Email -> Explanation: @Email is a validation annotation that checks whether a field contains a valid email address. It is part of the Bean Validation API.
SECTION B: THEORY QUESTIONS (20)
Q1. Explain Java Swing and its key features.
Answer:
Definition:Java Swing is a GUI (Graphical User Interface) toolkit used to create desktop applications. It is part of the Java Foundation Classes (JFC) and provides platform-independent GUI components.
Key Features:
| # | Feature | Explanation |
|---|---|---|
| 1 | GUI Toolkit | Provides components for desktop applications |
| 2 | Platform Independent | Runs on different operating systems |
| 3 | Lightweight Components | Implemented in Java, not OS-dependent |
| 4 | Rich Components | JFrame, JLabel, JTextField, JButton, JCheckBox, JRadioButton, JComboBox, JTable |
| 5 | Event Handling | Uses event listeners to respond to user actions |
| 6 | Easy to Build Forms | Login, registration, calculator, student management |
| 7 | Separation of GUI and Logic | Interface and logic organized separately |
Simple Swing Example:
import javax.swing.*;
public class SwingExample {
public static void main(String[] args) {
JFrame frame = new JFrame("My First Swing Program");
JLabel label = new JLabel("Welcome to Java Swing");
label.setBounds(80, 50, 200, 30);
JButton button = new JButton("Click Me");
button.setBounds(100, 100, 120, 40);
button.addActionListener(e ->
JOptionPane.showMessageDialog(frame, "Button Clicked!"));
frame.add(label);
frame.add(button);
frame.setSize(350, 250);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}Output:
┌──────────────────────────────────────┐
│ My First Swing Program X │
├──────────────────────────────────────┤
│ Welcome to Java Swing │
│ ┌───────────┐ │
│ │ Click Me │ │
│ └───────────┘ │
└──────────────────────────────────────┘Advantages of Swing:
- Platform Independent
- Rich GUI Components
- Event-Driven Programming
- Easy Database Integration
- Flexible Layout Managers
Q2. Explain the Swing components JLabel, JTextField, JButton, and JCheckBox with examples.
Answer:
1. JLabel
Displays text or images. Non-interactive.
JLabel label = new JLabel("Welcome");
label.setBounds(100, 100, 150, 30);
frame.add(label);2. JTextField
Used for user input. Allows a single line of text.
JTextField tf = new JTextField();
tf.setBounds(50, 50, 150, 30);
frame.add(tf);
String text = tf.getText(); // Retrieve input3. JButton
Represents a clickable button. Generates ActionEvent when clicked.
JButton b = new JButton("Click");
b.setBounds(100, 100, 100, 30);
b.addActionListener(e -> System.out.println("Clicked"));
frame.add(b);4. JCheckBox
Allows multiple selections (check/uncheck).
JCheckBox cb = new JCheckBox("Java");
cb.setBounds(100, 100, 100, 30);
frame.add(cb);
boolean selected = cb.isSelected();5. Comparison Table
| Component | Purpose | Interactive? |
|---|---|---|
| JLabel | Display text/image | No |
| JTextField | Text input | Yes |
| JButton | Trigger action | Yes |
| JCheckBox | Multiple selections | Yes |
6. Complete Example
import javax.swing.*;
public class ComponentDemo {
public static void main(String[] args) {
JFrame f = new JFrame("Components Demo");
JLabel l = new JLabel("Name:");
l.setBounds(20, 20, 100, 30);
JTextField tf = new JTextField();
tf.setBounds(100, 20, 150, 30);
JCheckBox cb = new JCheckBox("Java");
cb.setBounds(20, 60, 100, 30);
JButton b = new JButton("Submit");
b.setBounds(100, 100, 100, 30);
b.addActionListener(e ->
JOptionPane.showMessageDialog(f, "Hello " + tf.getText()));
f.add(l); f.add(tf); f.add(cb); f.add(b);
f.setSize(300, 200);
f.setLayout(null);
f.setVisible(true);
}
}Q3. Explain the different layout managers in Swing.
Answer:
Layout managers control how components are arranged in a container.
1. FlowLayout
Arranges components left to right, wrapping to the next line when needed.
frame.setLayout(new FlowLayout());Example:
[A] [B] [C]
[D] [E]2. 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("South"), BorderLayout.SOUTH);
frame.add(new JButton("East"), BorderLayout.EAST);
frame.add(new JButton("West"), BorderLayout.WEST);
frame.add(new JButton("Center"), BorderLayout.CENTER);Example:
North
West Center East
South3. GridLayout
Arranges components in a grid of rows and columns.
frame.setLayout(new GridLayout(2, 2));Example:
A B
C D4. CardLayout
Arranges components as stacked cards — only one visible at a time.
frame.setLayout(new CardLayout());5. GridBagLayout
Most flexible layout — components can have different sizes and positions.
6. Comparison Table
| Layout | Arrangement | Default For |
|---|---|---|
| FlowLayout | Left to right | JPanel |
| BorderLayout | 5 regions | JFrame |
| GridLayout | Rows × columns | Custom grids |
| CardLayout | Stacked cards | Wizards, tabs |
| GridBagLayout | Flexible grid | Complex forms |
7. Example — GridLayout
import javax.swing.*;
import java.awt.*;
public class GridDemo {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setLayout(new GridLayout(2, 2));
f.add(new JButton("A"));
f.add(new JButton("B"));
f.add(new JButton("C"));
f.add(new JButton("D"));
f.setSize(300, 300);
f.setVisible(true);
}
}Output:
[A] [B]
[C] [D]Q4. Explain event handling in Swing with the Delegation Event Model.
Answer:
Event Handling is the mechanism by which a program responds to user actions (clicks, keypresses, mouse movements).
1. Delegation Event Model
Swing follows the Delegation Event Model, which has three components:
| Component | Purpose |
|---|---|
| Source | The component that generates the event (e.g., JButton) |
| Event Object | Contains information about the event (e.g., ActionEvent) |
| Listener | Receives and handles the event (e.g., ActionListener) |
Flow:
Button → ActionEvent → ActionListener → actionPerformed()2. Common Listeners
| Listener | Purpose | Method |
|---|---|---|
| ActionListener | Button clicks | actionPerformed(ActionEvent e) |
| MouseListener | Mouse events | mouseClicked(), mousePressed(), etc. |
| KeyListener | Keyboard events | keyPressed(), keyReleased(), keyTyped() |
| WindowListener | Window events | windowClosing(), windowOpened(), etc. |
3. ActionListener Example
JButton b = new JButton("Click");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button Clicked");
}
});Using Lambda Expression:
b.addActionListener(e -> System.out.println("Button Clicked"));4. Event Adapters
Adapters provide default implementations of listener methods, so you override only what you need.
public class Demo extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}Benefits:
- Less coding
- Override only required methods
5. 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);
}
}Q5. Explain the Spring Framework and its features.
Answer:
Definition: The Spring Framework is one of the most popular Java frameworks used for developing enterprise applications. It provides comprehensive infrastructure support and simplifies development through Dependency Injection (DI) and Inversion of Control (IoC).
Features of Spring Framework
1. Lightweight Framework
Spring does not require heavyweight application servers and consumes fewer resources.
Features:
- Small footprint
- POJO (Plain Old Java Object) based
- Easy deployment
Example:
public class Student {
private int id;
private String name;
}Advantages: Faster development, easy maintenance, reduced memory usage.
2. Modular Design
Spring consists of independent modules.
Major Modules:
Spring Framework
|
|-- Core Container
|-- Spring MVC
|-- Spring JDBC
|-- Spring ORM
|-- Spring Security
|-- Spring AOPBenefits: Flexibility, easy integration, reduced complexity.
3. Dependency Management
Spring manages dependencies automatically.
Without Spring:
StudentDAO dao = new StudentDAO(); // Tightly coupledWith Spring:
@Autowired
private StudentDAO dao; // Spring injects automaticallyBenefits: Loose coupling, better testing, easier maintenance.
4. Enterprise Application Support
Spring supports enterprise-level applications.
Features:
- Transaction Management
- Security
- Database Integration
- Web Services
- Cloud Applications
Example:
@Transactional
public void saveStudent() {
}Spring Architecture
Application
|
--------------------------------
| Core Container |
| Data Access Layer |
| Web Layer |
| Integration Layer |
--------------------------------Advantages of Spring
- Loose Coupling
- Easier Testing
- Better Maintainability
- Reusability
- Scalability
Q6. Explain Inversion of Control (IoC) in Spring.
Answer:
Definition:Inversion of Control means object creation and dependency management are transferred from the programmer to the Spring container.
Traditional Approach vs Spring Approach
Traditional (Without IoC):
StudentDAO dao = new StudentDAO(); // Programmer creates objectsSpring (With IoC):
@Autowired
StudentDAO dao; // Spring creates and injects objectsIoC Flow
Application
↓
Spring Container
↓
Object Creation
↓
Dependency InjectionBean Management
What is a Bean? A Bean is an object managed by Spring.
@Component
public class Student {
}XML Bean Definition:
<bean id="student" class="com.demo.Student"/>Container Services
Spring Container provides:
- Object Creation
- Dependency Injection
- Lifecycle Management
- Configuration Management
Example:
ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");Advantages of IoC
- 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
Q7. Explain the types of Dependency Injection in Spring.
Answer:
Dependency Injection (DI) is the process of providing dependencies to an object.
1. Constructor Injection
Dependencies are injected through the constructor.
public class StudentService {
private StudentDAO dao;
public StudentService(StudentDAO dao) {
this.dao = dao;
}
}Spring Configuration (XML):
<bean id="dao" class="StudentDAO"/>
<bean id="service" class="StudentService">
<constructor-arg ref="dao"/>
</bean>Advantages:
- Mandatory Dependencies
- Better Immutability
2. Setter Injection
Dependency 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"/>Advantages:
- Optional Dependencies
- Flexible Configuration
3. Field Injection
Uses @Autowired directly on fields.
@Service
public class StudentService {
@Autowired
private StudentDAO dao;
}Advantages:
- Less Code
- Simple Configuration
Disadvantages:
- Difficult to test
Comparison Table
| Technique | Injection Point | Mandatory? | Testability |
|---|---|---|---|
| Constructor | Constructor | Yes | Best |
| Setter | Setter method | No | Good |
| Field | Field directly | Yes | Poor |
Dependency Resolution
Spring resolves dependencies automatically.
@Autowired
private StudentDAO dao;Spring searches:
- Matching Bean
- Matching Type
- Matching Name
Q8. Explain Bean Scope and Bean Lifecycle in Spring.
Answer:
Bean Scope
1. Singleton Scope
Default scope in Spring. Only one object is created.
@Component
@Scope("singleton")
public class Student {
}Diagram:
Request 1 → Same Object
Request 2 → Same Object
Request 3 → Same Object2. Prototype Scope
Creates a new object every time.
@Component
@Scope("prototype")
public class Student {
}Diagram:
Request 1 → Object 1
Request 2 → Object 2
Request 3 → Object 3Difference Table
| Aspect | Singleton | Prototype |
|---|---|---|
| Objects | One Object | Multiple Objects |
| Default | Yes | Explicit Scope |
| Memory | Less Memory | More Memory |
| Use Case | Stateless beans | Stateful beans |
Bean Lifecycle
1. Bean Instantiation
2. Dependency Injection
3. @PostConstruct (init)
4. Bean Ready for Use
5. @PreDestroy (destroy)
6. Bean RemovedBean Initialization
Executed after bean creation.
@PostConstruct
public void init() {
System.out.println("Bean Initialized");
}Bean Destruction
Executed before bean removal.
@PreDestroy
public void destroy() {
System.out.println("Bean Destroyed");
}Complete Example
@Component
@Scope("singleton")
public class Student {
@PostConstruct
public void init() {
System.out.println("Student bean initialized");
}
@PreDestroy
public void destroy() {
System.out.println("Student bean destroyed");
}
}Q9. Explain Spring MVC configuration and DispatcherServlet.
Answer:
Spring MVC Architecture
Browser
↓
DispatcherServlet (Front Controller)
↓
HandlerMapping
↓
Controller
↓
ViewResolver
↓
View (JSP)1. DispatcherServlet
Front Controller of Spring MVC. It receives all requests and dispatches them to appropriate controllers.
Configuration:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>2. Configuration Files
Used to define beans and MVC settings.
<context:component-scan base-package="com.demo"/>3. Controller Setup
Controller handles requests.
@Controller
public class HomeController {
}Request Handler:
@RequestMapping("/home")
public String home() {
return "home";
}4. View Resolver
Maps view names to JSP pages.
<bean class="InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>Example: If controller returns "home", ViewResolver maps it to /WEB-INF/views/home.jsp.
5. Complete Flow
- Browser sends request to
/home - DispatcherServlet receives request
- HandlerMapping finds
HomeController - Controller method executes and returns
"home" - ViewResolver maps
"home"to/WEB-INF/views/home.jsp - JSP renders HTML response
- Response sent back to browser
Advantages of Spring MVC
- Separation of Concerns
- Easy Validation
- Powerful Request Mapping
- Flexible View Management
- Integration with Spring Modules
Q10. Explain Request Mapping and Form Tag Library in Spring MVC.
Answer:
1. RequestMapping Annotation
Maps URL requests to controller methods.
@RequestMapping("/student")
public String student() {
return "student";
}2. URL Mapping
Maps multiple URLs or HTTP methods.
@RequestMapping(value="/save", method=RequestMethod.POST)
public String save() {
return "success";
}Using @PostMapping (Spring 4.3+):
@PostMapping("/save")
public String save() {
return "success";
}3. Form Tag Library
Spring provides JSP form tags for data binding.
Tag Library Declaration:
<%@ taglib prefix="form"
uri="http://www.springframework.org/tags/form"%>Form Tag:
<form:form modelAttribute="student">
<form:input path="name"/>
<form:input path="email"/>
<input type="submit" value="Save"/>
</form:form>4. Data Binding
Automatically maps form data to Java objects.
Model Class:
public class Student {
private String name;
private String email;
// getters and setters
}Controller:
@PostMapping("/save")
public String save(Student student) {
// student.name and student.email are populated
return "success";
}5. Common Form Tags
| Tag | Purpose |
|---|---|
<form:form> | Main 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 validation errors |
6. Complete Example
Form (form.jsp):
<%@ taglib prefix="form"
uri="http://www.springframework.org/tags/form"%>
<html>
<body>
<form:form modelAttribute="student" action="save">
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>
</body>
</html>Controller:
@Controller
public class StudentController {
@GetMapping("/form")
public String showForm(Model model) {
model.addAttribute("student", new Student());
return "form";
}
@PostMapping("/save")
public String save(@Valid Student student, BindingResult result) {
if (result.hasErrors()) {
return "form";
}
return "success";
}
}Advantages
- Reduced Code — No manual parameter extraction
- Data Binding — Automatic mapping
- Validation Integration — Errors displayed easily
- Type Safety — Compile-time checking
Q11. Explain Spring Validation with annotations.
Answer:
Spring Validation is used to validate user input before processing.
1. Validation Annotations
| Annotation | Purpose |
|---|---|
| @NotNull | Cannot be null |
| @NotEmpty | Cannot be empty |
| @Size | Length validation |
| Email validation | |
| @Min | Minimum value |
| @Max | Maximum value |
| @Pattern | Regex pattern |
2. Model Class with Validation
public class Student {
@NotEmpty(message = "Name is required")
private String name;
@Email(message = "Invalid email")
@NotEmpty(message = "Email is required")
private String email;
@Min(value = 18, message = "Age must be at least 18")
@Max(value = 60, message = "Age must be at most 60")
private int age;
// getters and setters
}3. Controller with @Valid
@PostMapping("/save")
public String save(@Valid Student student, BindingResult result) {
if (result.hasErrors()) {
return "form"; // Return to form with errors
}
return "success";
}4. Displaying Errors in JSP
<form:form modelAttribute="student">
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>5. Validation Flow
User submits form
↓
Controller receives @Valid Student
↓
Validation runs automatically
↓
If errors → BindingResult contains errors → return to form
↓
If valid → process data → return success6. Advantages
- Automatic Validation — No manual checks
- Error Handling — Errors displayed to user
- Reusable — Annotations used across application
- Standard — Based on Bean Validation API (JSR-303)
Q12. Explain the Spring architecture with its layers.
Answer:
Spring Architecture Overview
Application
|
--------------------------------
| Core Container |
| Data Access Layer |
| Web Layer |
| Integration Layer |
--------------------------------1. Core Container
Core of Spring Framework.
Components:
- BeanFactory — Basic container
- ApplicationContext — Advanced container
- IoC Container — Manages beans
Example:
ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");2. Data Access Layer
Provides database support.
Features:
- JDBC Support
- ORM Integration
- Transaction Management
Example:
JdbcTemplate jdbcTemplate;Spring JDBC simplifies database operations.
3. Web Layer
Supports web application development.
Components:
- Spring MVC
- Controllers
- View Resolvers
Example:
@Controller
public class HomeController {
}4. Integration Layer
Integrates with external technologies.
Examples:
- Hibernate
- JPA
- JMS
- Web Services
Example:
@Repository
public class StudentDAO {
}Module Summary
| Layer | Purpose | Key Components |
|---|---|---|
| Core Container | Bean management | BeanFactory, ApplicationContext |
| Data Access | Database operations | JdbcTemplate, ORM |
| Web Layer | Web applications | Spring MVC, Controllers |
| Integration | External technologies | Hibernate, JPA, JMS |
Q13. Explain the steps to create a Calculator application using Swing.
Answer:
Calculator Application Design
Components:
- JTextField for display
- JButtons for digits (0-9) and operations (+, -, *, /, =)
Layout:
[ 10 ]
[7] [8] [9] [ / ]
[4] [5] [6] [ * ]
[1] [2] [3] [ - ]
[0] [.] [=] [ + ]Step 1: Create JFrame
JFrame frame = new JFrame("Calculator");
frame.setSize(300, 400);
frame.setLayout(new BorderLayout());Step 2: Create Display (JTextField)
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
StringBuilder expression = new StringBuilder();
for (Component c : panel.getComponents()) {
JButton btn = (JButton) c;
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());
}
});
}Step 6: Complete Example
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.setHorizontalAlignment(JTextField.RIGHT);
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 = eval(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.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
static double eval(String expr) {
// Simple evaluation (use ScriptEngine for real apps)
return new Object() {
int pos = -1, ch;
void nextChar() { ch = (++pos < expr.length()) ? expr.charAt(pos) : -1; }
boolean eat(int c) { while (ch == ' ') nextChar(); if (ch == c) { nextChar(); return true; } return false; }
double parse() { nextChar(); double x = parseExpression(); return x; }
double parseExpression() {
double x = parseTerm();
for (;;) {
if (eat('+')) x += parseTerm();
else if (eat('-')) x -= parseTerm();
else return x;
}
}
double parseTerm() {
double x = parseFactor();
for (;;) {
if (eat('*')) x *= parseFactor();
else if (eat('/')) x /= parseFactor();
else return x;
}
}
double parseFactor() {
if (eat('+')) return parseFactor();
if (eat('-')) return -parseFactor();
double x;
int startPos = pos;
if (eat('(')) { x = parseExpression(); eat(')'); }
else if ((ch >= '0' && ch <= '9') || ch == '.') {
while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
x = Double.parseDouble(expr.substring(startPos, pos));
} else throw new RuntimeException("Unexpected");
return x;
}
}.parse();
}
}Key Concepts Used
| Concept | Usage |
|---|---|
| JFrame | Main window |
| JTextField | Display |
| JButton | Digits and operations |
| GridLayout | Button arrangement |
| ActionListener | Handle clicks |
| Lambda expression | Concise event handling |
Q14. Explain how to connect a Swing application with a database using JDBC.
Answer:
Swing + JDBC Integration
Purpose: Create desktop applications that store and retrieve data from a database.
Step 1: Load JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");Step 2: Establish Connection
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/school",
"root",
"root"
);Step 3: Create Swing Form
JFrame f = new JFrame("Student Registration");
JLabel l1 = new JLabel("Name:");
JTextField tf1 = new JTextField();
JLabel l2 = new JLabel("Age:");
JTextField tf2 = new JTextField();
JButton save = new JButton("Save");Step 4: Handle Save Button
save.addActionListener(e -> {
try {
String name = tf1.getText();
int age = Integer.parseInt(tf2.getText());
PreparedStatement ps = con.prepareStatement(
"INSERT INTO student(name, age) VALUES(?, ?)");
ps.setString(1, name);
ps.setInt(2, age);
ps.executeUpdate();
JOptionPane.showMessageDialog(f, "Saved successfully!");
} catch (SQLException ex) {
ex.printStackTrace();
}
});Step 5: Retrieve Data and Display 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")
});
}
f.add(new JScrollPane(table));Step 6: Complete Example
import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;
public class StudentApp {
public static void main(String[] args) {
JFrame f = new JFrame("Student Management");
f.setLayout(null);
JLabel l1 = new JLabel("Name:");
l1.setBounds(20, 20, 100, 30);
JTextField tf1 = new JTextField();
tf1.setBounds(100, 20, 150, 30);
JLabel l2 = new JLabel("Age:");
l2.setBounds(20, 60, 100, 30);
JTextField tf2 = new JTextField();
tf2.setBounds(100, 60, 150, 30);
JButton save = new JButton("Save");
save.setBounds(100, 100, 100, 30);
String[] columns = {"ID", "Name", "Age"};
DefaultTableModel model = new DefaultTableModel(columns, 0);
JTable table = new JTable(model);
JScrollPane sp = new JScrollPane(table);
sp.setBounds(20, 150, 350, 200);
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) {
ex.printStackTrace();
}
});
f.add(l1); f.add(tf1);
f.add(l2); f.add(tf2);
f.add(save); f.add(sp);
f.setSize(420, 420);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}Best Practices
- Use PreparedStatement to prevent SQL injection
- Close all resources (Connection, Statement, ResultSet)
- Handle SQLException properly
- Use connection pooling for performance
Q15. Explain the advantages of Swing over AWT.
Answer:
| Feature | Swing | AWT |
|---|---|---|
| Package | javax.swing | java.awt |
| Components | Lightweight (pure Java) | Heavyweight (OS-dependent) |
| Platform | Platform independent | Platform dependent |
| Look and Feel | Pluggable | OS-specific |
| Components Count | Rich (JTable, JTree, JTabbedPane) | Limited |
| MVC Support | Yes (Model-View-Controller) | Limited |
| Performance | Better for complex UIs | Slower for complex UIs |
| Double Buffering | Built-in | Not built-in |
| Keyboard Navigation | Better support | Limited |
| Tooltips | Built-in | Manual |
| Icons | Easy to use | Limited |
Advantages of Swing
- Platform Independent — Runs consistently across OS
- Lightweight — Pure Java, no OS dependencies
- Rich Components — JTable, JTree, JTabbedPane, JSlider
- Pluggable Look and Feel — Change appearance dynamically
- MVC Architecture — Separation of model and view
- Better Event Handling — More listener types
- Double Buffering — Reduces flicker
- Keyboard Navigation — Better accessibility
Example — Swing Look and Feel
try {
UIManager.setLookAndFeel(
"javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}When to Use Swing
- Desktop applications
- Forms and data entry
- Database front-ends
- Internal business tools
- Educational software
Q16. Explain the Spring IoC container and its types.
Answer:
What is IoC Container?
The IoC Container is the core of the Spring Framework. It is responsible for:
- Creating objects (beans)
- Managing their lifecycle
- Injecting dependencies
- Managing configuration
Types of IoC Containers
1. BeanFactory
The simplest container — provides basic IoC support.
Features:
- Lazy initialization (beans created on demand)
- Lightweight
- Suitable for resource-constrained environments
Example:
BeanFactory factory = new XmlBeanFactory(
new ClassPathResource("beans.xml"));
Student student = (Student) factory.getBean("student");2. ApplicationContext
Advanced container — built on top of BeanFactory.
Features:
- Eager initialization (beans created at startup)
- Event propagation
- Internationalization (i18n)
- Annotation support
- Integration with Spring AOP
- Suitable for enterprise applications
Example:
ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");
Student student = context.getBean("student", Student.class);Comparison Table
| 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 |
Getting Beans from Context
// By name
Student s1 = (Student) context.getBean("student");
// By type
Student s2 = context.getBean(Student.class);
// By name and type
Student s3 = context.getBean("student", Student.class);Bean Definition (XML)
<bean id="student" class="com.demo.Student">
<property name="name" value="Rahul"/>
<property name="age" value="20"/>
</bean>Bean Definition (Annotation)
@Component
public class Student {
@Value("Rahul")
private String name;
@Value("20")
private int age;
}Advantages of IoC Container
- Loose Coupling — Objects don’t create dependencies
- Lifecycle Management — Container manages creation/destruction
- Configuration Flexibility — XML, annotations, Java config
- Testability — Easy to mock dependencies
- Scalability — Enterprise-ready
Q17. Explain the Spring Bean lifecycle with methods.
Answer:
Bean Lifecycle Phases
1. Instantiation
↓
2. Dependency Injection (Populate Properties)
↓
3. BeanNameAware.setBeanName()
↓
4. BeanFactoryAware.setBeanFactory()
↓
5. ApplicationContextAware.setApplicationContext()
↓
6. BeanPostProcessor.postProcessBeforeInitialization()
↓
7. @PostConstruct / InitializingBean.afterPropertiesSet() / custom init-method
↓
8. BeanPostProcessor.postProcessAfterInitialization()
↓
9. Bean Ready for Use
↓
10. @PreDestroy / DisposableBean.destroy() / custom destroy-method
↓
11. Bean RemovedKey Lifecycle Methods
1. Initialization Methods
Using @PostConstruct:
@Component
public class Student {
@PostConstruct
public void init() {
System.out.println("Bean initialized");
}
}Using InitializingBean:
public class Student implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Bean initialized");
}
}Using init-method (XML):
<bean id="student" class="com.demo.Student" init-method="init"/>2. Destruction Methods
Using @PreDestroy:
@PreDestroy
public void destroy() {
System.out.println("Bean destroyed");
}Using DisposableBean:
public class Student implements DisposableBean {
@Override
public void destroy() throws Exception {
System.out.println("Bean destroyed");
}
}Using destroy-method (XML):
<bean id="student" class="com.demo.Student" destroy-method="cleanup"/>Complete Example
@Component
public class Student {
public Student() {
System.out.println("1. Constructor called");
}
@Autowired
public void setDao(StudentDAO dao) {
System.out.println("2. Dependency injected");
}
@PostConstruct
public void init() {
System.out.println("3. @PostConstruct called");
}
public void doWork() {
System.out.println("4. Bean in use");
}
@PreDestroy
public void destroy() {
System.out.println("5. @PreDestroy called");
}
}Output (when context starts):
1. Constructor called
2. Dependency injected
3. @PostConstruct calledOutput (when context closes):
5. @PreDestroy calledComparison of Lifecycle Methods
| Method | Annotation | Interface | XML |
|---|---|---|---|
| Init | @PostConstruct | InitializingBean | init-method |
| Destroy | @PreDestroy | DisposableBean | destroy-method |
Best Practices
- Use @PostConstruct and @PreDestroy for annotations
- Prefer annotations over XML
- Keep initialization logic simple
- Close resources in destroy method
- Avoid heavy operations in constructor
Q18. Explain the difference between Spring and Spring Boot.
Answer:
| Feature | Spring Framework | Spring Boot |
|---|---|---|
| Purpose | Core framework | Rapid application development |
| Configuration | Manual (XML/annotations) | Auto-configuration |
| Setup Time | Longer | Shorter |
| Server | External server needed | Embedded server (Tomcat) |
| Dependencies | Manual management | Starter POMs |
| Deployment | WAR to server | Executable JAR |
| Boilerplate | More | Minimal |
| Learning Curve | Steeper | Easier |
| Production Ready | Manual setup | Actuator, metrics built-in |
Spring Framework Example
@Configuration
@ComponentScan(basePackages = "com.demo")
public class AppConfig {
@Bean
public DataSource dataSource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setUrl("jdbc:mysql://localhost:3306/test");
ds.setUsername("root");
ds.setPassword("root");
return ds;
}
}Spring Boot Example
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=rootKey Spring Boot Features
- Auto-configuration — Automatically configures beans based on classpath
- Starter POMs — Pre-configured dependency sets (
spring-boot-starter-web,spring-boot-starter-data-jpa) - Embedded Server — Tomcat, Jetty, Undertow included
- Actuator — Production-ready metrics
- DevTools — Hot reload during development
- CLI — Command-line interface for quick prototyping
When to Use
| Use Spring Framework | Use Spring Boot |
|---|---|
| Legacy applications | New projects |
| Fine-grained control | Rapid development |
| Custom configurations | Microservices |
| Existing WAR deployments | Standalone JARs |
Q19. Explain data binding and validation in Spring MVC forms.
Answer:
Data Binding
Data Binding is the automatic mapping of form data to Java objects.
Flow:
HTML Form → HTTP Request → Controller → Java ObjectStep 1: Model Class
public class Student {
private String name;
private String email;
private int age;
// getters and setters
}Step 2: Form (JSP)
<%@ taglib prefix="form"
uri="http://www.springframework.org/tags/form"%>
<form:form modelAttribute="student" action="save" method="post">
Name: <form:input path="name"/><br/>
Email: <form:input path="email"/><br/>
Age: <form:input path="age"/><br/>
<input type="submit" value="Submit"/>
</form:form>Step 3: Controller
@Controller
public class StudentController {
@GetMapping("/form")
public String showForm(Model model) {
model.addAttribute("student", new Student());
return "form";
}
@PostMapping("/save")
public String save(Student student) {
// Spring automatically binds form data to student object
System.out.println("Name: " + student.getName());
System.out.println("Email: " + student.getEmail());
return "success";
}
}Validation
Validation ensures user input meets specified rules.
Step 1: Add Validation Annotations
public class Student {
@NotEmpty(message = "Name is required")
private String name;
@Email(message = "Invalid email")
@NotEmpty(message = "Email is required")
private String email;
@Min(value = 18, message = "Age must be at least 18")
@Max(value = 60, message = "Age must be at most 60")
private int age;
// getters and setters
}Step 2: Enable Validation in Controller
@PostMapping("/save")
public String save(@Valid Student student, BindingResult result) {
if (result.hasErrors()) {
return "form"; // Return to form with errors
}
return "success";
}Step 3: Display Errors in JSP
<form:form modelAttribute="student">
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="Submit"/>
</form:form>Validation Annotations
| Annotation | Purpose |
|---|---|
| @NotNull | Cannot be null |
| @NotEmpty | Cannot be empty |
| @Size | Length constraints |
| Valid email format | |
| @Min | Minimum value |
| @Max | Maximum value |
| @Pattern | Regex pattern |
| @Past | Date in past |
| @Future | Date in future |
Complete Flow
1. User opens form → GET /form
2. Controller adds empty Student to model
3. Form displayed with empty fields
4. User fills form → POST /save
5. Spring binds form data to Student object
6. @Valid triggers validation
7. If errors → BindingResult has errors → return to form
8. If valid → process data → return successAdvantages
- Automatic Binding — No manual
request.getParameter() - Type Conversion — String to int/date automatically
- Validation — Declarative via annotations
- Error Display —
<form:errors>shows messages - Reusability — Model reused across forms
Q20. Explain a complete Spring MVC application with example.
Answer:
Spring MVC Application Structure
src/
├── main/
│ ├── java/
│ │ └── com/demo/
│ │ ├── controller/
│ │ │ └── StudentController.java
│ │ ├── model/
│ │ │ └── Student.java
│ │ └── config/
│ │ └── WebConfig.java
│ ├── resources/
│ │ └── application.properties
│ └── webapp/
│ └── WEB-INF/
│ ├── views/
│ │ ├── form.jsp
│ │ └── success.jsp
│ └── web.xmlStep 1: Model Class
package com.demo.model;
import javax.validation.constraints.*;
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;
// getters and setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}Step 2: Controller
package com.demo.controller;
import com.demo.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@Controller
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";
}
}Step 3: Form (form.jsp)
<%@ taglib prefix="form"
uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Student Form</title>
<style>
.error { color: red; }
</style>
</head>
<body>
<h2>Student Registration</h2>
<form:form modelAttribute="student" action="save" method="post">
<table>
<tr>
<td>Name:</td>
<td><form:input path="name"/></td>
<td><form:errors path="name" cssClass="error"/></td>
</tr>
<tr>
<td>Email:</td>
<td><form:input path="email"/></td>
<td><form:errors path="email" cssClass="error"/></td>
</tr>
<tr>
<td>Age:</td>
<td><form:input path="age"/></td>
<td><form:errors path="age" cssClass="error"/></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Submit"/></td>
</tr>
</table>
</form:form>
</body>
</html>Step 4: Success Page (success.jsp)
<html>
<body>
<h2>Registration Successful!</h2>
<p>Name: ${student.name}</p>
<p>Email: ${student.email}</p>
<p>Age: ${student.age}</p>
</body>
</html>Step 5: Spring Configuration (WebConfig.java)
package com.demo.config;
import org.springframework.context.annotation.*;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.demo")
public class WebConfig implements WebMvcConfigurer {
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}Step 6: web.xml
<web-app>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.demo.config.WebConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>Application Flow
1. User opens http://localhost:8080/form
2. DispatcherServlet receives GET /form
3. HandlerMapping finds showForm() method
4. showForm() adds empty Student to model, returns "form"
5. ViewResolver maps "form" to /WEB-INF/views/form.jsp
6. Form displayed to user
7. User fills form and submits → POST /save
8. DispatcherServlet receives POST /save
9. HandlerMapping finds save() method
10. Spring binds form data to Student object
11. @Valid triggers validation
12. If errors → return "form" (redisplay with errors)
13. If valid → return "success"
14. ViewResolver maps "success" to /WEB-INF/views/success.jsp
15. Success page displayedKey Concepts Used
| Concept | Purpose |
|---|---|
| @Controller | Marks class as controller |
| @GetMapping | Maps GET requests |
| @PostMapping | Maps POST requests |
| @ModelAttribute | Binds form data to object |
| @Valid | Triggers validation |
| BindingResult | Holds validation errors |
| Model | Passes data to view |
| ViewResolver | Maps view names to JSP |
| form:form | Spring form tag |
| form:input | Text input tag |
| form:errors | Error display tag |
Advantages
- Separation of Concerns — MVC pattern
- Validation — Declarative annotations
- Data Binding — Automatic form-to-object mapping
- Flexible View — JSP, Thymeleaf, etc.
- Testability — Controllers easily unit tested
SECTION C: ANALYTICAL QUESTIONS (10)
Q1. Analyze the following Swing code and predict the output.
import javax.swing.*;
public class Test {
public static void main(String[] args) {
JFrame f = new JFrame("Test");
JLabel l = new JLabel("Hello");
l.setBounds(50, 50, 100, 30);
JButton b = new JButton("Click");
b.setBounds(50, 100, 100, 30);
b.addActionListener(e -> l.setText("Clicked!"));
f.add(l);
f.add(b);
f.setSize(250, 200);
f.setLayout(null);
f.setVisible(true);
}
}Answer:
Initial Output:
┌─────────────────────────┐
│ Test X │
├─────────────────────────┤
│ Hello │
│ [Click] │
└─────────────────────────┘After Clicking Button:
┌─────────────────────────┐
│ Test X │
├─────────────────────────┤
│ Clicked! │
│ [Click] │
└─────────────────────────┘-> Explanation:
JFramecreates the main window.JLabeldisplays “Hello” at (50, 50).JButton“Click” at (50, 100).b.addActionListener(e -> l.setText("Clicked!"))— when clicked, changes label text.setLayout(null)enables absolute positioning.setVisible(true)displays the frame.
Key Concepts:
- Event handling with lambda expression
- Component positioning with
setBounds() - Absolute layout (
setLayout(null))
Q2. Analyze the following Spring code and identify the injection type.
@Service
public class StudentService {
private final StudentDAO dao;
@Autowired
public StudentService(StudentDAO dao) {
this.dao = dao;
}
public void save() {
dao.save();
}
}Answer:
Injection Type: Constructor Injection
-> Explanation:
@Servicemarks the class as a Spring bean.@Autowiredon the constructor tells Spring to inject dependencies.StudentDAOis provided as a constructor parameter.- The field is
final— ensures immutability. - Spring resolves
StudentDAObean and passes it to the constructor.
Advantages:
- Mandatory Dependencies — StudentService cannot be created without StudentDAO.
- Immutability —
finalfield cannot be changed after construction. - Testability — Easy to pass mock in unit tests.
- Fail-Fast — Missing dependency detected at startup.
Test Example:
@Test
public void testSave() {
StudentDAO mockDao = mock(StudentDAO.class);
StudentService service = new StudentService(mockDao);
service.save();
verify(mockDao).save();
}Key Points:
- Constructor injection is preferred for mandatory dependencies.
- Spring 4.3+ doesn’t require
@Autowiredif there’s only one constructor.
Q3. Analyze the following Spring bean configuration and predict behavior.
@Component
@Scope("prototype")
public class Student {
private static int count = 0;
public Student() {
count++;
System.out.println("Student created: " + count);
}
}ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student s1 = context.getBean(Student.class);
Student s2 = context.getBean(Student.class);
Student s3 = context.getBean(Student.class);Answer:
Output:
Student created: 1
Student created: 2
Student created: 3-> Explanation:
@Scope("prototype")— new instance created each time.getBean()called 3 times → 3 new Student objects.- Static
countincrements on each creation. - Output shows 3 separate instances.
If Scope Were Singleton:
Student created: 1Only one instance created, and all getBean() calls return the same object.
Comparison:
| Scope | Output | Objects Created |
|---|---|---|
| Prototype | 3 lines | 3 |
| Singleton | 1 line | 1 |
Key Points:
- Singleton → one instance per container
- Prototype → new instance per request
- Static fields shared across all instances
Q4. Analyze the following Spring MVC code and identify errors.
@Controller
public class StudentController {
@RequestMapping("/save")
public String save(Student student) {
System.out.println(student.getName());
return "success";
}
@RequestMapping("/form")
public String form() {
return "form";
}
}Answer:
Issues Identified:
- No model attribute for form — The form page needs a
Studentobject in the model. - No @Valid validation — Input not validated.
- No BindingResult — Validation errors not captured.
- No HTTP method specification — Both GET and POST accepted for
/save.
Corrected Code:
@Controller
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";
}
System.out.println(student.getName());
return "success";
}
}Improvements:
- @GetMapping/@PostMapping — Specific HTTP methods
- @ModelAttribute — Binds form to Student
- @Valid — Triggers validation
- BindingResult — Captures errors
- Model — Provides Student to form
Key Points:
- Always specify HTTP method
- Use
@Validfor validation - Handle errors with
BindingResult - Provide model attribute for forms
Q5. Analyze the following JDBC + Swing code and identify improvements.
button.addActionListener(e -> {
try {
Connection con = DriverManager.getConnection(url, user, password);
Statement stmt = con.createStatement();
String sql = "INSERT INTO student VALUES('" + tf.getText() + "')";
stmt.executeUpdate(sql);
} catch (SQLException ex) {
ex.printStackTrace();
}
});Answer:
Issues Identified:
- SQL Injection Risk — String concatenation in SQL
- Resource Leak — Connection and Statement not closed
- No User Feedback — No success/error message
- Driver Not Loaded —
Class.forName()missing - No PreparedStatement — Should use parameterized queries
- Catch Block Silent — Only prints stack trace
Improved Code:
button.addActionListener(e -> {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
try (Connection con = DriverManager.getConnection(url, user, password);
PreparedStatement ps = con.prepareStatement(
"INSERT INTO student(name) VALUES(?)")) {
ps.setString(1, tf.getText());
int rows = ps.executeUpdate();
if (rows > 0) {
JOptionPane.showMessageDialog(frame, "Saved successfully!");
}
}
} catch (ClassNotFoundException ex) {
JOptionPane.showMessageDialog(frame, "Driver not found");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(frame, "Error: " + ex.getMessage());
}
});Improvements:
- PreparedStatement — Prevents SQL injection
- try-with-resources — Auto-closes resources
- User Feedback — Dialog messages
- Driver Loading — Class.forName()
- Error Handling — User-friendly messages
- Affected Rows — Verify insertion
Key Points:
- Always use PreparedStatement for user input
- Close resources with try-with-resources
- Provide feedback to users
- Handle exceptions properly
Q6. Analyze the following Spring bean lifecycle code.
@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");
}
}Answer:
Output (when context starts):
1. Constructor
2. Setter
3. InitOutput (when context closes):
4. Destroy-> Explanation:
| Phase | Order | Method | Trigger |
|---|---|---|---|
| 1 | First | Constructor | Bean instantiation |
| 2 | Second | Setter | Dependency injection |
| 3 | Third | @PostConstruct | After initialization |
| 4 | Fourth | @PreDestroy | Before destruction |
Key Points:
- Constructor → Setter → @PostConstruct
- @PreDestroy called on context close
- Order is guaranteed by Spring
- Use @PostConstruct for init logic
- Use @PreDestroy for cleanup
If @PostConstruct Missing:
1. Constructor
2. SetterIf Singleton vs Prototype:
- Singleton → all phases once
- Prototype → init on each request; destroy NOT called automatically
Q7. Analyze the following Spring MVC form and identify data binding issues.
<form action="save" method="post">
Name: <input type="text" name="studentName"/>
Email: <input type="text" name="studentEmail"/>
<input type="submit" value="Submit"/>
</form>public class Student {
private String name;
private String email;
}Answer:
Issue: Data Binding Failure
Problem: Form field names (studentName, studentEmail) do not match Java field names (name, email). Spring cannot bind them.
Solutions:
Option 1: Match Names
<form action="save" method="post">
Name: <input type="text" name="name"/>
Email: <input type="text" name="email"/>
<input type="submit" value="Submit"/>
</form>Option 2: Use Spring Form Tags
<%@ taglib prefix="form"
uri="http://www.springframework.org/tags/form"%>
<form:form modelAttribute="student" action="save" method="post">
Name: <form:input path="name"/>
Email: <form:input path="email"/>
<input type="submit" value="Submit"/>
</form:form>Controller:
@PostMapping("/save")
public String save(@ModelAttribute("student") Student student) {
System.out.println(student.getName());
System.out.println(student.getEmail());
return "success";
}Key Points:
- Form field names must match Java field names
- Use
@ModelAttributefor binding - Spring form tags provide automatic binding
pathattribute maps to field name
Q8. Analyze the following Spring DI configuration and suggest improvements.
@Service
public class StudentService {
@Autowired
private StudentDAO dao;
@Autowired
private EmailService emailService;
public void register(Student student) {
dao.save(student);
emailService.send(student.getEmail());
}
}Answer:
Issues:
- Field Injection — Hard to test
- No Final Fields — Not immutable
- Hidden Dependencies — Not visible in constructor
Improved Code (Constructor Injection):
@Service
public class StudentService {
private final StudentDAO dao;
private final EmailService emailService;
@Autowired
public StudentService(StudentDAO dao, EmailService emailService) {
this.dao = dao;
this.emailService = emailService;
}
public void register(Student student) {
dao.save(student);
emailService.send(student.getEmail());
}
}Improvements:
| Aspect | Before | After |
|---|---|---|
| Injection | Field | Constructor |
| Immutability | No | Yes (final) |
| Testability | Hard | Easy |
| Dependencies | Hidden | Visible |
| Fail-fast | No | Yes |
Test Example:
@Test
public void testRegister() {
StudentDAO mockDao = mock(StudentDAO.class);
EmailService mockEmail = mock(EmailService.class);
StudentService service = new StudentService(mockDao, mockEmail);
service.register(new Student());
verify(mockDao).save(any());
verify(mockEmail).send(anyString());
}Key Points:
- Constructor injection is preferred
- Use
finalfor immutability - Dependencies visible in constructor
- Easy to mock in tests
Q9. Design a Spring MVC application for a Student Management System.
Answer:
Application Overview
Features:
- Add student
- View all students
- Update student
- Delete student
Step 1: Model Class
public class Student {
private int id;
@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;
// getters and setters
}Step 2: DAO Layer
@Repository
public class StudentDAO {
@Autowired
private JdbcTemplate jdbcTemplate;
public void save(Student student) {
String sql = "INSERT INTO student(name, email, age) VALUES(?,?,?)";
jdbcTemplate.update(sql, student.getName(),
student.getEmail(), student.getAge());
}
public List<Student> findAll() {
String sql = "SELECT * FROM student";
return jdbcTemplate.query(sql, new StudentRowMapper());
}
public void update(Student student) {
String sql = "UPDATE student SET name=?, email=?, age=? WHERE id=?";
jdbcTemplate.update(sql, student.getName(),
student.getEmail(), student.getAge(), student.getId());
}
public void delete(int id) {
String sql = "DELETE FROM student WHERE id=?";
jdbcTemplate.update(sql, id);
}
}Step 3: Service Layer
@Service
public class StudentService {
@Autowired
private StudentDAO dao;
public void save(Student student) {
dao.save(student);
}
public List<Student> getAll() {
return dao.findAll();
}
public void update(Student student) {
dao.update(student);
}
public void delete(int id) {
dao.delete(id);
}
}Step 4: Controller
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService service;
@GetMapping("/list")
public String list(Model model) {
model.addAttribute("students", service.getAll());
return "student/list";
}
@GetMapping("/add")
public String showAddForm(Model model) {
model.addAttribute("student", new Student());
return "student/form";
}
@PostMapping("/save")
public String save(@Valid @ModelAttribute("student") Student student,
BindingResult result) {
if (result.hasErrors()) {
return "student/form";
}
service.save(student);
return "redirect:/student/list";
}
@GetMapping("/edit/{id}")
public String showEditForm(@PathVariable int id, Model model) {
// Load student by id and add to model
return "student/form";
}
@GetMapping("/delete/{id}")
public String delete(@PathVariable int id) {
service.delete(id);
return "redirect:/student/list";
}
}Step 5: JSP Pages
list.jsp:
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<h2>Student List</h2>
<a href="add">Add Student</a>
<table border="1">
<tr>
<th>ID</th><th>Name</th><th>Email</th><th>Age</th><th>Actions</th>
</tr>
<c:forEach var="s" items="${students}">
<tr>
<td>${s.id}</td>
<td>${s.name}</td>
<td>${s.email}</td>
<td>${s.age}</td>
<td>
<a href="edit/${s.id}">Edit</a>
<a href="delete/${s.id}">Delete</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>form.jsp:
<%@ taglib prefix="form"
uri="http://www.springframework.org/tags/form"%>
<html>
<body>
<h2>Student Form</h2>
<form:form modelAttribute="student" action="save" method="post">
<form:hidden path="id"/>
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>
</body>
</html>Architecture
Browser
↓
DispatcherServlet
↓
StudentController
↓
StudentService
↓
StudentDAO
↓
DatabaseKey Concepts
| Layer | Purpose |
|---|---|
| Controller | Handle HTTP requests |
| Service | Business logic |
| DAO | Database operations |
| Model | Data holder |
| View | Display (JSP) |
Advantages
- Separation of Concerns — Clear layer separation
- Validation — Declarative annotations
- Data Binding — Automatic form binding
- Testability — Each layer testable
- Maintainability — Easy to modify
Q10. Design a complete desktop application using Swing + JDBC + Spring concepts.
Answer:
Application: Employee Management System
Features:
- Add employee
- View all employees
- Update employee
- Delete employee
- Search by name
Architecture
┌─────────────────┐
│ Swing UI │
└────────┬────────┘
↓
┌─────────────────┐
│ Controller │
└────────┬────────┘
↓
┌─────────────────┐
│ Service │
└────────┬────────┘
↓
┌─────────────────┐
│ DAO │
└────────┬────────┘
↓
┌─────────────────┐
│ Database │
└─────────────────┘Step 1: Model Class
public class Employee {
private int id;
private String name;
private String department;
private double salary;
// constructors, getters, setters
}Step 2: Database Connection Utility
public class DBConnection {
private static final String URL = "jdbc:mysql://localhost:3306/company";
private static final String USER = "root";
private static final String PASSWORD = "root";
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASSWORD);
}
}Step 3: DAO Layer
public class EmployeeDAO {
public void save(Employee emp) throws SQLException {
String sql = "INSERT INTO employee(name, department, salary) VALUES(?,?,?)";
try (Connection con = DBConnection.getConnection();
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setString(1, emp.getName());
ps.setString(2, emp.getDepartment());
ps.setDouble(3, emp.getSalary());
ps.executeUpdate();
}
}
public List<Employee> findAll() throws SQLException {
List<Employee> list = new ArrayList<>();
String sql = "SELECT * FROM employee";
try (Connection con = DBConnection.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
Employee e = new Employee();
e.setId(rs.getInt("id"));
e.setName(rs.getString("name"));
e.setDepartment(rs.getString("department"));
e.setSalary(rs.getDouble("salary"));
list.add(e);
}
}
return list;
}
public void update(Employee emp) throws SQLException {
String sql = "UPDATE employee SET name=?, department=?, salary=? WHERE id=?";
try (Connection con = DBConnection.getConnection();
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setString(1, emp.getName());
ps.setString(2, emp.getDepartment());
ps.setDouble(3, emp.getSalary());
ps.setInt(4, emp.getId());
ps.executeUpdate();
}
}
public void delete(int id) throws SQLException {
String sql = "DELETE FROM employee WHERE id=?";
try (Connection con = DBConnection.getConnection();
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setInt(1, id);
ps.executeUpdate();
}
}
}Step 4: Swing UI
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.util.List;
public class EmployeeApp extends JFrame {
private JTextField nameField, deptField, salaryField;
private JTable table;
private DefaultTableModel tableModel;
private EmployeeDAO dao = new EmployeeDAO();
public EmployeeApp() {
setTitle("Employee Management System");
setSize(700, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// Form Panel
JPanel formPanel = new JPanel(new GridLayout(3, 2, 5, 5));
formPanel.setBorder(BorderFactory.createTitledBorder("Employee Details"));
formPanel.add(new JLabel("Name:"));
nameField = new JTextField();
formPanel.add(nameField);
formPanel.add(new JLabel("Department:"));
deptField = new JTextField();
formPanel.add(deptField);
formPanel.add(new JLabel("Salary:"));
salaryField = new JTextField();
formPanel.add(salaryField);
// Button Panel
JPanel buttonPanel = new JPanel();
JButton addBtn = new JButton("Add");
JButton updateBtn = new JButton("Update");
JButton deleteBtn = new JButton("Delete");
JButton refreshBtn = new JButton("Refresh");
buttonPanel.add(addBtn);
buttonPanel.add(updateBtn);
buttonPanel.add(deleteBtn);
buttonPanel.add(refreshBtn);
// Table
String[] columns = {"ID", "Name", "Department", "Salary"};
tableModel = new DefaultTableModel(columns, 0);
table = new JTable(tableModel);
JScrollPane scrollPane = new JScrollPane(table);
add(formPanel, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
// Event Handlers
addBtn.addActionListener(e -> addEmployee());
updateBtn.addActionListener(e -> updateEmployee());
deleteBtn.addActionListener(e -> deleteEmployee());
refreshBtn.addActionListener(e -> loadEmployees());
// Load initial data
loadEmployees();
setVisible(true);
}
private void addEmployee() {
try {
Employee emp = new Employee();
emp.setName(nameField.getText());
emp.setDepartment(deptField.getText());
emp.setSalary(Double.parseDouble(salaryField.getText()));
dao.save(emp);
JOptionPane.showMessageDialog(this, "Employee added!");
clearFields();
loadEmployees();
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());
}
}
private void updateEmployee() {
int row = table.getSelectedRow();
if (row == -1) {
JOptionPane.showMessageDialog(this, "Select a row to update");
return;
}
try {
Employee emp = new Employee();
emp.setId((int) tableModel.getValueAt(row, 0));
emp.setName(nameField.getText());
emp.setDepartment(deptField.getText());
emp.setSalary(Double.parseDouble(salaryField.getText()));
dao.update(emp);
JOptionPane.showMessageDialog(this, "Employee updated!");
clearFields();
loadEmployees();
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());
}
}
private void deleteEmployee() {
int row = table.getSelectedRow();
if (row == -1) {
JOptionPane.showMessageDialog(this, "Select a row to delete");
return;
}
try {
int id = (int) tableModel.getValueAt(row, 0);
dao.delete(id);
JOptionPane.showMessageDialog(this, "Employee deleted!");
loadEmployees();
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());
}
}
private void loadEmployees() {
try {
tableModel.setRowCount(0);
List<Employee> employees = dao.findAll();
for (Employee e : employees) {
tableModel.addRow(new Object[]{
e.getId(), e.getName(), e.getDepartment(), e.getSalary()
});
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());
}
}
private void clearFields() {
nameField.setText("");
deptField.setText("");
salaryField.setText("");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new EmployeeApp());
}
}Step 5: Table Selection Listener
table.getSelectionModel().addListSelectionListener(e -> {
int row = table.getSelectedRow();
if (row != -1) {
nameField.setText((String) tableModel.getValueAt(row, 1));
deptField.setText((String) tableModel.getValueAt(row, 2));
salaryField.setText(String.valueOf(tableModel.getValueAt(row, 3)));
}
});Application Flow
1. User opens application
2. EmployeeApp constructor initializes UI
3. loadEmployees() fetches data from DB
4. Table displays all employees
5. User adds/updates/deletes → DAO methods called
6. Database updated
7. loadEmployees() refreshes tableKey Concepts Used
| Concept | Usage |
|---|---|
| JFrame | Main window |
| JPanel | Form and button grouping |
| JTable | Display employee data |
| DefaultTableModel | Table data management |
| JTextField | Input fields |
| JButton | Action triggers |
| ActionListener | Button click handling |
| JDBC | Database connectivity |
| PreparedStatement | Secure SQL execution |
| try-with-resources | Auto-close resources |
Advantages
- User-Friendly — GUI interface
- Secure — PreparedStatement prevents SQL injection
- Resource-Safe — try-with-resources closes connections
- Responsive — Immediate feedback via dialogs
- Maintainable — Clear layer separation
- Extensible — Easy to add features
Extensions
- Search functionality — Filter by name
- Export to CSV — Save employee data
- Login screen — Authentication
- Reports — Generate employee reports
- Pagination — Handle large datasets
SUMMARY TABLE
| Section | Count | Topics Covered |
|---|---|---|
| MCQ | 50 | Swing components, containers, layouts, events, IDE, Spring, IoC, DI, beans, scope, lifecycle, Spring MVC, validation |
| Theory | 20 | Swing features, components, layouts, event handling, Spring features, IoC, DI, bean scope, lifecycle, Spring MVC, request mapping, form tags, validation, architecture, calculator, JDBC+Swing, Swing vs AWT, Spring containers, bean lifecycle, Spring vs Spring Boot, data binding, complete Spring MVC app |
| Analytical | 10 | Code analysis, error identification, DI analysis, bean scope, Spring MVC errors, JDBC+Swing improvements, lifecycle, form binding, DI improvements, complete application design |