0% found this document useful (0 votes)
33 views68 pages

Advanced Java Programming Practicals

The document contains a series of Java programming practicals covering various concepts such as OOPs, Swing, AWT, Event Handling, JDBC, and Servlets. Each section includes code examples demonstrating class and object implementation, abstraction, encapsulation, inheritance, GUI components, mouse and keyboard event handling, database operations, and servlet creation. The document serves as a comprehensive guide for MCA students to understand and apply advanced Java programming techniques.

Uploaded by

Rumesh Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views68 pages

Advanced Java Programming Practicals

The document contains a series of Java programming practicals covering various concepts such as OOPs, Swing, AWT, Event Handling, JDBC, and Servlets. Each section includes code examples demonstrating class and object implementation, abstraction, encapsulation, inheritance, GUI components, mouse and keyboard event handling, database operations, and servlet creation. The document serves as a comprehensive guide for MCA students to understand and apply advanced Java programming techniques.

Uploaded by

Rumesh Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

ADVANCED JAVA PRACTICALS

[Link]
MCA – 1ST YEAR
ROLL NO: MC25(32)
DATE OF SUBMISSION:
OOPs Concept

1..Write a Java program to implement class and objects.


class Student {

// Data members (properties)

String name;

int age;

String course;

// Method to display student details

void displayInfo() {

[Link]("Student Name: " + name);

[Link]("Age: " + age);

[Link]("Course: " + course);

public class Class_Object {

public static void main(String[] args) {

// Creating first object

Student s1 = new Student();

[Link] = "Rahul";

[Link] = 20;
[Link] = "Computer Science";

// Creating second object

Student s2 = new Student();

[Link] = "Anita";

[Link] = 22;

[Link] = "Information Technology";

// Displaying information

[Link]("---- Student 1 Details ----");

[Link]();

[Link]("\n---- Student 2 Details ----");

[Link]();

OUTPUT:
2.. Program to implement Abstraction in Java
// Abstract class

abstract class Animal {

// Abstract method (no body)

abstract void sound();

// Non-abstract method (normal method)

void sleep() {

[Link]("This animal is sleeping...");

// Child class

class Dog extends Animal {

// Implementing abstract method

void sound() {

[Link]("Dog barks: Woof Woof!");

// Main class

public class Abstraction {

public static void main(String[] args) {


Animal obj = new Dog(); // Upcasting

[Link](); // Calls subclass method

[Link](); // Calls non-abstract method

OUTPUT:
3..Program to implement Encapsulation in Java
class Student1 {

// Private data members (cannot be accessed directly)

private String name;

private int age;

// Public setter method → write data

public void setName(String name) {

[Link] = name;

// Public getter method → read data

public String getName() {

return name;

// Setter for age

public void setAge(int age) {

if (age > 0) {

[Link] = age;

} else {

[Link]("Invalid age!");

}
}

// Getter for age

public int getAge() {

return age;

public class Encapsulation {

public static void main(String[] args) {

Student1 s = new Student1();

// Setting values using setters (safe access)

[Link]("Rahul");

[Link](20);

// Getting values using getters

[Link]("Student Name: " + [Link]());

[Link]("Age: " + [Link]());

OUPUT:
4..Program to implement Inheritance in Java
// Parent class (superclass)

class Animal1 {

void eat() {

[Link]("This animal eats food.");

// Child class (subclass) inherits from Animal

class Dog1 extends Animal1 {

void bark() {

[Link]("The dog barks: Woof Woof!");

// Main class

public class Inheritance {

public static void main(String[] args) {

// Object of subclass

Dog1 d = new Dog1();

[Link](); // Inherited from Animal


[Link](); // Dog's own method

OUTPUT:
Swing

1..Develop a program using label to display the msg SNDT website


clip
package Swing;

import [Link].*;

public class SNDTLabel

public static void main(String[] args) {

Frame f = new Frame("Colored Label Example");

// Creating a Label

Label l = new Label("SNDT Website Clip");

// Setting label text color and background color

[Link]([Link]); // Text color

[Link]([Link]); // Label background

// Setting frame size and layout

[Link](350, 200);

[Link](new FlowLayout());
// Adding label

[Link](l);

// Setting frame background color

[Link](Color.LIGHT_GRAY);

// Making frame visible

[Link](true);

OUTPUT:
2..Write a program to create 3 butttons with caption submit ok
cancel
package Swing;

import [Link].*;

import [Link].*;

public class ThreeButtons {

public static void main(String[] args) {

Frame f = new Frame("Button Action Example");

// Creating buttons

Button submit = new Button("Submit");

Button ok = new Button("OK");

Button cancel = new Button("Cancel");

// Layout & frame settings

[Link](400, 250);

[Link](new FlowLayout());

// SUBMIT Button Action

[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {

[Link]([Link]);

});

// OK Button Action

[Link](new ActionListener() {

public void actionPerformed(ActionEvent e) {

[Link]([Link]);

});

// CANCEL Button Action

[Link](new ActionListener() {

public void actionPerformed(ActionEvent e) {

[Link]([Link]);

});

// Adding components

[Link](submit);

[Link](ok);

[Link](cancel);

[Link](true);
}

OUTPUT:
AWT

1..Write a program to implement the java AWT program to create a


button
package AWT;

import [Link].*;

public class CreateButton {

public static void main(String[] args) {

Frame f = new Frame("AWT Button Example");

// Create Button

Button b = new Button("Click Me");

// Set button position & size (optional)

[Link](80, 100, 100, 40);

// Add button to frame

[Link](b);

// Frame settings

[Link](300, 250);

[Link](null); // Using no layout


[Link](true);

OUTPUT
Event Handling

1..Write a java program that handles all basic mouse events (click,
press, release, enter and exit) and display the current event name
in the window using MouseListener
package EventHandling;

import [Link].*;

import [Link].*;

public class MouseEventsDemo extends Frame implements MouseListener {

String msg = "";

public MouseEventsDemo() {

// Register the mouse listener

addMouseListener(this);

setSize(400, 300);

setTitle("Mouse Listener Demo");

setVisible(true);

// MouseListener methods
public void mouseClicked(MouseEvent e) {

msg = "Mouse Clicked";

repaint();

public void mousePressed(MouseEvent e) {

msg = "Mouse Pressed";

repaint();

public void mouseReleased(MouseEvent e) {

msg = "Mouse Released";

repaint();

public void mouseEntered(MouseEvent e) {

msg = "Mouse Entered";

repaint();

public void mouseExited(MouseEvent e) {

msg = "Mouse Exited";

repaint();
}

// To display the message on window

public void paint(Graphics g) {

[Link](new Font("Arial", [Link], 20));

[Link](msg, 120, 150);

public static void main(String[] args) {

new MouseEventsDemo();

OUTPUT:
2..WJP to demonstrate MouseMotionListener by showing the
current mouse x,y coordinate in a label while the mouse is move or
drag over the frame
package EventHandling;

import [Link].*;

import [Link].*;

public class MouseMotionDemo extends Frame implements


MouseMotionListener {

Label lbl;

public MouseMotionDemo() {

// Create label

lbl = new Label("Move the mouse inside the window");

[Link](50, 50, 250, 30);

// Adding label to frame

add(lbl);

// Register mouse motion listener

addMouseMotionListener(this);
// Frame settings

setSize(400, 300);

setLayout(null);

setTitle("Mouse Motion Listener Demo");

setVisible(true);

// Mouse moved event

public void mouseMoved(MouseEvent e) {

[Link]("Mouse Moved: X = " + [Link]() + ", Y = " + [Link]());

// Mouse dragged event

public void mouseDragged(MouseEvent e) {

[Link]("Mouse Dragged: X = " + [Link]() + ", Y = " + [Link]());

public static void main(String[] args) {

new MouseMotionDemo();

}
3..WJP that use an adapter class to handle mouse events and
display the event name in the center of the window
package EventHandling;

import [Link].*;

import [Link].*;

public class MouseAdapterDemo extends Frame {

String msg = "";

public MouseAdapterDemo() {

// Add mouse listener using adapter class

addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) {

msg = "Mouse Clicked";

repaint();

public void mousePressed(MouseEvent e) {

msg = "Mouse Pressed";

repaint();

public void mouseReleased(MouseEvent e) {


msg = "Mouse Released";

repaint();

public void mouseEntered(MouseEvent e) {

msg = "Mouse Entered";

repaint();

public void mouseExited(MouseEvent e) {

msg = "Mouse Exited";

repaint();

});

setSize(400, 300);

setTitle("Mouse Adapter Demo");

setVisible(true);

// Display event name in center

public void paint(Graphics g) {

[Link](new Font("Arial", [Link], 20));

[Link](msg, 120, 150);

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

new MouseAdapterDemo();

OUTPUT:
4..WJP using keyListener that

i)take keyboard input in a textfield

ii)show in a label whether the last key was press , release or type
package EventHandling;

import [Link].*;

import [Link].*;

import [Link].*;

public class KeyListenerDemo extends JFrame implements KeyListener {

private JTextField tf;

private JLabel lbl;

public KeyListenerDemo() {

setTitle("Key Listener Demo");

setSize(400, 200);

setLayout(new FlowLayout());

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

tf = new JTextField(20);

[Link](this); // attaching keyListener


lbl = new JLabel("Press any key inside the textfield");

add(tf);

add(lbl);

setVisible(true);

@Override

public void keyPressed(KeyEvent e) {

[Link]("Key Pressed: " + [Link]());

@Override

public void keyReleased(KeyEvent e) {

[Link]("Key Released: " + [Link]());

@Override

public void keyTyped(KeyEvent e) {

[Link]("Key Typed: " + [Link]());

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

new KeyListenerDemo();

OUTPUT:
5..WJP with two buttons RED and BLUE on clicking each button the
background of the frame changed accordingly using an
ActionListener
package EventHandling;

import [Link].*;

import [Link].*;

import [Link].*;

public class ColorChangeFrame extends JFrame implements ActionListener {

private JButton redBtn, blueBtn;

public ColorChangeFrame() {

setTitle("Color Change Demo");

setSize(400, 200);

setLayout(new FlowLayout());

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Buttons

redBtn = new JButton("RED");

blueBtn = new JButton("BLUE");


// Add ActionListeners

[Link](this);

[Link](this);

add(redBtn);

add(blueBtn);

setVisible(true);

@Override

public void actionPerformed(ActionEvent e) {

if ([Link]() == redBtn) {

getContentPane().setBackground([Link]);

else if ([Link]() == blueBtn) {

getContentPane().setBackground([Link]);

public static void main(String[] args) {

new ColorChangeFrame();
}

OUTPUT:
[Link] to demonstrate windowListener such that a conformation
dialogue appears when the user tries to close the window
package EventHandling;

import [Link].*;

import [Link].*;

public class WindowListenerDemo extends JFrame implements


WindowListener {

public WindowListenerDemo() {

setTitle("Window Listener Demo");

setSize(400, 200);

// Add WindowListener

addWindowListener(this);

setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

setVisible(true);

@Override

public void windowClosing(WindowEvent e) {


int choice = [Link](

this,

"Are you sure you want to exit?",

"Confirm Exit",

JOptionPane.YES_NO_OPTION

);

if (choice == JOptionPane.YES_OPTION) {

dispose(); // close the window

// If NO → window stays open

// Unused methods but required by WindowListener

public void windowOpened(WindowEvent e) {}

public void windowClosed(WindowEvent e) {}

public void windowIconified(WindowEvent e) {}

public void windowDeiconified(WindowEvent e) {}

public void windowActivated(WindowEvent e) {}

public void windowDeactivated(WindowEvent e) {}

public static void main(String[] args) {

new WindowListenerDemo();
}

OUTPUT:
JDBC

1.A Program to execute select query using JDBC.

package selectdemo;

import [Link].*;

public class SelectDemo {

public static void main(String[] args) {

String url = "jdbc:mysql://localhost:3306/practical?


useSSL=false&allowPublicKeyRetrieval=true"; // your DB name

String username = "root"; // your MySQL username

String password = "ab3022"; // your MySQL password

try {

// 1. Load MySQL JDBC Driver

[Link]("[Link]");

// 2. Establish the connection

Connection con = [Link](url, username,


password);

// 3. Create a SELECT query

String query = "SELECT id, name FROM student";


// 4. Create statement object

Statement stmt = [Link]();

// 5. Execute the query

ResultSet rs = [Link](query);

// 6. Process the result

while ([Link]()) {

int id = [Link]("id");

String name = [Link]("name");

[Link](id + " " + name );

// 7. Close the connection

[Link]();

} catch (Exception e) {

[Link]("Error : " + [Link]());

}
OutPut:
2. A Program to Update Custoer Information.

package updatedemo;

import [Link].*;

public class UpdateDemo {

public static void main(String[] args) {

String url = "jdbc:mysql://localhost:3306/practical?


useSSL=false&allowPublicKeyRetrieval=true";

String username = "root";

String password = "ab3022";

try {

[Link]("[Link]");

Connection con = [Link](url, username,


password);

String query = "UPDATE customers SET name = ?, city = ? WHERE id = ?";

PreparedStatement pst = [Link](query);

[Link](1, "Amit Sharma");

[Link](2, "Mumbai");

[Link](3, 1);

int rows = [Link]();

if (rows > 0) {

[Link]("Customer information updated successfully!");

} else {

[Link]("No customer found with the given ID.");

}
[Link]();

} catch (Exception e) {

[Link]("Error: " + [Link]());

OutPut:
SERVLETS

1. Write a Java Program to simple servlet that just generates


plain text.

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@WebServlet("/PlainTextServlet")

public class PlainTextServlet extends HttpServlet {

@Override

protected void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {


[Link]("text/plain");

PrintWriter out = [Link]();

[Link]("Hello, this is a Simple Plain Text Servlet!");

[Link]("Current Server Time: " + new [Link]());

OUTPUT:
[Link] a Java program that displays the cookie id.
package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@WebServlet("/displayCookie")

public class DisplayCookieServlet extends HttpServlet {

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse


response)

throws ServletException, IOException {

[Link]("text/html");

PrintWriter out = [Link]();


[Link]("<html><body>");
[Link]("<h3>Cookie Details:</h3>");

Cookie[] cookies = [Link](); // get all cookies

if (cookies != null) {
for (Cookie c : cookies) {
[Link]("Cookie Name: " + [Link]() + "<br>");
[Link]("Cookie Value (ID): " + [Link]() + "<br><br>");
}
} else {
[Link]("No Cookies Found!");
}

[Link]("</body></html>");
}
}

OUTPUT:
JAVA SERVER PAGES

1. Write a Java program for basic arithmetic functions.

<html>
<head>
<title>Arithmetic Operations</title>
</head>
<body>

<%
int a = 20;
int b = 10;

[Link]("Addition = " + (a + b) + "<br>");


[Link]("Subtraction = " + (a - b) + "<br>");
[Link]("Multiplication = " + (a * b) + "<br>");
[Link]("Division = " + (a / b) + "<br>");
%>

</body>
</html>

OUTPUT:
[Link] a Java program to display a String.

<html>

<head>

<title>Display String</title>

</head>

<body>

<%

String msg = "Welcome to Java Server Pages";

[Link](msg);

%>

</body>

</html>

OUTPUT:
[Link] a java Program to create check boxes.

<html>

<head>

<title>Checkbox Example</title>

</head>

<body>

<form>

<h3>Select Your Subjects:</h3>

<input type="checkbox" name="subject" value="Java"> Java <br>

<input type="checkbox" name="subject" value="Python"> Python


<br>

<input type="checkbox" name="subject" value="Web"> Web


Development <br>

</form>

</body>

</html>

OUTPUT:
JQUERY

[Link] a java program to implement the show() method & hide()


method to toggle the element to display.

<!DOCTYPE html>

<html>

<head>

<title>Show and Hide Two Boxes</title>

<script
src="[Link]

<style>

.box {

width: 200px;

height: 100px;

margin-top: 10px;

padding: 10px;

color: white;

display: none; /* Initially hidden */

#box1 { background-color: lightblue; }

#box2 { background-color: lightgreen; }

button { margin-right: 5px; margin-top: 10px; }

</style>
</head>

<body>

<h2>Box 1</h2>

<button id="showBox1">Show Box 1</button>

<button id="hideBox1">Hide Box 1</button>

<div id="box1" class="box">

This is Box 1

</div>

<h2>Box 2</h2>

<button id="showBox2">Show Box 2</button>

<button id="hideBox2">Hide Box 2</button>

<div id="box2" class="box">

This is Box 2

</div>

<script>

$(document).ready(function(){

// Box 1 controls

$("#showBox1").click(function(){
$("#box1").show(); // Show Box 1

});

$("#hideBox1").click(function(){

$("#box1").hide(); // Hide Box 1

});

// Box 2 controls

$("#showBox2").click(function(){

$("#box2").show(); // Show Box 2

});

$("#hideBox2").click(function(){

$("#box2").hide(); // Hide Box 2

});

});

</script>

</body>

</html>

OUTPUT:
jQuery Form Validation

2. Write a jQuery program to validate that a username field is not


empty before submitting a form.

 If empty → show error message below the textbox.


 If filled → allow form submission.

<!DOCTYPE html>

<html>

<head>

<title>Username Validation Example</title>

<script
src="[Link]

<style>

.error {

color: red;

font-size: 14px;

</style>

</head>

<body>

<h2>Username Validation Form</h2>


<form id="myForm">

<label for="username">Username:</label><br>

<input type="text" id="username" name="username"><br>

<span class="error" id="usernameError"></span><br><br>

<input type="submit" value="Submit">

</form>

<script>

$(document).ready(function() {

$("#myForm").submit(function(e) {

// Get the value of the username field

var username = $("#username").val().trim();

// Check if the username is empty

if(username === "") {

[Link](); // Prevent form submission

$("#usernameError").text("Username cannot be empty!");

} else {

$("#usernameError").text(""); // Clear any previous error

// Form will submit

}
});

});

</script>

</body>

</html>

Output:
jQuery Events

3. Create a webpage where an alert message displays whenever the


user hovers over a specific div.
Event to use:

 mouseenter() or hover()

<!DOCTYPE html>

<html>

<head>

<title>Hover Event Example</title>

<script
src="[Link]

<style>

#myDiv {

width: 200px;

height: 100px;

background-color: yellow;

text-align: center;

line-height: 100px;

font-weight: bold;

</style>
</head>

<body>

<div id="myDiv">

Hover over this box

</div>

<script>

$(document).ready(function(){

// Using hover() for mouse enter and mouse leave

$("#myDiv").hover(

function() {

// Mouse enter function

alert("Mouse entered the div!");

},

function() {

// Mouse leave function (optional)

[Link]("Mouse left the div.");

);

});
</script>

</body>

</html>

OUTPUT:
Spring Framework

[Link] a Spring program to demonstrate Dependency Injection


using XML configuration.

Create two beans: Student and Address, then inject


Address into Student.

package [Link];
public class Student {
private String name;
private Address address;

// Setter for DI
public void setName(String name) {
[Link] = name;
}

public void setAddress(Address address) {


[Link] = address;
}

public void display() {


[Link]("Student Name: " + name);
[Link]("Student Address: " + address);
}
}

package [Link];

public class Address {


private String city;
private String state;

// Setters for DI
public void setCity(String city) {
[Link] = city;
}

public void setState(String state) {


[Link] = state;
}

@Override
public String toString() {
return city + ", " + state;
}
}
package [Link];

import [Link];
import [Link];

public class MainApp {


public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("[Link]");
Student student = (Student) [Link]("student");
[Link]();
}
}

<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]

<bean id="address" class="[Link]">


<property name="city" value="Mumbai"/>
<property name="state" value="Maharashtra"/>
</bean>

<bean id="student" class="[Link]">


<property name="name" value="Rutuja"/>
<property name="address" ref="address"/>
</bean>
</beans>

OUTPUT:
2. Create a Spring application using Annotation-based configuration
to manage employee details.
Use @Component, @Autowired, @Configuration, and
@Bean.
package [Link];

import [Link];
import [Link];

@Component // marks this class as a Spring bean


public class Employee {
private String name;
private int age;
private Department department;

public String getName() {


return name;
}
public void setName(String name) {
[Link] = name;
}

public int getAge() {


return age;
}
public void setAge(int age) {
[Link] = age;
}

public Department getDepartment() {


return department;
}

@Autowired // Spring will automatically inject the Department bean


public void setDepartment(Department department) {
[Link] = department;
}
}

package [Link];

import [Link];

@Component // marks this class as a Spring bean


public class Department {
private String deptName;

public String getDeptName() {


return deptName;
}
public void setDeptName(String deptName) {
[Link] = deptName;
}
}

package [Link];

import [Link];
import [Link];

@Configuration // marks this class as a configuration for Spring


public class AppConfig {

@Bean
public Employee employee() {
Employee emp = new Employee();
[Link]("Rutuja");
[Link](22);
return emp; // Department will be injected automatically by @Autowired
}

@Bean
public Department department() {
Department dept = new Department();
[Link]("IT");
return dept;
}
}

package [Link];

import [Link];
import [Link];

public class MainApp {


public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext([Link]);

Employee emp = [Link]([Link]);

[Link]("Employee Name: " + [Link]());


[Link]("Employee Age: " + [Link]());
[Link]("Employee Department: " + [Link]().getDeptName());
}
}

OUTPUT:
3. Write a Spring program to display the lifecycle of a bean.
Use InitializingBean, DisposableBean, or annotations like
@PostConstruct and @PreDestroy.

package [Link];

import [Link];
import [Link];

public class Employee implements InitializingBean, DisposableBean {

private String name;

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

// Called after properties are set


@Override
public void afterPropertiesSet() throws Exception {
[Link]("InitializingBean: afterPropertiesSet() called - Bean is initialized");
}

// Called before bean is destroyed


@Override
public void destroy() throws Exception {
[Link]("DisposableBean: destroy() called - Bean is destroyed");
}

// Custom init method


public void customInit() {
[Link]("Custom init method called");
}

// Custom destroy method


public void customDestroy() {
[Link]("Custom destroy method called");
}
}

package [Link];

import [Link];
import [Link];

public class Department {

private String deptName;


public String getDeptName() {
return deptName;
}

public void setDeptName(String deptName) {


[Link] = deptName;
}

@PostConstruct
public void init() {
[Link]("@PostConstruct: Department bean is initialized");
}

@PreDestroy
public void cleanup() {
[Link]("@PreDestroy: Department bean is destroyed");
}
}

package [Link];

import [Link];

public class MainApp {


public static void main(String[] args) {
[Link]("Starting Spring context...");

// Load Spring context from [Link]


ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("[Link]");

// Get Employee bean


Employee emp = (Employee) [Link]("employee");
[Link]("Employee Name: " + [Link]());

// Get Department bean


Department dept = (Department) [Link]("department");
[Link]("IT");
[Link]("Department Name: " + [Link]());

// Close context to trigger destroy methods


[Link]();
[Link]("Spring context closed.");
}
}

<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]

<!-- Employee bean using InitializingBean/DisposableBean -->


<bean id="employee" class="[Link]"
init-method="customInit" destroy-method="customDestroy">
<property name="name" value="Rutuja"/>
</bean>

<!-- Department bean using @PostConstruct/@PreDestroy -->


<bean id="department" class="[Link]"/>
</beans>

Output:
4. Create a Spring application to demonstrate constructor vs setter
injection.

Show both methods with two separate beans.

package [Link];

public class Customer {


private String name;
private String email;

// Constructor injection
public Customer(String name, String email) {
[Link] = name;
[Link] = email;
}

public void displayCustomer() {


[Link]("Customer Name: " + name);
[Link]("Customer Email: " + email);
}
}

package [Link];

public class Order {


private int orderId;
private String product;

public int getOrderId() {


return orderId;
}

public void setOrderId(int orderId) {


[Link] = orderId;
}

public String getProduct() {


return product;
}

public void setProduct(String product) {


[Link] = product;
}

public void displayOrder() {


[Link]("Order ID: " + orderId);
[Link]("Product: " + product);
}
}

package [Link];

import [Link];
import [Link];

public class MainApp {


public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("[Link]");

// Constructor injection
Customer customer = (Customer) [Link]("customer");
[Link]();

[Link]("-----------------------");

// Setter injection
Order order = (Order) [Link]("order");
[Link]();
}
}

OUTPUT:
<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]

<!-- Constructor injection -->


<bean id="customer" class="[Link]">
<constructor-arg value="Rutuja"/>
<constructor-arg value="rutuja@[Link]"/>
</bean>

<!-- Setter injection -->


<bean id="order" class="[Link]">
<property name="orderId" value="101"/>
<property name="product" value="Laptop"/>
</bean>

</beans>

You might also like