BTCE | 5th Sem
Adv-Java SubjectUnit 4

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?

  1. Database connectivity
  2. GUI components for desktop applications
  3. Web server functionality
  4. 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?

  1. Java Database Connectivity
  2. Java Foundation Classes (JFC)
  3. Java Server Pages
  4. 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?

  1. JFrame
  2. JButton
  3. JTextField
  4. 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:

  1. They use less memory
  2. They are implemented in Java, not OS-dependent
  3. They are faster
  4. 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?

  1. java.awt
  2. javax.swing
  3. java.swing
  4. javax.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?

  1. JPanel
  2. JFrame
  3. JButton
  4. 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?

  1. JTextField
  2. JLabel
  3. JButton
  4. 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?

  1. JLabel
  2. JTextField
  3. JButton
  4. 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?

  1. JLabel
  2. JTextField
  3. JButton
  4. JCheckBox

Answer: C) JButton -> Explanation: JButton represents a clickable button. When clicked, it generates an ActionEvent.


Q10. Which component allows multiple selections?

  1. JRadioButton
  2. JCheckBox
  3. JButton
  4. 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?

  1. JTable
  2. JList
  3. JComboBox
  4. 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?

  1. JList
  2. JComboBox
  3. JCheckBox
  4. 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?

  1. JFrame
  2. JPanel
  3. JButton
  4. 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?

  1. BorderLayout
  2. GridLayout
  3. FlowLayout
  4. 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?

  1. FlowLayout
  2. GridLayout
  3. BorderLayout
  4. 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?

  1. FlowLayout
  2. BorderLayout
  3. GridLayout
  4. 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?

  1. FlowLayout
  2. BorderLayout
  3. GridLayout
  4. 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?

  1. Observer model
  2. Delegation Event Model
  3. Producer-Consumer model
  4. 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?

  1. MouseListener
  2. KeyListener
  3. ActionListener
  4. WindowListener

Answer: C) ActionListener -> Explanation: ActionListener handles button clicks. It has one method: actionPerformed(ActionEvent e).


Q20. Which method must be implemented in ActionListener?

  1. actionEvent()
  2. actionPerformed()
  3. performAction()
  4. 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?

  1. A class that generates events
  2. A class providing default implementations of listener methods
  3. A class that blocks events
  4. 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?

  1. setDimension()
  2. setSize()
  3. setBounds()
  4. 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?

  1. show()
  2. display()
  3. setVisible(true)
  4. 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?

  1. setClose()
  2. setDefaultCloseOperation()
  3. setExit()
  4. 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?

  1. Integrated Development Environment
  2. Internal Debugging Engine
  3. Interactive Design Editor
  4. 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?

  1. Eclipse
  2. NetBeans
  3. IntelliJ IDEA
  4. 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?

  1. Breaking the program permanently
  2. Pausing program execution for debugging
  3. Closing the program
  4. 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?

  1. Syntax highlighting
  2. Auto completion
  3. Error detection
  4. 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?

  1. JTextField and JButton
  2. JTable and JTree
  3. JMenu and JMenuItem
  4. 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?

  1. Integer.parse()
  2. Integer.parseInt()
  3. Integer.valueOfInt()
  4. 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?

  1. setText()
  2. setValue()
  3. setString()
  4. 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?

  1. DriverManager.getConnection()
  2. Connection.open()
  3. Database.connect()
  4. 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?

  1. Input/Output Control
  2. Inversion of Control
  3. Internal Object Creation
  4. 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?

  1. Direct Integration
  2. Dependency Injection
  3. Dynamic Inheritance
  4. 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?

  1. @Bean
  2. @Component
  3. @Service
  4. 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?

  1. @Inject
  2. @Autowired
  3. @Resource
  4. @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?

  1. Lightweight
  2. Modular design
  3. Tight coupling
  4. 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?

  1. Spring MVC
  2. Spring JDBC
  3. Spring Security
  4. 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?

  1. A JavaBean component
  2. An object managed by the Spring container
  3. A configuration file
  4. 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?

  1. spring.xml
  2. beans.xml
  3. config.xml
  4. application.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?

  1. Setter Injection
  2. Constructor Injection
  3. Field Injection
  4. 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?

  1. Constructor Injection
  2. Setter Injection
  3. Field Injection
  4. 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?

  1. Constructor Injection
  2. Setter Injection
  3. Field Injection
  4. 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?

  1. Setter Injection
  2. Constructor Injection
  3. Field Injection
  4. 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?

  1. Prototype
  2. Singleton
  3. Request
  4. 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?

  1. Singleton
  2. Prototype
  3. Request
  4. 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?

  1. @Init
  2. @PostConstruct
  3. @AfterConstruct
  4. @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?

  1. @Destroy
  2. @PreDestroy
  3. @BeforeDestroy
  4. @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?

  1. Controller
  2. DispatcherServlet
  3. ViewResolver
  4. 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?

  1. @Email
  2. @ValidEmail
  3. @EmailAddress
  4. @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:

