24MCA-56 Advanced Java Journal 6 Practs
24MCA-56 Advanced Java Journal 6 Practs
Step 3: Right click on the project file created and click on New >Class
Step 4: Finish
Practical No. 1
(1.1) Generic Class
Test(T obj)
{
this.obj=obj;
}
public T getObject()
{
return this.obj;
}
}
public class test{
public static void main(String[] args) {
Test<Integer> iobj=new Test<Integer>(04);
System.out.println("the value of integer:"+iobj.getObject());
Test<String>sobj=new Test<String>("Manoranjan");
System.out.println("the value of string:"+sobj.getObject());
Output:
void display()
{
System.out.println("Generic method example:");
}
<T>void gdisplay(T e)
{
System.out.println(e.getClass().getName()+"="+e);
}
public static void main(String[]args)
{
prac1b g1=new prac1b();
g1.display();
g1.gdisplay(1);
g1.gdisplay("Manoranjan");
g1.gdisplay(20.09);
Output:
(1.3) Wildcards
Aim: Write a Java program to demonstrate Wildcards in Java Generics.
Code:
package generic;
import java.util.Arrays;
import java.util.List;
}
private static void show(List<? super Integer> list)
{
list.forEach
((x)->{
System.out.print(x+" ");
});
Practical No. 2
(2.1) List
Aim: Write a Java program to create a List containing a list of items of type String and use
for each loop to print the items of the list.
Code:
package Prac2;
import java.util.ArrayList;
public class prac2a {
public static void main(String[] args) {
ArrayList<String>list=new ArrayList<String>();
list.add("adbms");
list.add("python");
list.add("java");
list.add("maths");
System.out.println(list);
System.out.println("Traversing list through for each loop:");
for(String subject:list)
System.out.println(subject);
}
}
Output:
Output:
Practical No. 3
(3.1) Sets
Aim: 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:
package Prac3;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class prac3a {
public static void main(String[] args) {
List<String>names = new LinkedList<>();
names.add("Amey");
names.add("Vishwas");
names.add("Shinde");
ListIterator<String> LT=names.listIterator();
System.out.println("forward direction ListIterator:");
while(LT.hasNext()) {
System.out.println(LT.next());
}
System.out.println("backward direction ListIterator:");
while(LT.hasPrevious()) {
System.out.println(LT.previous());
}
}
}
Output:
Output:
Practical No. 4
Aim: 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:
package prac4;
import java.util.HashMap;
import java.util.Map;
System.out.println("map1"+map1);
Map<Integer,String>map2=new HashMap<>();
map2.put(5,"komal");
map2.put(6,"vijay");
map2.put(7,"bhamble");
map1.putAll(map2);
System.out.println("map1 adding item from map2:"+map1);
map1.remove(5);
System.out.println("map1 after removing:"+map1);
boolean isPresent=map1.containsKey(1);
System.out.println("is manoranjan present in set1:"+ isPresent);
String value= map1.get(2);
System.out.println("Value for key 1 is:"+ value);
System.out.println("Printing all key and values:");
for(Map.Entry<Integer,String>entry:map1.entrySet())
{
System.out.println("key:"+entry.getKey()+"values:"+entry.getValue());
}
}
Output:
Practical No. 5
(5.1)
Aim: Write a java program using Lambda expressions to print “Hello World”.
Code:
package prac5;
public class prac5a {
public static void main(String[] args) {
Runnable helloworld=()-> System.out.println("Hello GNIMS World");
helloworld.run();
}
}
Output:
(5.2)
Aim: Write a java program using Lambda expressions using single parameters.
Code:
package prac5;
import java.util.Arrays;
import java.util.List;
public class prac5b {
public static void main(String[] args) {
List<String>names=Arrays.asList("amey","vishwas","shinde");
names.forEach(name->System.out.println("Hello"+names+"!"));
}
}
Output:
(5.3)
Aim: Write a java program using Lambda expressions with multiple parameters to add two
numbers.
Code:
package prac5;
interface A
{
int add(int i,int j);
}
public class prac5c
{
public static void main(String[] args) {
A num=(i,j)->i+j;
int result= num.add(7, 8);
System.out.println("Addition of 7 and 8 is : " +result);
}
}
Output:
(5.4)
Aim: Write a Java Program using Lambda Expression to calculate the following
a) Convert Fahrenheit to Celsius
b) Convert Kilometers to Miles
Code:
package prac5;
interface Converter{
double convert(double input);
}
public class prac5d {
public static void main(String[] args) {
Converter a=f->(f-32)*5/9;
double celcius= a.convert(122);
System.out.println("100 Degree fahrenite is " +celcius+ " degree celcius");
Converter b =km->km/1.609344;
double miles=b.convert(90);
System.out.println("90 kilometer is : "+miles+ " miles");
}
}
Output:
(5.5)
Aim: Write a Java Program using Lambda expression with or without return keyword.
Code:
package prac5;
interface Calculator{
int calculate(int i, int j);
}
public class prac5e {
public static void main(String[] args) {
Calculator add=(i,j)->i+j;
Calculator subtract=(i,j)->{
return i-j;
};
int sum= add.calculate(10,8);
int difference = subtract.calculate(78, 45);
System.out.println("Addition of 10 and 8 is : "+sum);
System.out.println("Subtraction of 78 and 45 is : "+difference);
}
}
Output:
(5.6)
Aim: Write a Java Program using Lambda expression to concatenate two strings.
Code:
package prac5;
interface Concatenator{
String concatenate(String s1, String s2);
}
public class prac5f {
public static void main(String[] args) {
String str ="Amey_";
String str1="Shinde";
Concatenator cn= (s1,s2)-> s1+s2;
String result= cn.concatenate(str, str1);
System.out.println("The Concatenated String is : "+result);
}
}
Output:
Practical No. 6
(6.1)
Aim: Create a Telephone directory using JSP and store all the information within a database,
so that later could be retrieved as per the requirement.
Code:
Create a database and create table
CREATE DATABASE PhoneDirectory;
USE PhoneDirectory;
CREATE TABLE Contacts (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
phone VARCHAR(20),
email VARCHAR(255)
);
DBConnection.java:
package phonedirectory;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
try {
connection = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
throw e; // You may want to handle this exception more gracefully in a real
application
}
return connection;
}
}
Add_contact.jsp
try {
// Insert the new contact into the database
String insertQuery = "INSERT INTO contacts (name, phone, email) VALUES (?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(insertQuery);
preparedStatement.setString(1, name);
preparedStatement.setString(2, phone);
preparedStatement.setString(3, email);
preparedStatement.executeUpdate();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// Close the database connection
if (connection != null) {
connection.close();
}
%>
<html>
<body>
<h1>Add a New Contact</h1>
<form action="add_contact.jsp" method="post">
<label>Name: <input type="text" name="name"></label><br>
<label>Phone: <input type="text" name="phone"></label><br>
<label>Email: <input type="text" name="email"></label><br>
<input type="submit" value="Add Contact">
<a href="display_contacts.jsp">show data</a>
</form>
</body>
</html>
Display_contact.jsp:
while (resultSet.next()) {
int userId = resultSet.getInt("id");
String username = resultSet.getString("name");
String phone = resultSet.getString("phone");
String email = resultSet.getString("email");
%>
<tr>
<td><%= userId %></td>
<td><%= username %></td>
<td><%= phone %></td>
<td><%= email %></td>
<td>
<a href="edit_contact.jsp?id=<%= userId %>">Edit</a>
<a href="delete_contact.jsp?id=<%= userId %>">Delete</a>
</td>
</tr>
<%
}
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
// Handle database errors here
out.println("Database error: " + e.getMessage());
}
%>
</table>
</body>
</html>
Edit_contacts.jsp:
if (resultSet.next()) {
String currentName = resultSet.getString("name");
String currentPhone = resultSet.getString("phone");
String currentEmail = resultSet.getString("email");
%>
<form action="update_contact.jsp" method="post">
<input type="hidden" name="id" value="<%= contactId %>">
Name: <input type="text" name="name" value="<%= currentName %>"><br>
Phone: <input type="text" name="phone" value="<%= currentPhone %>"><br>
Email: <input type="text" name="email" value="<%= currentEmail %>"><br>
<input type="submit" value="Update Contact">
</form>
<%
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Close database resources individually
if (resultSet != null) resultSet.close();
if (preparedStatement != null) preparedStatement.close();
if (connection != null) connection.close();
}
%>
</body>
</html>
update _contact.jsp:
String updateQuery = "UPDATE contacts SET name=?, phone=?, email=? WHERE id=?";
preparedStatement = connection.prepareStatement(updateQuery);
preparedStatement.setString(1, newName);
preparedStatement.setString(2, newPhone);
preparedStatement.setString(3, newEmail);
GURU NANAK INSTITUTE OF MANAGEMENT STUDIES
32
ROLL NO – 24MCA56 ADVANCED JAVA
preparedStatement.setInt(4, contactId);
preparedStatement.executeUpdate();
%>
<p>Contact updated successfully.</p>
<a href="display_contacts.jsp">Back to Contacts</a>
<%
} catch (SQLException e) {
e.printStackTrace();
%>
<p>An error occurred while updating the contact: <%= e.getMessage() %></p>
<%
} finally {
// Close database resources individually
if (preparedStatement != null) preparedStatement.close();
if (connection != null) connection.close();
}
%>
</body>
</html>
Delete_contact.jsp:
if (idParam != null) {
int contactId = Integer.parseInt(idParam);
try {
// Delete the contact from the database
String deleteQuery = "DELETE FROM contacts WHERE id=?";
PreparedStatement preparedStatement = connection.prepareStatement(deleteQuery);
preparedStatement.setInt(1, contactId);
preparedStatement.executeUpdate();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// Close the database connection
if (connection != null) {
connection.close();
}
%>
<html>
<body>
<h1>Contact Deleted</h1>
<p>The contact has been deleted successfully.</p>
<a href="display_contacts.jsp">Back to Contacts</a>
</body>
</html>
Output:
(6.2)
Aim : Write a JSP Page to display the Registration Form.
Code:
<!DOCTYPE html>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<h2>Registration Form</h2>
<form action="storeRegistration.jsp" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Register">
</form>
</body>
</html>
Output:
(6.3)
Aim: Write a JSP Program to add, delete and display record from StudentMaster(Roll
No, Name, Semester, Course) table.
Code:
DBConnection.java
package studentdirectory;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
public static Connection getConnection() throws SQLException {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
}
catch(ClassNotFoundException e) {
throw new SQLException("MySQL JDBC Driver not found",e);
}
String url = "jdbc:mysql://localhost:3306/PhoneDirectory";
String username = "root";
String password = "";
try {
connection = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
throw e; // You may want to handle this exception more gracefully in a real
application
}
GURU NANAK INSTITUTE OF MANAGEMENT STUDIES
39
ROLL NO – 24MCA56 ADVANCED JAVA
return connection;
}
}
Add_student.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<%@ page import="studentdirectory.DBConnection" %><%
Connection connection = DBConnection.getConnection();
if (request.getMethod().equals("POST")) {
String Roll_no = request.getParameter("Roll_no");
String name = request.getParameter("name");
String semester = request.getParameter("semester");
String course = request.getParameter("course");
if (name != null && semester != null && course != null) {
try {
// Insert the new contact into the database
String insertQuery = "INSERT INTO students (Roll_no,name, semester, course) VALUES
(?, ?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(insertQuery);
preparedStatement.setString(1, Roll_no);
preparedStatement.setString(2, name);
preparedStatement.setString(3, semester);
preparedStatement.setString(4, course);
preparedStatement.executeUpdate();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
GURU NANAK INSTITUTE OF MANAGEMENT STUDIES
40
ROLL NO – 24MCA56 ADVANCED JAVA
}
// Close the database connection
if (connection != null) {
connection.close();
}
%>
<html>
<body>
<h1>Add a New Student Data</h1>
<form action="add_student.jsp" method="post">
<label>Roll_No: <input type="text" name="Roll_no"></label><br>
<label>Name: <input type="text" name="name"></label><br>
<label>Semester: <input type="text" name="semester"></label><br>
<label>Course: <input type="text" name="course"></label><br>
<input type="submit" value="Add Data">
<a href="display_data.jsp">show data</a>
</form>
</body>
</html>
Delete_data.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<%@ page import="studentdirectory.DBConnection" %>
<%
Connection connection = DBConnection.getConnection();
// Check if an ID parameter is provided in the URL
String idParam = request.getParameter("id");
if (idParam != null) {
Display_data.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<%@ page import="studentdirectory.DBConnection" %>
<!DOCTYPE html>
GURU NANAK INSTITUTE OF MANAGEMENT STUDIES
42
ROLL NO – 24MCA56 ADVANCED JAVA
<html>
<head>
<title>Display Students</title>
</head>
<body>
<h1>Registered Students</h1>
<table border="1">
<tr>
<th>User ID</th>
<th>Roll_no</th>
<th>name</th>
<th>semester</th>
<th>course</th>
<th>Update</th>
</tr>
<%
try {
// Establish a database connection
Connection connection = DBConnection.getConnection();
// Create and execute an SQL SELECT statement
String selectQuery = "SELECT * FROM students";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(selectQuery);
while (resultSet.next()) {
int userId = resultSet.getInt("id");
%>
<tr>
<td><%= userId %></td>
<td><%= Roll_no %></td>
<td><%= name %></td>
<td><%= semester %></td>
<td><%= course %></td>
<td>
<a href="edit_data.jsp?id=<%= userId %>">Edit</a>
<a href="delete_data.jsp?id=<%= userId %>">Delete</a>
</td>
</tr>
<%
}
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
// Handle database errors here
out.println("Database error: " + e.getMessage());
}
%>
</table>
</body>
</html>
edit_data.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<%@ page import="studentdirectory.DBConnection" %>
GURU NANAK INSTITUTE OF MANAGEMENT STUDIES
44
ROLL NO – 24MCA56 ADVANCED JAVA
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Edit Data</title>
</head>
<body>
<h1>Edit Data</h1>
<%
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// Establish a database connection
connection = DBConnection.getConnection();
// Check if an ID parameter is provided in the URL
String idParam = request.getParameter("id");
int contactId = -1;
if (idParam != null) {
contactId = Integer.parseInt(idParam);
// Retrieve the contact's current details
String selectQuery = "SELECT * FROM students WHERE id=?";
preparedStatement = connection.prepareStatement(selectQuery);
preparedStatement.setInt(1, contactId);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
String currentId = resultSet.getString("Id");
Update_data.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<%@ page import="studentdirectory.DBConnection" %>
GURU NANAK INSTITUTE OF MANAGEMENT STUDIES
46
ROLL NO – 24MCA56 ADVANCED JAVA
<!DOCTYPE html>
<html>
<head>
<title>Update Data</title>
</head>
<body>
<h1>Update Data</h1>
<%
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
// Establish a database connection
connection = DBConnection.getConnection();
// Get the data submitted from the form
int contactId = Integer.parseInt(request.getParameter("id"));
String newRoll_no = request.getParameter("Roll_no");
String newName = request.getParameter("name");
String newSemester = request.getParameter("Semester");
String newCourse = request.getParameter("Course");
// Update the contact's information in the database
String updateQuery = "UPDATE students SET Roll_no=?, name=?, semester=?, course=?
WHERE id=?";
preparedStatement = connection.prepareStatement(updateQuery);
preparedStatement.setString(1,newRoll_no);
preparedStatement.setString(2, newName);
preparedStatement.setString(3, newSemester);
preparedStatement.setString(4, newCourse);
preparedStatement.executeUpdate();
%>
<p>Data updated successfully.</p>
GURU NANAK INSTITUTE OF MANAGEMENT STUDIES
47
ROLL NO – 24MCA56 ADVANCED JAVA
Output:
(6.4)
Aim: Design loan calculator using JSP which accepts Period of Time (in years) and
Principal Loan Amount. Display the payment amount for each loan and then list the
loan balance and interest paid for each payment over the term of the loan for the
following time period and interest rate:
a. 1 to 7 year at 5.35%
b. 8 to 15 year at 5.5%
c. 16 to 30 year at 5.75%
Code:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>SIMPLE INTEREST CALCULATOR</title>
</head>
<body>
<h1> Simple Interest Calculator</h1>
<form>
Principal Amount: <input type="text" id="principal" required><br>
Rate of Interest (per annum):<input type="text" id="rate" required><br>
Time(in years):<input type="text" id="time" required><br>
}
</script>
</body>
</html>
Output:
(6.5)
Aim: Write a program using JSP that displays a webpage consisting Application form
for change of Study Center which can be filled by any student who wants to change his/
her study center. Make necessary assumptions
Code:
prac6e.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Change Study Centre Application</title>
</head>
<body>
<h1> Change Study Center</h1>
<form action="exchange.jsp" method="post">
<label for="studentName">Student Name:</label>
<input type="text" id="studentName" name="studentName" required><br><br>
<label for="currentCenter">Current Study Center:</label>
<input type="text" id="currentCenter" name="currentCenter" required><br><br>
<label for="newCenter">New Study Center:</label>
<input type="text" id="newCenter" name="newCenter" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
exchange.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Application Submitted</title>
</head>
<body>
<h1>Application Submitted</h1>
<p>Thank you for submitting your study center change application.</p>
<p> Student Name:<%=request.getParameter("studentName") %></p>
<p> Current Center:<%=request.getParameter("currentCenter") %></p>
<p> New Center:<%=request.getParameter("newCenter") %></p>
</body>
</html>
Output:
(6.6)
Aim: Write a JSP program that demonstrates the use of JSP declaration, scriptlet,
directives, expression, header and footer.
Code:
Prac6f.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<style>
/* General page styles */
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
color: #333;
margin: 0;
padding: 0;
}
/* Centering content */
center {
text-align: center;
margin-top: 50px;
}
/* Header styles */
h1 {
color: #2c3e50;
}
/* Paragraph styles */
p{
font-size: 16px;
color: #7f8c8d;
}
/* Footer styles */
footer {
font-size: 14px;
color: #95a5a6;
margin-top: 30px;
}
</style>
</head>
<body>
<%@ include file="header.jsp" %>
<center>
<%! int data=50; %>
<%= "Value of the variable is: " + data %>
<%! double circle(int n) {return 3.14 * n * n;} %>
<br>
<%= "Area of Circle is: " + circle(5) %>
<br>
<%! int rectangle(int l, int b) {return 1 * b;} %>
<%= "Area of rectangle is: " + rectangle(4,6) %>
<br>
<%! int perimeter(int x, int y) {
int peri = 2 * (x+y);
return peri;
}%>
<br>
<%= "Perimeter of rectangle: " + perimeter(5,6) %>
<br>
<p> thanks for visiting my page </p>
footer.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center>
<b>Amey Shinde</b>
<b>24MCA-56</b>
</center>
</body>
</html>
Header.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center>
<h2>
This include directive example.
</h2>
</center>
</body>
</html>
Output: