0% found this document useful (0 votes)
2 views25 pages

Advanced Java Practicals

The document outlines practical experiments for MCA students at the University of Mumbai, focusing on Java programming, JSP, and Spring Framework applications. Each experiment includes a theoretical explanation, code examples, and conclusions about the concepts demonstrated, such as Java Generics, ListIterator, Map interface, Lambda expressions, and database interactions using JDBC. The document serves as a certification template for students who complete these practicals satisfactorily.

Uploaded by

vcst Exam
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)
2 views25 pages

Advanced Java Practicals

The document outlines practical experiments for MCA students at the University of Mumbai, focusing on Java programming, JSP, and Spring Framework applications. Each experiment includes a theoretical explanation, code examples, and conclusions about the concepts demonstrated, such as Java Generics, ListIterator, Map interface, Lambda expressions, and database interactions using JDBC. The document serves as a certification template for students who complete these practicals satisfactorily.

Uploaded by

vcst Exam
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

University of Mumbai

Center for Distance & Online Education (CDOE)


Dr. Shankardayal Sharma bhavan, Vidyanagari, Santacruz(E)

PCP CENTER:

Vidyavardhini's College of Engineering and Technology, Vasai (West)

Certificate
This is to certify that Mr/Ms. ___________________________________
of MCA Semester _______ has completed the specified Practical in the
subject of __________________________________________________
satisfactorily within this institute as laid down by University of Mumbai
during the academic year 20___ to 20___.

Faculty In-charge PCP Coordinator

Examiner
INDEX

Sr. No. Practical Name

1 Write a Java Program to demonstrate Wildcards in Java Generics.

Write a Java program to create List containing list of items and use
2 ListIterator interface to print items present in the list. Also print the
list in reverse / backward direction.

Write a Java program to create a Set containing list of items of type


3 String and print the items in the list using Iterator interface. Also print
the list in reverse / backward direction.

Write a Java program using Map interface containing list of items


having keys and associated values and perform the following
operations:
4
a. Add items in the map.
b. Remove items from the map
c. Search specific key from the map

Write a Java program using Lambda Expression with multiple


5
parameters to add two numbers

Write a JSP page to display the Registration form (Make your own
6
assumptions)

Write a JSP program to add, delete and display the records from
7
StudentMaster (RollNo, Name, Semester, Course) table.

8 Write a program to print “Hello World” using spring framework.

9 Write a program to demonstrate Autowiring

10 Write a program to demonstrate Spring AOP – before advice.

Write a program to insert, update and delete records from the given
11
table.

Write a program to create a simple Spring Boot application that prints


12
a message.
Experiment No. 1
Aim: Write a Java Program to demonstrate Wildcards in Java Generics.

Theory: Java Generics allow classes, interfaces, and methods to operate on objects
of different types while providing compile-time type safety.
However, sometimes strict type parameters reduce flexibility. To overcome this,
wildcards are used.
A wildcard in Java is represented by the symbol ? and is mainly used when the exact
type parameter is unknown or irrelevant.
There are three types of wildcards in Java Generics:

1. Unbounded Wildcard (?)


 Represents any type.
 Used when the method can work with all object types.

Example:
List<?> list;

2. Upper Bounded Wildcard (? extends Type)


 Restricts the wildcard to a specific type or its subclasses.
 Used mainly for reading data.

Example:
List<? extends Number> list;

3. Lower Bounded Wildcard (? super Type)


 Restricts the wildcard to a specific type or its superclasses.
 Used mainly for adding data.

Example:
List<? super Integer> list;

Wildcards improve code reusability, readability, and flexibility, especially when


working with collections.

Code:
import [Link].*;

public class WildcardDemo {


// Upper Bounded Wildcard (Accepts Number and its subclasses)
public static void drawShapes(List<? extends Number> list) {
for (Number n : list) {
[Link]("Processing Number: " + n);
}
}
public static void main(String[] args) {
List<Integer> intList = [Link](10, 20, 30);
List<Double> doubleList = [Link](10.5, 20.5);

[Link]("Integer List:");
drawShapes(intList);
[Link]("\nDouble List:");
drawShapes(doubleList);
}
}

Output:

