0% found this document useful (0 votes)
4 views56 pages

Java - 2520

The document consists of practical exercises for an Advanced Java Lab, focusing on Java Generics, List, Set, and Map interfaces, as well as Lambda Expressions. It includes code examples demonstrating the creation and manipulation of generic classes, methods, and various collection types, along with their respective operations. Each section provides clear aims and code snippets to illustrate the concepts being taught.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views56 pages

Java - 2520

The document consists of practical exercises for an Advanced Java Lab, focusing on Java Generics, List, Set, and Map interfaces, as well as Lambda Expressions. It includes code examples demonstrating the creation and manipulation of generic classes, methods, and various collection types, along with their respective operations. Each section provides clear aims and code snippets to illustrate the concepts being taught.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

Practical 1

Java Generics

Generics add stability to your code by making more of your bugs detectable at compile time.
Generics enable types (classes and interfaces) to be parameters when defining classes,
interfaces and methods.

A Generic Type is a generic class or interface that is parameterized over types.

 The most commonly used type parameter names are:


 E – Element
 K - Key
 N - Number
 T - Type
 V – Value

Aim1: Write a Java Program to demonstrate a Generic Class.

class Stack<E>
{
E a[];
int top; Stack()
{

a=(E[])new Object[100]; top=-1;


}
void push(E data)
{
a[++top]=data;
}
E pop()
{
return a[top--];
}
boolean hasElements()
{
return top!=-1;
}

}
class P1A
{
public static void main(String arg[])
{
Stack<Integer> si=new Stack<Integer>(); // creating a Stack that holds a set of Integer
objects

Page 1 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

Stack<Double> sd=new Stack<Double>(); // creating a Stack that holds a set of Double


objects
Stack<Student> ss=new Stack<Student>(); // creating a Stack that holds a set of Student

[Link](10);
[Link](20);
[Link](30);

[Link](1.2);
[Link](2.34);
[Link](56.789);
[Link](0.15);

[Link]( new Student("student1",2) );


[Link]( new Student("student2",3) );
[Link]( new Student("student3",7) );
[Link]( new Student("student4",5) );

[Link]("\nintegers...");
while([Link]())
{
[Link]([Link]());
[Link]([Link]);
}

[Link]("\ndoubles...");
while([Link]())
{

[Link]([Link]());
[Link]([Link]);
}

[Link]("\nstudents...");
while([Link]())
{
[Link]([Link]());
[Link]([Link]());
}
}
}

class Student
{
String name; int standard;
Student(String n,int s)
{
name=n; standard=s;
}

Page 2 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

public String toString()


{

return name+" "+standard;


}
}

Output:

Aim 2: Write a Java Program to demonstrate Generic

Methods

Generic Methods are methods that introduce their own type parameters. This is similar to
declaring a generic type, but the type parameter's scope is limited to the method where it is
declared.

Page 3 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

public class GenericMethod {


public static void main(String args []) {
// TODO code application logic here
Democlass objDemoclass = new Democlass();
objDemoclass.<String>genericMethod("Java lab session");
objDemoclass.<Integer>genericMethod(1);
}
}
class Democlass
{
public <T> void genericMethod(T data)
{
[Link]("Generic method");
[Link]("Data passed"+data);
}
}
Output:

Aim 3: Write a Java Program to demonstrate Wildcards in Java Generics.

[Link] Bounded Wildcard

You can use an upper bounded wildcard to relax the restrictions on a variable. For example,
say you want to write a method that works on List, List, and List; you can achieve this by
using an upper bounded wildcard.

Code:

import [Link].*;
// import [Link];
// import [Link];
/***/
public class UpperBound{
public static void main(String[] args) {
// TODO code application logic here
List<Integer>list1= [Link](3,5,6,8);
[Link]("Total sum is:" + sum(list1));
List<Double> list2 = [Link](3.1,5.1,7.1);

Page 4 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
[Link]("Total sum is:"+sum(list2));
}
private static double sum(List<? extends Number> list)
{
double sum=0.0;
for(Number i : list)
{
sum+=[Link]();
}
return sum;
}}

Output:

[Link] Bounded