#FeatureExplanation
1GUI ToolkitProvides components for desktop applications
2Platform IndependentRuns on different operating systems
3Lightweight ComponentsImplemented in Java, not OS-dependent
4Rich ComponentsJFrame, JLabel, JTextField, JButton, JCheckBox, JRadioButton, JComboBox, JTable
5Event HandlingUses event listeners to respond to user actions
6Easy to Build FormsLogin, registration, calculator, student management
7Separation of GUI and LogicInterface 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:

  1. Platform Independent
  2. Rich GUI Components
  3. Event-Driven Programming
  4. Easy Database Integration
  5. 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 input

3. 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

ComponentPurposeInteractive?
JLabelDisplay text/imageNo
JTextFieldText inputYes
JButtonTrigger actionYes
JCheckBoxMultiple selectionsYes

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
        South

3. GridLayout

Arranges components in a grid of rows and columns.

frame.setLayout(new GridLayout(2, 2));

Example:

A B
C D

4. 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

LayoutArrangementDefault For
FlowLayoutLeft to rightJPanel
BorderLayout5 regionsJFrame
GridLayoutRows × columnsCustom grids
CardLayoutStacked cardsWizards, tabs
GridBagLayoutFlexible gridComplex 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:

ComponentPurpose
SourceThe component that generates the event (e.g., JButton)
Event ObjectContains information about the event (e.g., ActionEvent)
ListenerReceives and handles the event (e.g., ActionListener)

Flow:

Button → ActionEvent → ActionListener → actionPerformed()

2. Common Listeners

ListenerPurposeMethod
ActionListenerButton clicksactionPerformed(ActionEvent e)
MouseListenerMouse eventsmouseClicked(), mousePressed(), etc.
KeyListenerKeyboard eventskeyPressed(), keyReleased(), keyTyped()
WindowListenerWindow eventswindowClosing(), 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:

  1. Less coding
  2. 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 AOP

Benefits: Flexibility, easy integration, reduced complexity.

3. Dependency Management

Spring manages dependencies automatically.

Without Spring:

StudentDAO dao = new StudentDAO();   // Tightly coupled

With Spring:

@Autowired
private StudentDAO dao;   // Spring injects automatically

Benefits: 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

  1. Loose Coupling
  2. Easier Testing
  3. Better Maintainability
  4. Reusability
  5. 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 objects

Spring (With IoC):

@Autowired
StudentDAO dao;   // Spring creates and injects objects

IoC Flow

Application
    ↓
Spring Container
    ↓
Object Creation
    ↓
Dependency Injection

Bean 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:

  1. Object Creation
  2. Dependency Injection
  3. Lifecycle Management
  4. Configuration Management

Example:

ApplicationContext context =
    new ClassPathXmlApplicationContext("beans.xml");

Advantages of IoC

  1. Loose Coupling — Objects don’t create their dependencies
  2. Easier Testing — Dependencies can be mocked
  3. Better Maintainability — Changes in one place
  4. Reusability — Beans can be reused
  5. Scalability — Container manages resources

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:

  1. Mandatory Dependencies
  2. 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:

  1. Optional Dependencies
  2. Flexible Configuration

3. Field Injection

Uses @Autowired directly on fields.

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

Advantages:

  1. Less Code
  2. Simple Configuration

Disadvantages:

  • Difficult to test

Comparison Table

TechniqueInjection PointMandatory?Testability
ConstructorConstructorYesBest
SetterSetter methodNoGood
FieldField directlyYesPoor

Dependency Resolution

Spring resolves dependencies automatically.

@Autowired
private StudentDAO dao;

Spring searches:

  1. Matching Bean
  2. Matching Type
  3. 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 Object

2. 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 3

Difference Table

AspectSingletonPrototype
ObjectsOne ObjectMultiple Objects
DefaultYesExplicit Scope
MemoryLess MemoryMore Memory
Use CaseStateless beansStateful beans

Bean Lifecycle

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

Bean 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

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

Advantages of Spring MVC

  1. Separation of Concerns
  2. Easy Validation
  3. Powerful Request Mapping
  4. Flexible View Management
  5. 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