Conclusion: Wildcards in Java Generics allow methods to handle different data types
safely and efficiently. They help overcome the limitations of strict generic type
binding and make programs more flexible. By using unbounded, upper bounded, and
lower bounded wildcards, Java ensures type safety while supporting polymorphism
in generic programming.
Experiment No. 2
Aim: To write a Java program that creates a List of items and uses the ListIterator
interface to display the elements in forward and reverse (backward) direction.

Theory: In Java, the List interface is a part of the Collection Framework and allows
storing ordered elements, including duplicate values.
The ListIterator interface is used to traverse the elements of a list in both forward
and backward directions.
It provides methods such as:

 hasNext() – checks if next element exist.


 next() – returns next element
 hasPrevious() – checks if previous element exists
 previous() – returns previous element

Unlike Iterator, ListIterator supports bidirectional traversal, making it suitable for


printing lists in reverse order.

Code:
import [Link].*;

public class ListIteratorDemo {


public static void main(String[] args) {
List<String> items = new ArrayList<>([Link]("Java", "Python", "C++",
"Kotlin"));

ListIterator<String> it = [Link]();

[Link]("Forward Direction:");
while ([Link]()) {
[Link]([Link]());
}

[Link]("\nBackward Direction:");
while ([Link]()) {
[Link]([Link]());
}
}
}
Output:

Conclusion: The ListIterator interface allows traversal of a list in both forward and
backward directions. It is more powerful than the Iterator interface and is useful
when bidirectional traversal is required. Thus, ListIterator enhances flexibility while
working with lists in Java.
Experiment No. 3
Aim: To write a Java program that creates a Set of String items, prints the elements
using the Iterator interface, and displays the elements in reverse / backward order.

Theory: In Java, a Set is a part of the Collection Framework that stores unique
elements and does not allow duplicates. Common implementations of Set are
HashSet, LinkedHashSet, and TreeSet.

The Iterator interface is used to traverse elements of a collection in forward


direction only using:

 hasNext()
 next()

 Since Set does not maintain index-based access and Iterator does not support
backward traversal, printing elements in reverse order is achieved by:

1. Converting the Set into a List


2. Using ListIterator to traverse backward

Code:
import [Link].*;

public class SetReverseDemo {


public static void main(String[] args) {
Set<String> set = new HashSet<>([Link]("Red", "Green", "Blue",
"Yellow"));

[Link]("Items using Iterator:");


Iterator<String> it = [Link]();
List<String> tempList = new ArrayList<>();
while ([Link]()) {
String val = [Link]();
[Link](val);
[Link](val);
}

[Link]("\nReverse Direction (via List):");


ListIterator<String> li = [Link]([Link]());
while ([Link]()) {
[Link]([Link]());
}
}
}
Output:

Conclusion: The Iterator interface allows traversal of Set elements only in the
forward direction.
Since a Set does not support backward traversal directly, converting it into a List
enables reverse traversal using ListIterator.
Thus, Java collections provide flexible ways to traverse data while maintaining type
safety and structure.
Experiment No. 4
Aim: To write a Java program using the Map interface to store items as key–value
pairs and perform the following operations:
a) Add items to the map
b) Remove items from the map
c) Search a specific key in the map

Theory: In Java, the Map interface is part of the Collection Framework and is used to
store data in the form of key–value pairs.
Each key in a map is unique, and each key maps to exactly one value.

Common implementations of the Map interface include:

 HashMap – does not maintain order


 LinkedHashMap – maintains insertion order
 TreeMap – stores keys in sorted order

Important Map methods:

put(key, value) – adds items to the map


remove(key) – removes an item using its key
containsKey(key) – searches for a specific key
entrySet() – returns all key–value pairs

Code:
import [Link].*;

public class MapPractical {


public static void main(String[] args) {
Map<Integer, String> students = new HashMap<>();

// a. Add items
[Link](101, "Amit");
[Link](102, "Sumit");
[Link](103, "Rahul");

// c. Search specific key


[Link]("Searching for key 102: " + [Link](102));

// b. Remove items
[Link](103);
[Link]("Map after removing 103: " + students);
}
}
Output:
Conclusion: The Map interface stores data in the form of key–value pairs and
provides efficient operations such as insertion, deletion, and searching.
By using methods like put(), remove(), and containsKey(), we can easily manage and
access data in a Map.
Thus, the Map interface is useful for fast and structured data storage in Java
applications.
Experiment No. 5
Aim: To write a Java program using a Lambda Expression with multiple parameters
to add two numbers.