Wildcard Lower bounded wildcard restricts the unknown type to be a specific type or a super
type of that type. A lower bounded wildcard is expressed using the wildcard character ('?'),
following by the super keyword, followed by its lower bound:

Code:

import [Link].*;
import [Link];
import [Link];
class LowerBound {
public static void main(String[] args)
{
// Lower Bounded Integer List
List<Integer> list1 = [Link](2, 4, 6, 8);
// Integer list object is being passed
printOnlyIntegerClassorSuperClass(list1);

// Number list
List<Number> list2 = [Link](4, 5, 3, 5,8);
// Integer list object is being passed
printOnlyIntegerClassorSuperClass(list2);
}
public static void printOnlyIntegerClassorSuperClass(
List<? super Integer> list)

Page 5 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
{
[Link](list);
}
}

Output:

[Link] Wildcard

The unbounded wildcard type is specified using the wildcard character (?), for example, List.
This is called a list of unknown type. When the code is using methods in the generic class
that don't depend on the type parameter. For example, [Link] or [Link]. In fact, Class is
so often used because most of the methods in Class do not depend on T.

Code:

import [Link];
import [Link];
import [Link].*;

class UnBounded {
public static void main(String[] args)
{
// Integer List
List<Integer> list1 = [Link](1, 2, 3);
// Double list
List<Double> list2 = [Link](1.1, 2.2, 3.3); printlist(list1);

printlist(list2);
}
private static void printlist(List<?> list)
{
[Link](list);
}
}

Page 6 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

Output:

Page 7 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
Practical 2

Assignments on List Interface

The List interface in Java extends the Collection interface and is part of the [Link]
package. It is used to store ordered collections where duplicates are allowed and elements
can be accessed by their index.
 Maintains insertion order
 Allows duplicate elements
 Supports null elements (implementation dependent)
 Supports bidirectional traversal using ListIterator

Aim1:Write a Java program to create List containing list of items of type String and use
for-each loop to print the items of the list.

Code:
import [Link].*;
public class p3_a{
public static void main(String args[]){
List<String>a1=new ArrayList<>();
[Link]("sakshi");
[Link]("shweta");
[Link]("sharad");
[Link]("bharti");

// for(int i=0; i<[Link]();i++){


// [Link]([Link](i)+" ");
// }
// [Link]();

for(String item:a1){
[Link](item+" ");
}

}
}

Page 8 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
Aim 2: Write a Java program to create List containing list of items and use ListIterator
interface to print items present in the list. Also print the list in reverse / backward
direction.

Code:

import [Link].*;
import [Link];
import [Link];

public class p3_c{


public static void main(String args[])
{
ListIterator<String> iterator=null;
List<String> names=new ArrayList<>();
[Link]("sakshi");
[Link]("shweta");
[Link]("tanaya");

iterator=[Link]();
[Link]("Travalsal in forward direction");
while([Link]()){
[Link]([Link]());
}

[Link]();
[Link]("Travalsal in backward direction");
while([Link]()){
[Link]([Link]());
}
}
}

Output:

Page 9 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
Practical 3

Set Interface:
In Java, the Set interface is a part of the Java Collection Framework, located in the [Link]
package. It represents a collection of unique elements, meaning it does not allow duplicate
values.
 The set interface does not allow duplicate elements.
 It can contain at most one null value except TreeSet implementation which does
not allow null.
 The set interface provides efficient search, insertion, and deletion operations.

Aim 1 : Write a Java program to create a Set containing list of items of type String and
print the items in the list using Iterator interface. Also print the list in reverse /
backward direction.

Code:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class p4_1
{
public static void main(String[] args)
{
HashSet<Integer> evenNumSet = new LinkedHashSet<>(
[Link](4,16,8,102,24,30,46) );
[Link]("Unsorted Set: " + evenNumSet);

List<Integer> numList = new ArrayList<Integer>(evenNumSet);


[Link](numList);

evenNumSet = new LinkedHashSet<>(numList);


[Link]("Sorted Set:" + evenNumSet);
[Link](numList);
[Link]("Sorted Set In Backward Direction:"+numList);
}
}

Page 10 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

Output :