TagPurpose
<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

  1. Reduced Code — No manual parameter extraction
  2. Data Binding — Automatic mapping
  3. Validation Integration — Errors displayed easily
  4. 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

AnnotationPurpose
@NotNullCannot be null
@NotEmptyCannot be empty
@SizeLength validation
@EmailEmail validation
@MinMinimum value
@MaxMaximum value
@PatternRegex 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 success

6. Advantages

  1. Automatic Validation — No manual checks
  2. Error Handling — Errors displayed to user
  3. Reusable — Annotations used across application
  4. 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:

  1. BeanFactory — Basic container
  2. ApplicationContext — Advanced container
  3. 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

LayerPurposeKey Components
Core ContainerBean managementBeanFactory, ApplicationContext
Data AccessDatabase operationsJdbcTemplate, ORM
Web LayerWeb applicationsSpring MVC, Controllers
IntegrationExternal technologiesHibernate, 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

ConceptUsage
JFrameMain window
JTextFieldDisplay
JButtonDigits and operations
GridLayoutButton arrangement
ActionListenerHandle clicks
Lambda expressionConcise 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

  1. Use PreparedStatement to prevent SQL injection
  2. Close all resources (Connection, Statement, ResultSet)
  3. Handle SQLException properly
  4. Use connection pooling for performance

Q15. Explain the advantages of Swing over AWT.

Answer:

FeatureSwingAWT
Packagejavax.swingjava.awt
ComponentsLightweight (pure Java)Heavyweight (OS-dependent)
PlatformPlatform independentPlatform dependent
Look and FeelPluggableOS-specific
Components CountRich (JTable, JTree, JTabbedPane)Limited
MVC SupportYes (Model-View-Controller)Limited
PerformanceBetter for complex UIsSlower for complex UIs
Double BufferingBuilt-inNot built-in
Keyboard NavigationBetter supportLimited
TooltipsBuilt-inManual
IconsEasy to useLimited

Advantages of Swing

  1. Platform Independent — Runs consistently across OS
  2. Lightweight — Pure Java, no OS dependencies
  3. Rich Components — JTable, JTree, JTabbedPane, JSlider
  4. Pluggable Look and Feel — Change appearance dynamically
  5. MVC Architecture — Separation of model and view
  6. Better Event Handling — More listener types
  7. Double Buffering — Reduces flicker
  8. 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

FeatureBeanFactoryApplicationContext
InitializationLazyEager
Annotation SupportNoYes
Event HandlingNoYes
i18nNoYes
AOP IntegrationBasicFull
MemoryLessMore
Use CaseSmall appsEnterprise 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

  1. Loose Coupling — Objects don’t create dependencies
  2. Lifecycle Management — Container manages creation/destruction
  3. Configuration Flexibility — XML, annotations, Java config
  4. Testability — Easy to mock dependencies
  5. 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 Removed

Key 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 called

Output (when context closes):

5. @PreDestroy called

Comparison of Lifecycle Methods

MethodAnnotationInterfaceXML
Init@PostConstructInitializingBeaninit-method
Destroy@PreDestroyDisposableBeandestroy-method

Best Practices

  1. Use @PostConstruct and @PreDestroy for annotations
  2. Prefer annotations over XML
  3. Keep initialization logic simple
  4. Close resources in destroy method
  5. Avoid heavy operations in constructor

Q18. Explain the difference between Spring and Spring Boot.

Answer:

FeatureSpring FrameworkSpring Boot
PurposeCore frameworkRapid application development
ConfigurationManual (XML/annotations)Auto-configuration
Setup TimeLongerShorter
ServerExternal server neededEmbedded server (Tomcat)
DependenciesManual managementStarter POMs
DeploymentWAR to serverExecutable JAR
BoilerplateMoreMinimal
Learning CurveSteeperEasier
Production ReadyManual setupActuator, 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=root

Key Spring Boot Features

  1. Auto-configuration — Automatically configures beans based on classpath
  2. Starter POMs — Pre-configured dependency sets (spring-boot-starter-web, spring-boot-starter-data-jpa)
  3. Embedded Server — Tomcat, Jetty, Undertow included
  4. Actuator — Production-ready metrics
  5. DevTools — Hot reload during development
  6. CLI — Command-line interface for quick prototyping

When to Use

Use Spring FrameworkUse Spring Boot
Legacy applicationsNew projects
Fine-grained controlRapid development
Custom configurationsMicroservices
Existing WAR deploymentsStandalone 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 Object

Step 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

AnnotationPurpose
@NotNullCannot be null
@NotEmptyCannot be empty
@SizeLength constraints
@EmailValid email format
@MinMinimum value
@MaxMaximum value
@PatternRegex pattern
@PastDate in past
@FutureDate 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 success