Theory: A Lambda Expression in Java provides a concise way to represent a


functional interface (an interface with exactly one abstract method).
It is mainly used to implement functional programming features introduced in Java 8.

Syntax of a lambda expression with multiple parameters:


(parameter1, parameter2) -> expression

Lambda expressions improve code readability, reduce boilerplate code, and support
parallel processing.

Code:

interface Addable {
int add(int a, int b);
}

public class LambdaDemo {


public static void main(String[] args) {
// Lambda expression with multiple parameters
Addable ad1 = (a, b) -> (a + b);
[Link]("Sum of 10 and 20: " + [Link](10, 20));

Addable ad2 = (int a, int b) -> {


return (a + b);
};
[Link]("Sum of 100 and 200: " + [Link](100, 200));
}
}

Output:
Sum of 10 and 20: 30

Conclusion: Lambda expressions allow writing concise and readable code in Java.
Using multiple parameters in a lambda expression makes it easy to perform
operations like addition without creating separate implementation classes.
Thus, lambda expressions simplify functional programming in Java.
Experiment No. 6
Aim: Write a JSP page to display the Registration form (Make your own assumptions)

Theory: JSP (Java Server Pages) is a server-side technology used to create dynamic
web pages.
A JSP page can contain HTML tags along with JSP directives and scripting elements.
In this experiment, a registration form is created using HTML form elements inside a
JSP page to collect user details and submit them to the server.

Code:
<html>
<body>
<h2>User Registration Form</h2>
<form action="[Link]">
Name: <input type="text" name="uName"><br><br>
Email: <input type="email" name="uEmail"><br><br>
Course: <input type="text" name="uCourse"><br><br>
<input type="submit" value="Register">
</form>
</body>
</html>

Output:

Conclusion: A simple registration form can be created using JSP by embedding HTML
form elements.
JSP allows easy creation of dynamic web pages and efficient handling of user input.
Thus, JSP is useful for developing interactive web applications.
Experiment No. 7
Aim: To write a JSP program to add, delete, and display records from the
StudentMaster table using JDBC.

Theory: JSP (Java Server Pages) is a server-side technology used to create dynamic
web applications.
Using JDBC (Java Database Connectivity), JSP can interact with databases to perform
operations like insert, delete, and select records.
In this experiment, JSP is used to manage student records stored in the
StudentMaster table.

Code:

 Database table: StudentMaster

StudentMaster(
RollNo INT PRIMARY KEY,
Name VARCHAR(50),
Semester INT,
Course VARCHAR(50)
)

 JSP Code ([Link])

<%@ page import="[Link].*" %>

<html>
<head>
<title>Student Master</title>
</head>
<body>

<h2>Student Master</h2>

<form method="post">
Roll No: <input type="text" name="roll"><br><br>
Name: <input type="text" name="name"><br><br>
Semester: <input type="text" name="sem"><br><br>
Course: <input type="text" name="course"><br><br>

<input type="submit" name="add" value="Add">


<input type="submit" name="delete" value="Delete">
</form>

<hr>
<%
String url = "jdbc:mysql://localhost:3306/college";
String user = "root";
String pass = "";

[Link]("[Link]");
Connection con = [Link](url, user, pass);
Statement stmt = [Link]();

if ([Link]("add") != null) {
[Link](
"INSERT INTO StudentMaster VALUES (" +
[Link]("roll") + ",'" +
[Link]("name") + "'," +
[Link]("sem") + ",'" +
[Link]("course") + "')"
);
}

if ([Link]("delete") != null) {
[Link](
"DELETE FROM StudentMaster WHERE RollNo=" +
[Link]("roll")
);
}

ResultSet rs = [Link]("SELECT * FROM StudentMaster");


%>

<h3>Student Records</h3>
<table border="1">
<tr>
<th>Roll No</th>
<th>Name</th>
<th>Semester</th>
<th>Course</th>
</tr>

<%
while ([Link]()) {
%>
<tr>
<td><%= [Link](1) %></td>
<td><%= [Link](2) %></td>
<td><%= [Link](3) %></td>
<td><%= [Link](4) %></td>
</tr>
<%
}
[Link]();
%>

</table>