Aim 2 : Write a Java program using Set interface containing list of items and perform
the following operations:
a. Add items in the set.
b. Insert items of one set in to other set.
c. Remove items from the set
d. Search the specified item in the set

Code:

import [Link].*;
public class p4_2
{
public static void main(String args[])
{
Set<Integer> numSet = new HashSet<Integer>();
[Link](13);
[Link]([Link](new Integer[] {1,6,4,7,3,9,8,2,12,11,20}));
[Link]("Original Set (numSet):" + numSet);
[Link]("\nNumSet Size:" + [Link]());

Set<Integer> oddSet = new HashSet<Integer>();


[Link]([Link](new Integer[] {1, 3, 7, 5, 9}));
[Link]("\nOddSet contents:" + oddSet);
[Link]("\nnumSet contains element 2:" + [Link](3));
[Link]("\nnumSet contains collection oddset:" +
[Link](oddSet));

Set<Integer> set_intersection = new HashSet<Integer>(numSet);


set_intersection.retainAll(oddSet);
[Link]("\nIntersection of the numSet & oddSet:");
[Link](set_intersection);

Set<Integer> set_difference = new HashSet<Integer>(numSet);


set_difference.removeAll(oddSet);
[Link]("Difference of the numSet & oddSet:");
[Link](set_difference);

Page 11 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

Set<Integer> set_union = new HashSet<Integer>(numSet);


set_union.addAll(oddSet);
[Link]("Union of the numSet & oddSet:");
[Link](set_union);
}
}

Output:

Page 12 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
Practical 4

Map Interface:

In Java, the Map Interface is part of the [Link] package and represents a collection of key-
value pairs, where Keys should be unique, but values can be duplicated.
It provides efficient retrieval, insertion, and deletion operations based on keys.
Keys should be unique, but values can be duplicated.
HashMap and LinkedHashMap allow one null key, and TreeMap does NOT allow null keys
(if natural ordering is used).
Use ConcurrentHashMap for thread-safe operations, or [Link]() to
make an existing map synchronized.

Declaration of the Map interface


Public interface Map<K, V>
 K -> Type of keys maintained by the map
 V -> Type of mapped values

Aim 1: Write a Java program using Map interface containing list of items having keys
and associated values and perform the following operations:
a. Add items in the map.
b. Remove items from the map
c. Search specific key from the map
d. Get value of the specified key
e. Insert map elements of one map in to other map.
f. Print all keys and values of the map.

Code:
import [Link].*;

public class MapOperations {


public static void main(String[] args) {
// Create Map
Map<String, String> items = new HashMap<>();

// a. ADD ITEMS
[Link](" a. ADDING ITEMS ");
[Link]("101", "Laptop");
[Link]("102", "Mouse");
[Link]("103", "Keyboard");
[Link]("After adding: " + items);

// b. REMOVE ITEM
[Link](" b. REMOVE ITEM ");
[Link]("102");
[Link]("After removing 102: " + items);

// c. SEARCH KEY
[Link](" c. SEARCH KEY ");
if([Link]("101")) {

Page 13 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
[Link]("Key '101' FOUND");
} else {
[Link]("Key '101' NOT FOUND");
}

// d. GET VALUE
[Link]("d. GET VALUE ");
String value = [Link]("101");
[Link]("Value for key 101: " + value);

// e. INSERT ONE MAP INTO ANOTHER


[Link]("e. INSERT MAP2 INTO MAP1 ");
Map<String, String> map2 = new HashMap<>();
[Link]("104", "Monitor");
[Link]("105", "Printer");

[Link](map2);
[Link]("After putAll(map2): " + items);

// f. PRINT ALL KEYS & VALUES


[Link]("f. ALL KEYS & VALUES");
[Link]("KEYS: ");
for(String key : [Link]()) {
[Link](key + " ");
}
[Link]("VALUES: ");
for(String val : [Link]()) {
[Link](val + " ");
}
[Link]("ALL ENTRIES: " +items);
}
}

Page 14 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
Output:

Page 15 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
Practical 5

Assignments on Lambda Expression

Java lambda expressions, introduced in Java 8, allow developers to write concise,