Advantages

  1. Automatic Binding — No manual request.getParameter()
  2. Type Conversion — String to int/date automatically
  3. Validation — Declarative via annotations
  4. Error Display — <form:errors> shows messages
  5. 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.xml

Step 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 displayed

Key Concepts Used

ConceptPurpose
@ControllerMarks class as controller
@GetMappingMaps GET requests
@PostMappingMaps POST requests
@ModelAttributeBinds form data to object
@ValidTriggers validation
BindingResultHolds validation errors
ModelPasses data to view
ViewResolverMaps view names to JSP
form:formSpring form tag
form:inputText input tag
form:errorsError display tag

Advantages

  1. Separation of Concerns — MVC pattern
  2. Validation — Declarative annotations
  3. Data Binding — Automatic form-to-object mapping
  4. Flexible View — JSP, Thymeleaf, etc.
  5. 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:

  1. JFrame creates the main window.
  2. JLabel displays “Hello” at (50, 50).
  3. JButton “Click” at (50, 100).
  4. b.addActionListener(e -> l.setText("Clicked!")) — when clicked, changes label text.
  5. setLayout(null) enables absolute positioning.
  6. 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:

  1. @Service marks the class as a Spring bean.
  2. @Autowired on the constructor tells Spring to inject dependencies.
  3. StudentDAO is provided as a constructor parameter.
  4. The field is final — ensures immutability.
  5. Spring resolves StudentDAO bean and passes it to the constructor.

Advantages:

  1. Mandatory Dependencies — StudentService cannot be created without StudentDAO.
  2. Immutability — final field cannot be changed after construction.
  3. Testability — Easy to pass mock in unit tests.
  4. 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 @Autowired if 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:

  1. @Scope("prototype") — new instance created each time.
  2. getBean() called 3 times → 3 new Student objects.
  3. Static count increments on each creation.
  4. Output shows 3 separate instances.

If Scope Were Singleton:

Student created: 1

Only one instance created, and all getBean() calls return the same object.

Comparison:

ScopeOutputObjects Created
Prototype3 lines3
Singleton1 line1

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:

  1. No model attribute for form — The form page needs a Student object in the model.
  2. No @Valid validation — Input not validated.
  3. No BindingResult — Validation errors not captured.
  4. 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:

  1. @GetMapping/@PostMapping — Specific HTTP methods
  2. @ModelAttribute — Binds form to Student
  3. @Valid — Triggers validation
  4. BindingResult — Captures errors
  5. Model — Provides Student to form

Key Points:

  • Always specify HTTP method
  • Use @Valid for 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:

  1. SQL Injection Risk — String concatenation in SQL
  2. Resource Leak — Connection and Statement not closed
  3. No User Feedback — No success/error message
  4. Driver Not Loaded — Class.forName() missing
  5. No PreparedStatement — Should use parameterized queries
  6. 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:

  1. PreparedStatement — Prevents SQL injection
  2. try-with-resources — Auto-closes resources
  3. User Feedback — Dialog messages
  4. Driver Loading — Class.forName()
  5. Error Handling — User-friendly messages
  6. 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. Init

Output (when context closes):

4. Destroy

-> Explanation:

PhaseOrderMethodTrigger
1FirstConstructorBean instantiation
2SecondSetterDependency injection
3Third@PostConstructAfter initialization
4Fourth@PreDestroyBefore 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. Setter

If 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 @ModelAttribute for binding
  • Spring form tags provide automatic binding
  • path attribute 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:

  1. Field Injection — Hard to test
  2. No Final Fields — Not immutable
  3. 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:

AspectBeforeAfter
InjectionFieldConstructor
ImmutabilityNoYes (final)
TestabilityHardEasy
DependenciesHiddenVisible
Fail-fastNoYes

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 final for 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
    ↓
Database

Key Concepts

LayerPurpose
ControllerHandle HTTP requests
ServiceBusiness logic
DAODatabase operations
ModelData holder
ViewDisplay (JSP)

Advantages

  1. Separation of Concerns — Clear layer separation
  2. Validation — Declarative annotations
  3. Data Binding — Automatic form binding
  4. Testability — Each layer testable
  5. 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 table

Key Concepts Used

ConceptUsage
JFrameMain window
JPanelForm and button grouping
JTableDisplay employee data
DefaultTableModelTable data management
JTextFieldInput fields
JButtonAction triggers
ActionListenerButton click handling
JDBCDatabase connectivity
PreparedStatementSecure SQL execution
try-with-resourcesAuto-close resources