</body>
</html>

Output:

Conclusion: Using JSP and JDBC, records from the StudentMaster table can be added,
deleted, and displayed efficiently.
This experiment demonstrates how JSP interacts with a database to perform basic
CRUD operations.
Thus, JSP is suitable for developing database-driven web applications.
Experiment No. 8
Aim: To write a Spring Framework program that prints “Hello World” using Spring
IoC Container.

Theory: Spring Framework is a popular Java framework used for building enterprise-
level applications.
The IoC (Inversion of Control) container manages Java objects (beans) and their
dependencies.
In this experiment, we will create a Spring bean and use ApplicationContext to print
“Hello World”.

Code:
1. Create Bean Class

public class HelloWorld {


public void show() {
[Link]("Hello World");
}
}

2. Create Spring Configuration File ([Link])

<?xml version="1.0" encoding="UTF-8"?>


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

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


</beans>

3. Create Main Class

import [Link];
import [Link];

public class HelloSpring {


public static void main(String[] args) {

ApplicationContext context = new


ClassPathXmlApplicationContext("[Link]");
HelloWorld obj = (HelloWorld) [Link]("hello");

[Link]();
}
}
Output

Hello World

Conclusion: The Spring IoC container creates and manages beans using configuration
files.
By using ApplicationContext, we can easily retrieve beans and execute methods.
Thus, Spring simplifies dependency management and promotes loose coupling.
Experiment No. 9
Aim: To demonstrate Autowiring in Spring Framework to automatically inject
dependencies between beans.

Theory: Autowiring in Spring automatically injects dependencies without using


explicit <property> tags.
Spring supports several autowiring modes:
 no : No autowiring
 byName : Matches property name with bean id
 byType : Matches property type with bean class
 constructor : Uses constructor for autowiring
Autowiring reduces configuration and makes code cleaner.

Code:

1. Bean Class ([Link])


public class Student {
private int id;
private String name;

public void setId(int id) {


[Link] = id;
}

public void setName(String name) {


[Link] = name;
}

public void display() {


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

2. Bean Class ([Link])


public class StudentService {
private Student student;

public void setStudent(Student student) {


[Link] = student;
}

public void showStudent() {


[Link]();
}
}
3. Spring Configuration File ([Link])
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]

<!-- Student Bean -->


<bean id="student" class="Student">
<property name="id" value="101"/>
<property name="name" value="Abdul Haseeb"/>
</bean>

<!-- StudentService Bean with Autowiring byName -->


<bean id="studentService" class="StudentService" autowire="byName"/>
</beans>

4. Main Class ([Link])


import [Link];
import [Link];

public class Main {


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

StudentService service = (StudentService)


[Link]("studentService");
[Link]();
}
}

Output:

Student Id: 101


Student Name: John Doe

Conclusion: Autowiring in Spring allows automatic dependency injection, reducing


the need for explicit bean wiring.
Using autowire="byName" connects beans based on property names.
Autowiring simplifies configuration and improves code maintainability.
Experiment No. 10
Aim: To demonstrate Spring AOP (Aspect-Oriented Programming) using Before
Advice to execute code before the main method execution.

Theory: Spring AOP allows separation of cross-cutting concerns like logging, security,
transaction management, etc.
A Before Advice is executed before the execution of a method.

Key Components:
1. Aspect – contains advice
2. Advice – action taken before/after method execution
3. JoinPoint – point in execution (method call)
4. Pointcut – defines which methods to apply advice

Code:

1. Business Class ([Link])


public class Student {
public void display() {
[Link]("Student Details Displayed");
}
}

2. Aspect Class ([Link])


import [Link];
import [Link];

@Aspect
public class LoggingAspect {

@Before("execution(* [Link](..))")
public void beforeAdvice() {
[Link]("Before Advice: Logging before method execution");
}
}

3. Spring Configuration File ([Link])


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:aop="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="
[Link]
[Link]
[Link]
[Link]
<!-- Enable AOP -->
<aop:aspectj-autoproxy/>

<!-- Business Bean -->


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

<!-- Aspect Bean -->


<bean id="loggingAspect" class="LoggingAspect"/>
</beans>

4. Main Class ([Link])


import [Link];
import [Link];

public class Main {


public static void main(String[] args) {

ApplicationContext context = new


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

[Link]();
}
}