functional-style code by representing anonymous functions. They enable passing code as
parameters or assigning it to variables, resulting in cleaner and more readable programs.
 Lambda expressions implement a functional interface (An interface with only one
abstract function)
 Enable passing code as data (method arguments).
 Allow defining behavior without creating separate classes.

1. WAP using Lambda Expression to print “Hello World”.

Code:

interface MyLambda {
void display();
}

public class HelloWorldLambda {


public static void main(String[] args) {

MyLambda msg = () -> [Link]("Hello World");

[Link]();
}
}

Output:

2. Write a Java program using Lambda Expression to concatenate two strings.

Code:

// Functional Interface
@FunctionalInterface
interface StringConcat {
String concat(String a, String b);
}

Page 16 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

public class LambdaConcatenate {


public static void main(String[] args) {

// Lambda Expression
StringConcat sc = (s1, s2) -> s1 + s2;

// Calling the lambda


String result = [Link]("Hello ", "Sakshi");

[Link]("Concatenated String: " + result);


}
}

Output:

3. WAP using Lambda Expression with single parameters.

Code:

import [Link];

public class Main {


interface Print {
void show(int x);
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

[Link]("Enter a number: ");


int n = [Link]();

Print p = x -> [Link]("You entered: " + x);


[Link](n);
}
}

Page 17 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

Output:

4. Write a Java program using Lambda Expression with multiple parameters to add
two numbers.

Code:

import [Link];

public class Main2 {


interface Add {
int sum(int a, int b);
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

[Link]("Enter first number: ");


int a = [Link]();

[Link]("Enter second number: ");


int b = [Link]();

Add add = (x, y) -> x + y;


[Link]("Sum = " + [Link](a, b));
}
}

Output:

Page 18 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
5. Write a Java program using Lambda Expression to calculate the following:

[Link] Fahrenheit to Celsius

Code:

import [Link];

public class Main3 {


interface Temp {
double convert(double f);
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

[Link]("Enter temperature in Fahrenheit: ");


double f = [Link]();

Temp t = x -> (x - 32) * 5 / 9;


[Link]("Celsius = " + [Link](f));
}
}

Output:

[Link] Kilometers to Miles.

Code:

import [Link];

public class Main4 {


interface Distance {
double convert(double km);
}

Page 19 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter distance in kilometers: ");


double km = [Link]();

Distance d = k -> k * 0.621371;


[Link]("Miles = " + [Link](km));
}
}

Output:

6. Write a Java program using Lambda Expression with or without return keyword.

Code:

import [Link];

public class Main5 {


interface Square {
int calculate(int x);
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

[Link]("Enter number: ");


int n = [Link]();

// Without return
Square s1 = x -> x * x;
[Link]("Square (without return): " + [Link](n));

// With return
Square s2 = (x) -> {

Page 20 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
return x * x;
};
[Link]("Square (with return): " + [Link](n));
}
}

Output:

Page 21 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
Practical 6

Aim 1 : To design a JSP page to display and process a user registration form.

Code:

<%@ page language="java" contentType="text/html; charset=UTF-8" %>


<html>
<head>
<title>Registration Form</title>
</head>
<body>
<h2>Student Registration Form</h2>

<form method="post">
Name: <input type="text" name="name"><br><br>
Email: <input type="email" name="email"><br><br>
Password: <input type="password" name="password"><br><br>
Gender:
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female<br><br>
Course:
<select name="course">
<option>Java</option>
<option>Web Development</option>
<option>Python</option>
</select><br><br>
<input type="submit" value="Register">
</form>

<%
if([Link]().equalsIgnoreCase("post")) {
%>
<h3>Registration Details</h3>
Name: <%= [Link]("name") %><br>
Email: <%= [Link]("email") %><br>
Gender: <%= [Link]("gender") %><br>
Course: <%= [Link]("course") %>
<%
}
%>
</body>
</html>

Page 22 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

Output:

Page 23 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

Aim 2 : To design a JSP-based Loan Calculator that displays EMI, interest paid, and
remaining balance.

Code:

<%@ page language="java" %>