Advantages

  1. User-Friendly — GUI interface
  2. Secure — PreparedStatement prevents SQL injection
  3. Resource-Safe — try-with-resources closes connections
  4. Responsive — Immediate feedback via dialogs
  5. Maintainable — Clear layer separation
  6. 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

SectionCountTopics Covered
MCQ50Swing components, containers, layouts, events, IDE, Spring, IoC, DI, beans, scope, lifecycle, Spring MVC, validation
Theory20Swing 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
Analytical10Code analysis, error identification, DI analysis, bean scope, Spring MVC errors, JDBC+Swing improvements, lifecycle, form binding, DI improvements, complete application design

On this page

SECTION A: MULTIPLE CHOICE QUESTIONS (50 MCQs)Introduction to Java SwingsSwing ComponentsContainers and Layout ManagersEvent HandlingIDE and DebuggingDesktop Application DevelopmentSpring Framework FundamentalsDependency InjectionBean Scope and LifecycleSpring MVC and ValidationSECTION B: THEORY QUESTIONS (20)1. JLabel2. JTextField3. JButton4. JCheckBox5. Comparison Table6. Complete Example1. FlowLayout2. BorderLayout3. GridLayout4. CardLayout5. GridBagLayout6. Comparison Table7. Example — GridLayout1. Delegation Event Model2. Common Listeners3. ActionListener Example4. Event Adapters5. Complete ExampleFeatures of Spring Framework1. Lightweight Framework2. Modular Design3. Dependency Management4. Enterprise Application SupportSpring ArchitectureAdvantages of SpringTraditional Approach vs Spring ApproachIoC FlowBean ManagementContainer ServicesAdvantages of IoC1. Constructor Injection2. Setter Injection3. Field InjectionComparison TableDependency ResolutionBean Scope1. Singleton Scope2. Prototype ScopeDifference TableBean LifecycleBean InitializationBean DestructionComplete ExampleSpring MVC Architecture1. DispatcherServlet2. Configuration Files3. Controller Setup4. View Resolver5. Complete FlowAdvantages of Spring MVC1. RequestMapping Annotation2. URL Mapping3. Form Tag Library4. Data Binding5. Common Form Tags6. Complete ExampleAdvantages1. Validation Annotations2. Model Class with Validation3. Controller with @Valid4. Displaying Errors in JSP5. Validation Flow6. AdvantagesSpring Architecture Overview1. Core Container2. Data Access Layer3. Web Layer4. Integration LayerModule SummaryCalculator Application DesignStep 1: Create JFrameStep 2: Create Display (JTextField)Step 3: Create Buttons PanelStep 4: Add ButtonsStep 5: Event HandlingStep 6: Complete ExampleKey Concepts UsedSwing + JDBC IntegrationStep 1: Load JDBC DriverStep 2: Establish ConnectionStep 3: Create Swing FormStep 4: Handle Save ButtonStep 5: Retrieve Data and Display in JTableStep 6: Complete ExampleBest PracticesAdvantages of SwingExample — Swing Look and FeelWhen to Use SwingWhat is IoC Container?Types of IoC Containers1. BeanFactory2. ApplicationContextComparison TableGetting Beans from ContextBean Definition (XML)Bean Definition (Annotation)Advantages of IoC ContainerBean Lifecycle PhasesKey Lifecycle Methods1. Initialization Methods2. Destruction MethodsComplete ExampleComparison of Lifecycle MethodsBest PracticesSpring Framework ExampleSpring Boot ExampleKey Spring Boot FeaturesWhen to UseData BindingStep 1: Model ClassStep 2: Form (JSP)Step 3: ControllerValidationStep 1: Add Validation AnnotationsStep 2: Enable Validation in ControllerStep 3: Display Errors in JSPValidation AnnotationsComplete FlowAdvantagesSpring MVC Application StructureStep 1: Model ClassStep 2: ControllerStep 3: Form (form.jsp)Step 4: Success Page (success.jsp)Step 5: Spring Configuration (WebConfig.java)Step 6: web.xmlApplication FlowKey Concepts UsedAdvantagesSECTION C: ANALYTICAL QUESTIONS (10)Application OverviewStep 1: Model ClassStep 2: DAO LayerStep 3: Service LayerStep 4: ControllerStep 5: JSP PagesArchitectureKey ConceptsAdvantagesApplication: Employee Management SystemArchitectureStep 1: Model ClassStep 2: Database Connection UtilityStep 3: DAO LayerStep 4: Swing UIStep 5: Table Selection ListenerApplication FlowKey Concepts UsedAdvantagesExtensionsSUMMARY TABLE