Output:

Before Advice: Logging before method execution


Student Details Displayed

Conclusion: Spring AOP allows executing additional code before the actual method
execution using Before Advice.
This helps in modularizing cross-cutting concerns such as logging and security.
Thus, Spring AOP improves code maintainability and reduces redundancy.
Experiment No. 11
Aim: To write a JSP program to insert, update, and delete records in the
StudentMaster table using JDBC.

Theory: JSP pages can be used to interact with databases using JDBC.
Using JDBC, we can perform CRUD operations (Create, Read, Update, Delete) on
database tables.
In this experiment, the JSP page provides a form to insert, update, and delete
records.

Code:

 DATABASE (pgsql)
RollNo INT PRIMARY KEY
Name VARCHAR(50)
Semester INT
Course VARCHAR(50)

 [Link]
<%@ page import="[Link].*" %>
<%@ page errorPage="[Link]" %>

<html>
<head>
<title>Student CRUD</title>
</head>
<body>

<h2>Student CRUD Operations</h2>

<form method="post">
Roll No: <input type="text" name="roll"><br><br>
Name: <input type="text" name="name"><br><br>
Semester: <input type="text" name="sem"><br><br>
Course: <input type="text" name="course"><br><br>

<input type="submit" name="insert" value="Insert">


<input type="submit" name="update" value="Update">
<input type="submit" name="delete" value="Delete">
</form>

<hr>

<%
String url = "jdbc:mysql://localhost:3306/college";
String user = "root";
String pass = "";

[Link]("[Link]");
Connection con = [Link](url, user, pass);
Statement stmt = [Link]();

if ([Link]("insert") != null) {
String sql = "INSERT INTO StudentMaster VALUES (" +
[Link]("roll") + ",'" +
[Link]("name") + "'," +
[Link]("sem") + ",'" +
[Link]("course") + "')";
[Link](sql);
[Link]("Record Inserted Successfully<br>");
}

if ([Link]("update") != null) {
String sql = "UPDATE StudentMaster SET " +
"Name='" + [Link]("name") + "', " +
"Semester=" + [Link]("sem") + ", " +
"Course='" + [Link]("course") + "' " +
"WHERE RollNo=" + [Link]("roll");
[Link](sql);
[Link]("Record Updated Successfully<br>");
}

if ([Link]("delete") != null) {
String sql = "DELETE FROM StudentMaster WHERE RollNo=" +
[Link]("roll");
[Link](sql);
[Link]("Record Deleted Successfully<br>");
}

ResultSet rs = [Link]("SELECT * FROM StudentMaster");


%>

<h3>Student Records</h3>
<table border="1">
<tr>
<th>RollNo</th>
<th>Name</th>
<th>Semester</th>
<th>Course</th>
</tr>

<%
while ([Link]()) {
%>
<tr>
<td><%= [Link]("RollNo") %></td>
<td><%= [Link]("Name") %></td>
<td><%= [Link]("Semester") %></td>
<td><%= [Link]("Course") %></td>
</tr>
<%
}
[Link]();
%>

</table>

</body>
</html>

Conclusion: Using JSP and JDBC, we can perform database operations like insert,
update, and delete records.
This demonstrates basic CRUD operations and interaction between JSP and database.
Experiment No. 12
Aim: To create a simple Spring Boot application that prints a message on the console.

Theory: Spring Boot is a Spring framework module that makes it easy to create
stand-alone, production-ready Spring applications.
It provides auto-configuration, embedded servers, and reduces boilerplate code.
In this experiment, we will create a basic Spring Boot application and print a message
using the main method.

Code:

Step 1: Create Spring Boot Project


Use Spring Initializr or your IDE to create a Spring Boot project.

Dependencies required:
 Spring Web (optional for console output)

Step 2: Main Application Class

import [Link];
import [Link];

@SpringBootApplication
public class HelloSpringBoot {

public static void main(String[] args) {


[Link]([Link], args);
[Link]("Hello Spring Boot!");
}
}

Output:

Hello Spring Boot!

Conclusion: Spring Boot simplifies application development by providing automatic


configuration and an embedded server.
A simple Spring Boot application can be created using @SpringBootApplication and
[Link]().
Thus, Spring Boot helps in developing applications quickly with minimal
configuration.

You might also like