<html>
<head>
<title>Loan Calculator</title>
<style>
body {
font-family: Arial;
margin: 40px;
}
h2 {
color: #3b5ba9;
}
table {
border-collapse: collapse;
width: 70%;
}
th, td {
border: 1px solid #999;
padding: 6px;
text-align: center;
}
th {
background-color: #f2f2f2;
}
</style>
</head>

<body>

<h2>Loan Calculator</h2>

<form method="post">
Principal Amount:
<input type="number" name="principal" required><br><br>

Time (Years):
<input type="number" name="years" min="1" max="30" required><br><br>

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


</form>

<hr>

Page 24 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

<%
String pVal = [Link]("principal");
String yVal = [Link]("years");

if(pVal != null && yVal != null) {

double principal = [Link](pVal);


int years = [Link](yVal);
double rate = 0;

/* Interest rate selection as per AIM */


if(years >= 1 && years <= 7) {
rate = 5.35;
} else if(years >= 8 && years <= 15) {
rate = 5.5;
} else if(years >= 16 && years <= 30) {
rate = 5.75;
}

int months = years * 12;


double monthlyRate = rate / (12 * 100);

double emi = (principal * monthlyRate * [Link](1 + monthlyRate, months))


/ ([Link](1 + monthlyRate, months) - 1);

[Link]("<h3>Loan Details</h3>");
[Link]("Interest Rate: <b>" + rate + "%</b><br>");
[Link]("Monthly EMI: <b>" + [Link](\"%.2f\", emi) +
"</b><br><br>");

[Link]("<table>");
[Link]("<tr><th>Month</th><th>Interest Paid</th><th>Remaining
Balance</th></tr>");

double balance = principal;

for(int i = 1; i <= months; i++) {


double interest = balance * monthlyRate;
balance = balance + interest - emi;

[Link]("<tr>");
[Link]("<td>" + i + "</td>");
[Link]("<td>" + [Link](\"%.2f\", interest) + "</td>");
[Link]("<td>" + [Link](\"%.2f\", balance) + "</td>");
[Link]("</tr>");
}

Page 25 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
[Link]("</table>");
}
%>

</body>
</html>

Output:
a) 1 to 7 year at 5.35%
b) 8 to 15 year at 5.5%
c) c) 16 to 30 year at 5.75%

Page 26 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
Aim 3 : To demonstrate JSP Declaration, Scriptlet, Directive, Expression, Header, and
Footer.

Code:

Header :
<h2>Welcome to JSP Demo</h2>
<hr>

Footer :
<hr>
<p>&copy; 2025 JSP Lab</p>

Main File for demonstration.


<%@ page language="java" %>
<%@ include file="[Link]" %>

<%! int count = 10; %> <!-- Declaration -->

<%
int a = 5, b = 6;
int sum = a + b;
%> <!-- Scriptlet -->

<p>Sum is: <%= sum %></p> <!-- Expression -->

<p>Count Value: <%= count %></p>

<%@ include file="[Link]" %>

Page 27 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

Output:

Page 28 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

Aim 4 : Database Application

Code:
<%@ page import="[Link].*" %>
<html>
<head>
<title>Student Database Application</title>
<style>
body {
font-family: Arial;
margin: 40px;
}
h1 {
color: #3b5ba9;
}
table {
border-collapse: collapse;
width: 60%;
}
th, td {
border: 1px solid #999;
padding: 8px;
text-align: center;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>

<h1>Student Database Application</h1>


<hr>

<h3>Enter Student Details</h3>

<form method="post">
Name:
<input type="text" name="name" required>
<br><br>
Course:
<input type="text" name="course" required>
<br><br>
<input type="submit" value="Save">
</form>

Page 29 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
<hr>

<%
String name = [Link]("name");
String course = [Link]("course");

/* JDBC Connection */
[Link]("[Link]");
Connection con = [Link](
"jdbc:mysql://localhost:3306/college",
"root",
""
);

/* Insert Record */
if(name != null && course != null){
PreparedStatement ps = [Link](
"INSERT INTO student(name, course) VALUES (?, ?)"
);
[Link](1, name);
[Link](2, course);
[Link]();
}

/* Display Records */
Statement st = [Link]();
ResultSet rs = [Link]("SELECT * FROM student");

[Link]("<h3>Student List</h3>");
[Link]("<table>");
[Link]("<tr><th>ID</th><th>Name</th><th>Course</th></tr>");

while([Link]()){
[Link]("<tr>");
[Link]("<td>" + [Link]("id") + "</td>");
[Link]("<td>" + [Link]("name") + "</td>");
[Link]("<td>" + [Link]("course") + "</td>");
[Link]("</tr>");
}

[Link]("</table>");
[Link]();
%>

</body>
</html>

Page 30 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

Output:

Page 31 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
Practical 7

Aim 1 :To write a simple program using Spring Framework to print “Hello World”
by configuring and accessing a Spring bean through the IoC container.

Code:

[Link]

public class HelloWorld {

public void display() {

[Link]("Hello World");

[Link]

<beans xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="

[Link]

[Link]

<bean id="hello" class="HelloWorld"/>

</beans>

Page 32 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
[Link]

import [Link];

import [Link];

public class MainApp {

public static void main(String[] args) {

ApplicationContext context =

new ClassPathXmlApplicationContext("[Link]");

HelloWorld h = (HelloWorld) [Link]("hello");

[Link]();

Output:

Page 33 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
Aim 2 :To write a program using Spring Framework to demonstrate Dependency
Injection through Setter method using XML-based configuration.

Code:

[Link]

public class Student {

private String name;

public void setName(String name) {

[Link] = name;

public void display() {

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

[Link]

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

<bean id="student" class="Student">


<property name="name" value="Alice"/>
</bean>

</beans>

Page 34 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
[Link]

import [Link];
import [Link];

public class MainApp {


public static void main(String[] args) {

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

Student s = (Student) [Link]("student");


[Link]();
}
}

Output:

Page 35 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

Aim 3 :To write a program using Spring Framework to demonstrate Dependency


Injection through Constructor using XML configuration.

Code :

[Link]

public class Employee {

private String name;

public Employee(String name) {

[Link] = name;

public void show() {

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

[Link]

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

<bean id="employee" class="Employee">


<constructor-arg value="Bob"/>
</bean>

</beans>

Page 36 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
[Link]

import [Link];

import [Link];

public class MainApp {

public static void main(String[] args) {

ApplicationContext context =

new ClassPathXmlApplicationContext("[Link]");

Employee e = (Employee) [Link]("employee");

[Link]();

Output :

Page 37 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
Aim 4 :To write a program using Spring Framework to demonstrate Autowiring of
dependent objects using XML configuration.

Code:

[Link]

public class Address {


public void display() {
[Link]("Address: Bangalore");
}
}

[Link]

public class Employee {


private Address address;

public void setAddress(Address address) {


[Link] = address;
}

public void show() {


[Link]("Employee Details");
[Link]();
}
}

[Link]

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

<bean id="address" class="Address"/>

<bean id="employeeAuto" class="Employee" autowire="byType"/>

</beans>

[Link]

import [Link];
import [Link];

public class MainApp {

Page 38 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
public static void main(String[] args) {

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

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


[Link]();
}
}

Output:

Page 39 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
Practical 8

Aim 1: To write a program to demonstrate Spring AOP – Before Advice.

Code:

[Link] (TARGET CLASS)

public class Employee {


private Address address;

public Employee() {
}

public void setAddress(Address var1) {


[Link] = var1;
}

public void show() {


[Link]("Employee Details");
[Link]();
}
}

[Link] (ASPECT CLASS)

public class LoggingAspect {


public void beforeAdvice() {
[Link]("Before Advice: Method is about to execute");
}
}

Page 40 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

[Link]

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

<!-- Enable AOP -->


<aop:aspectj-autoproxy/>

<!-- Beans -->


<bean id="emp" class="Employee"/>
<bean id="aspect" class="LoggingAspect"/>

<!-- AOP Configuration -->


<aop:config>
<aop:aspect ref="aspect">
<aop:before method="beforeAdvice"
pointcut="execution(* [Link](..))"/>
</aop:aspect>
</aop:config>

</beans>

[Link]

import [Link];
import [Link];

public class MainApp {


public static void main(String[] args) {

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

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


[Link]();
}
}

Page 41 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

Output:

Aim 2: To write a program to demonstrate Spring AOP – After Advice.

Code:

[Link] (TARGET CLASS)

public class Employee {


private Address address;

public Employee() {
}

public void setAddress(Address var1) {


[Link] = var1;
}

public void show() {


[Link]("Employee Details");
[Link]();
}
}

[Link] (ASPECT CLASS)

public class LoggingAspect {


public void afterAdvice() {
[Link]("After Advice: Method execution completed");
}
}

Page 42 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
[Link]

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

<!-- Enable AOP -->


<aop:aspectj-autoproxy/>

<!-- Beans -->


<bean id="emp" class="Employee"/>
<bean id="aspect" class="LoggingAspect"/>

<!-- AOP Configuration -->


<aop:config>
<aop:aspect ref="aspect">
<aop:after method="afterAdvice"
pointcut="execution(* [Link](..))"/>
</aop:aspect>
</aop:config>

</beans>

[Link]

import [Link];
import [Link];

public class MainApp {


public static void main(String[] args) {

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

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


[Link]();
}
}

Page 43 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

Output:

Aim 3: To write a program to demonstrate Spring AOP – Around Advice.

Code:

[Link] (TARGET CLASS)

public class Employee {


private Address address;

public Employee() {
}

public void setAddress(Address var1) {


[Link] = var1;
}

public void show() {


[Link]("Employee Details");
[Link]();
}
}

[Link] (ASPECT CLASS)

import [Link];

public class LoggingAspect {


public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
[Link]("Around Advice: Before method");
Object obj = [Link]();
[Link]("Around Advice: After method");
return obj;
}
}

Page 44 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
[Link]

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

<!-- Enable AOP -->


<aop:aspectj-autoproxy/>

<!-- Beans -->


<bean id="emp" class="Employee"/>
<bean id="aspect" class="LoggingAspect"/>

<!-- AOP Configuration -->


<aop:config>
<aop:aspect ref="aspect">
<aop:around method="aroundAdvice"
pointcut="execution(* [Link](..))"/>

</aop:aspect>
</aop:config>

</beans>

[Link]

import [Link];
import [Link];

public class MainApp {


public static void main(String[] args) {

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

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


[Link]();
}
}

Page 45 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

Output:

Aim 4 : To write a program to demonstrate Spring AOP – After Returning Advice.

Code:

[Link] (TARGET CLASS)

public class Employee {


public String work() {
[Link]("Employee is working");
return "SUCCESS";
}
}

[Link] (ASPECT CLASS)

public class LoggingAspect {


public void afterReturningAdvice(Object result) {
[Link]("After Returning Advice: Result = " + result);
}
}

[Link]

<beans xmlns="[Link]
xmlns:xsi="[Link]
xmlns:aop="[Link]
xsi:schemaLocation="
[Link]
[Link]
[Link]
[Link]
<!-- Enable AOP -->
<aop:aspectj-autoproxy/>

<!-- Beans -->


<bean id="emp" class="Employee"/>
<bean id="aspect" class="LoggingAspect"/>

Page 46 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

<!-- AOP Configuration -->


<aop:config>
<aop:aspect ref="aspect">
<aop:after-returning method="afterReturningAdvice"
returning="result"
pointcut="execution(* [Link](..))"/>
</aop:aspect>
</aop:config>

</beans>

[Link]

import [Link];
import [Link];

public class MainApp {


public static void main(String[] args) {

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

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


[Link]();
}
}

Output:

Page 47 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
Aim 5 : To write a program to demonstrate Spring AOP – After Returning Advice.

Code:

[Link] (TARGET CLASS)

public class Employee {


public void work() {
[Link]("Employee is working");
throw new RuntimeException("Error occurred");
}
}

[Link] (ASPECT CLASS)

public class LoggingAspect {


public void afterThrowingAdvice(Exception e) {
[Link]("After Throwing Advice: " + [Link]());
}
}

[Link]

<beans xmlns="[Link]
xmlns:xsi="[Link]
xmlns:aop="[Link]
xsi:schemaLocation="
[Link]
[Link]
[Link]
[Link]
<!-- Enable AOP -->
<aop:aspectj-autoproxy/>
<!-- Beans -->
<bean id="emp" class="Employee"/>
<bean id="aspect" class="LoggingAspect"/>

<!-- AOP Configuration -->


<aop:config>
<aop:aspect ref="aspect">
<aop:after-throwing method="afterThrowingAdvice"
throwing="e"
pointcut="execution(* [Link](..))"/>
</aop:aspect>
</aop:config>
</beans>

Page 48 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

[Link]

import [Link];
import [Link];

public class MainApp {


public static void main(String[] args) {

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

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


[Link]();
}
}

Output:

Page 49 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
Aim 5 : To write a program to demonstrate Pointcuts in Spring AOP.

Code:

[Link] (TARGET CLASS)

public class Employee {


public void work() {
[Link]("Employee is working");
}
public void report() {
[Link]("Employee is reporting");
}
}

[Link] (ASPECT CLASS)

public class LoggingAspect {


public void log() {
[Link]("Pointcut applied");
}
}

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

<!-- Enable AOP -->


<aop:aspectj-autoproxy/>

<!-- Beans -->


<bean id="emp" class="Employee"/>
<bean id="aspect" class="LoggingAspect"/>

<!-- AOP Configuration -->


<aop:config>
<aop:aspect ref="aspect">
<aop:pointcut id="allMethods"
expression="execution(* Employee.*(..))"/>
<aop:before method="log" pointcut-ref="allMethods"/>
</aop:aspect>
</aop:config>
</beans>

Page 50 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

[Link]

import [Link];
import [Link];

public class MainApp {


public static void main(String[] args) {

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

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


[Link]();
}
}

Output:

Page 51 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
Practical 9

Aim : To write a program using Spring JDBC to perform database operations (Insert
and Display records).

Code :

[Link]
import [Link];

public class StudentDAO {

private JdbcTemplate jdbcTemplate;

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {


[Link] = jdbcTemplate;
}

// Insert Record
public void insert(String name, String course) {
String sql = "INSERT INTO student(name, course) VALUES (?, ?)";
[Link](sql, name, course);
[Link]("Record inserted successfully");
}

// Display Records
public void display() {
[Link](
"SELECT * FROM student",
rs -> {
[Link](
[Link]("id") + " " +
[Link]("name") + " " +
[Link]("course")
);
}
);
}
}

Page 52 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
[Link]

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

<!-- DataSource -->


<bean id="dataSource"
class="[Link]">
<property name="driverClassName" value="[Link]"/>
<property name="url" value="jdbc:mysql://localhost:3306/college"/>
<property name="username" value="root"/>
<property name="password" value="root123"/>
</bean>
<!-- JdbcTemplate -->
<bean id="jdbcTemplate"
class="[Link]">
<property name="dataSource" ref="dataSource"/>
</bean>

<!-- DAO -->


<bean id="studentDAO" class="StudentDAO">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
</beans>

[Link]

import [Link];
import [Link];

public class MainApp {


public static void main(String[] args) {

ApplicationContext ctx =
new ClassPathXmlApplicationContext("[Link]");

StudentDAO dao = (StudentDAO) [Link]("studentDAO");

[Link]("Alice", "BCA");
[Link]("Bob", "BSc");

[Link]("Student Records:");
[Link]();
}
}

Page 53 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
Output :

Page 54 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520
Practical 10

Aim : To write a program to create a simple Spring Boot application that prints a
message using RESTful Web Service.

Code :

[Link]

package [Link].chapter10;

import [Link];
import [Link];

@SpringBootApplication
public class Chapter10Application {

public static void main(String[] args) {


[Link]([Link], args);
}
}

[Link]

package [Link].chapter10;

import [Link];
import [Link];

@RestController
public class HelloController {

@GetMapping("/hello")
public String message() {
return "Hello, Welcome to Spring Boot!";
}
}

Output :

Page 55 of 56
SSCMR

MCA Department MCA L12 Advanced Java Lab Roll No: 2520

Page 56 of 56

You might also like