0% found this document useful (0 votes)
5 views

AJava_File[1]ss

This practical file contains a series of Java programming experiments focused on advanced Java concepts, including networking, servlets, JDBC, and design patterns. Each experiment includes a specific aim and corresponding code examples, such as creating a chat application, handling HTTP requests, and interacting with databases. The document serves as a comprehensive guide for students to understand and implement various Java functionalities in real-world applications.

Uploaded by

up85walajaat
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)
5 views

AJava_File[1]ss

This practical file contains a series of Java programming experiments focused on advanced Java concepts, including networking, servlets, JDBC, and design patterns. Each experiment includes a specific aim and corresponding code examples, such as creating a chat application, handling HTTP requests, and interacting with databases. The document serves as a comprehensive guide for students to understand and implement various Java functionalities in real-world applications.

Uploaded by

up85walajaat
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
You are on page 1/ 28

Practical file

of
Advance Java

Submitted by:- Submitted to


Sanjay Kumar Mr. Parveen Kumar

B. Tech CSE 6th Sem Assistant Professor(CSC)

Roll No. : 06

School of Computer Science & Technology

May 2025
Index
S. No Experiment

Write a Java program of the InetAddress class in Java for retrieving the host name and IP
1
address of a specified host.

Write a Java program of the URL class in Java for extracting components such as protocol,
2
host, port, file path, and full URL from a web address

Write a Java programto implement a simple client-server chat application in Java using
3
socket programming, where the server and client can exchange text messages in real-time.

4 To develop a basic Java servlet that displays a welcome message in a web browser

To write a Java program using the UCanAccess JDBC driver to connect to a Microsoft Access
5
database and create a table with appropriate fields and constraints.

To develop a Java servlet that collects member details including an image filename from an
6
HTML form, and stores the information in a MySQL database using JDBC.

To demonstrate the use of Cookies in Servlets by creating a FirstServlet that stores the user's
7
name in a cookie and passes it to the next Secondservlet.

8 To demonstrate HTTP session tracking using HttpSession in Servlets.

To demonstrate basic JSP scripting elements and expressions including string manipulation
9
and displaying the current date using JSP.

To demonstrate basic Hibernate CRUD operation (Create) using annotation-based


10
configuration.

To create a Java RMI-based application that performs basic arithmetic operations remotely
11
using client-server architecture

Write a Java program to implement the Singleton Design Pattern for managing database
12 operations, ensuring that only one instance of the DatabaseOperations class exists throughout
the application.
Program No 1.
Aim:- To demonstrate the use of the InetAddress class in Java for retrieving the host name and IP address
of a specified host.
import java.net.*;

public class InetDemo {


public static void main(String[] args) {
try {
InetAddress ip = InetAddress.getByName("localhost");
System.out.println("My First Program Advance Java in Starex
University B. Tech 6th Sem) ");
System.out.println("Host Name: " + ip.getHostName());
System.out.println("IP Address: " + ip.getHostAddress());
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
Program No 2.
Aim:-To demonstrate the use of the URL class in Java for extracting components such as protocol, host,
port, file path, and full URL from a web address.
import java.net.*;

class URLDemo {
public static void main(String args[]) throws MalformedURLException {
@SuppressWarnings("deprecation")
URL hp = new URL("https://www.tpointtech.com/java-tutorial");
System.out.println("Protocol: " + hp.getProtocol());
System.out.println("Port: " + hp.getPort());
System.out.println("Host: " + hp.getHost());
System.out.println("File: " + hp.getFile());
System.out.println("Ext: " + hp.toExternalForm());
}
}
Program No 3.
Aim:- To implement a simple client-server chat application in Java using socket programming, where
the server and client can exchange text messages in real-time.

import java.io.*;
import java.net.*;

public class ChatServer {


public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(1234); // Port number
System.out.println("Server started. Waiting for client...");

Socket socket = serverSocket.accept(); // Accept client connection


System.out.println("Client connected!");

// Create input and output streams


BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

// For reading messages from server side (keyboard input)


BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in));
String message;

// Chat loop
while (true) {
String clientMsg = in.readLine();
if (clientMsg == null || clientMsg.equalsIgnoreCase("bye"))
break;
System.out.println("Client: " + clientMsg);

System.out.print("Server: ");
message = userInput.readLine();
out.println(message);
if (message.equalsIgnoreCase("bye")) break;
}

socket.close();
serverSocket.close();
System.out.println("Chat ended.");

} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
import java.io.*;
import java.net.*;

public class ChatClient {


public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 1234); // Connect to server
System.out.println("Connected to server!");
// Create input and output streams
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// For reading messages from client side (keyboard input)
BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in));
String message;
// Chat loop
while (true) {
System.out.print("Client: ");
message = userInput.readLine();
out.println(message);
if (message.equalsIgnoreCase("bye")) break;

String serverMsg = in.readLine();


if (serverMsg == null || serverMsg.equalsIgnoreCase("bye"))
break;
System.out.println("Server: " + serverMsg);
}

socket.close();
System.out.println("Chat ended.");

} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
Program No 4.
Aim:- To develop a basic Java servlet that displays a welcome message in a web browser.

package in.sp.backend;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class Login extends HttpServlet {


@Override
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html"); // Set response content type
PrintWriter out = res.getWriter(); // writer object to write response
out.println("<h1>Welcome to Starex University </h1>");
out.println("<h2>It's my first servlet program at Starex University in
B.Tech 6th </h2>"); // Write HTML response
System.out.println("I am in Service of Starex University");
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<welcome-file-list>
<welcome-file>index1.html</welcome-file>
</welcome-file-list>

</servlet-mapping>
<servlet-mapping>
<servlet-name>ml</servlet-name>
<url-pattern>/mylogin</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ml</servlet-name>
<servlet-class>in.sp.backend.Login</servlet-class>
</servlet>

</web-app>
Program No 5.
Aim:- To write a Java program using the UCanAccess JDBC driver to connect to a Microsoft Access
database and create a table with appropriate fields and constraints.

import java.sql.*;

public class CreateTable {


public static void main(String[] args) {
// URL to the MS Access database file (modify according to your system)
String dbURL = "jdbc:ucanaccess://D:/Starex/Advance
Java/odbc/student.accdb";

// SQL command to create a new table with proper constraints


String sqlCreateTable = "CREATE TABLE stu (" +
"srollno INT PRIMARY KEY, " +
"sname VARCHAR(255), " +
"class VARCHAR(50), " +
"marks INT)";
Connection conn = null;
Statement stmt = null;
try {
// Load UCanAccess JDBC driver
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");

// Establish a connection to the MS Access database


conn = DriverManager.getConnection(dbURL);

// Create a statement object


stmt = conn.createStatement();

// Execute the SQL query to create the table


stmt.executeUpdate(sqlCreateTable);

// Confirm the table creation


System.out.println("Table 'stu' created successfully!");
} catch (SQLException e) {
System.err.println("SQL Error: " + e.getMessage());
} catch (ClassNotFoundException e) {
System.err.println("JDBC Driver not found!");
} finally {
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException ex) {
System.err.println("Error closing resources: " +
ex.getMessage());
}
}
}
}
Program No 6.
Aim:- To develop a Java servlet that collects member details including an image filename from an
HTML form, and stores the information in a MySQL database using JDBC.

package in.sp.backend;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

@MultipartConfig
public class MyServlet extends HttpServlet {
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/parveendb";
private static final String JDBC_USER = "root";
private static final String JDBC_PASSWORD = "Pky@1234";

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Retrieve form data


String mname = request.getParameter("mname");
String phone = request.getParameter("phone");
String email = request.getParameter("email");

// Define a permanent directory (change path as needed)


String uploadDir1 = "D://UploadedImages//"; // Permanent directory outside of workspace
String uploadDir2 = "D://Eclipse Workspace//WebxmlDemo12//src//main//webapp//images//" ;
// Ensure directory exists
File directory1 = new File(uploadDir1);
if (!directory1.exists()) {
directory1.mkdirs(); // Create directory if not exists
}
File directory2 = new File(uploadDir2);
if (!directory2.exists()) {
directory2.mkdirs(); // Create directory if not exists
}
// Retrieve image file
Part file = request.getPart("image");
String imageFileName = file.getSubmittedFileName();

// Construct the full path for saving the file


String uploadPath1 = uploadDir1 + imageFileName;
String uploadPath2 = uploadDir2 + imageFileName;

System.out.println("Final Image Path: " + uploadPath1);


System.out.println("Final Image Path: " + uploadPath2);

// Validate inputs
if (mname == null || mname.trim().isEmpty() ||
phone == null || phone.trim().isEmpty() ||
email == null || email.trim().isEmpty() ||
file == null || file.getSize() == 0) {
out.println("<h2 style='color:red;'>Please fill all fields!</h2>");
return;
}

// Save the image file


try (FileOutputStream fos = new FileOutputStream(uploadPath1);
InputStream is = file.getInputStream()) {
byte[] data = new byte[is.available()];
is.read(data);
fos.write(data);
} catch (Exception e) {
e.printStackTrace();
}
try (FileOutputStream fos = new FileOutputStream(uploadPath2);
InputStream is = file.getInputStream()) {
byte[] data = new byte[is.available()];
is.read(data);
fos.write(data);
} catch (Exception e) {
e.printStackTrace();
}
try {
// Establish database connection
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USER,
JDBC_PASSWORD);

// Insert data into database


String insertSQL = "INSERT INTO members (mname, phone, email, imageFileName) VALUES (?,
?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(insertSQL);
stmt.setString(1, mname);
stmt.setString(2, phone);
stmt.setString(3, email);
stmt.setString(4, imageFileName);
stmt.executeUpdate(); // Use executeUpdate() for INSERT

// Fetch the latest inserted member


String selectSQL = "SELECT * FROM members ORDER BY member_id DESC LIMIT 1"; //
Fetch latest entry
PreparedStatement stmt2 = conn.prepareStatement(selectSQL);
ResultSet rs = stmt2.executeQuery(); // Use executeQuery() for SELECT

// HTML response
out.println("<html><head><title>Latest Member Details</title></head><body>");
out.println("<h1>Latest Member Details</h1>");

if (rs.next()) {
String mname2 = rs.getString("mname");
String phone2 = rs.getString("phone");
String email2 = rs.getString("email");
String imageFileName2 = rs.getString("imageFileName");

out.println("<table border='1' style='width:50%; text-align:left;'>");


out.println("<tr><th>Name</th><td>" + mname2 + "</td></tr>");
out.println("<tr><th>Phone</th><td>" + phone2 + "</td></tr>");
out.println("<tr><th>Email</th><td>" + email2 + "</td></tr>");
out.println("<tr><th>Uploaded Image </th><td><img src='" + "D://UploadedImages/" +
imageFileName2 + "' width='200' height='200' alt='Uploaded Image'/></td></tr>");
// out.println("<tr><th>Uploaded Image </th><td><img src='" + "D://Eclipse
Workspace/WebxmlDemo12/src/main/webapp/images/" + imageFileName2 + "' width='200' height='200'
alt='Uploaded Image'/></td></tr>");
out.println("<tr><th>Uploaded Image</th><td><img src='" + "/uploadedImages/" +
imageFileName2 + "' width='200' height='200' alt='Uploaded Image'/></td></tr>");
//out.println("<tr><th>Uploaded Image</th><td><img src='/uploadedImages/" +
imageFileName2 + "' width='200' height='200' alt='Uploaded Image'/></td></tr>");

out.println("</table>");
out.println("<html><head>");
out.println("<script>");
out.println("setTimeout(function() { window.location.href = 'index1.html'; }, 5000);"); // Delay of
5 seconds
out.println("</script>");
out.println("<title>Success</title></head><body>");
out.println("<h2 style='color:green;'>Data inserted successfully! Redirecting to home page in 5
seconds...</h2>");
out.println("</body></html>");
} else {
out.println("<p>No recent members found!</p>");
}

out.println("</body></html>");

// Close resources
rs.close();
stmt2.close();
stmt.close();
conn.close();

} catch (ClassNotFoundException e) {
out.println("<p style='color:red;'>Error: MySQL JDBC Driver Not Found!</p>");
e.printStackTrace(out);
} catch (SQLException e) {
out.println("<p style='color:red;'>SQL Error: " + e.getMessage() + "</p>");
e.printStackTrace(out);
}
}
}

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home Page</title>
</head>
<body>
<h1>Welcome to Parveen Servlet Application for Image Uploading</h1>

<h2>Welcome</h2>

<form action="MyServlet" method="POST" enctype="multipart/form-data">


<label for="mname">Member Name:</label>
<input type="text" id="mname" name="mname" required>
<br>

<label for="phone">Phone No:</label>


<input type="text" id="phone" name="phone" required>
<br>

<label for="email">Email:</label>
<input type="text" id="email" name="email" required>
<br>

<label for="image">Upload Picture:</label>


<input type="file" id="image" name="image" required>
<br>

<button type="submit">Submit</button>
</form>

</body>
</html>

Web.xml

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


<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WebxmlDemo11</param-value>
</context-param>

<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>in.sp.backend.MyServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>SServlet</servlet-name>
<servlet-class>in.sp.backend.SearchServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>SServlet</servlet-name>
<url-pattern>/SearchServlet</url-pattern>
</servlet-mapping>

</web-app>
Program No 7.
.

Aim:- To demonstrate the use of Cookies in Servlets by creating a FirstServlet that stores the user's name in a
cookie and passes it to the next Secondservlet.
package com.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class FirstServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n = request.getParameter("userName");
out.print("<h1>Welcome " + n + "</h1>");

Cookie ck = new Cookie("uname", n);


response.addCookie(ck); // Adding cookie in the response

// Creating submit button


out.print("<form action='SecondServlet' method='post'>");
out.print("<input type='submit' value='Go to SecondServlet'>");
out.print("</form>");
}

// ✅ Fix: Implementing doPost to handle POST requests


protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response); // Redirecting POST requests to doGet
}
}

package com.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class SecondServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Fix: Handle null cookies


Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie ck : cookies) {
if (ck.getName().equals("uname")) {
out.print("<h1>Hello " + ck.getValue() + "</h1>");
break;
}
}
} else {
out.print("<h1>No cookies found</h1>");
}

out.close();
}
}

Output:-
Program No 8.
To demonstrate HTTP session tracking using HttpSession in Servlets.

package com.servlets;

// Import statements
import java.io.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;

public class HTTPServletEx1 extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Setting content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Retrieving user input from form


String name = request.getParameter("userName");

// Displaying the username


out.println("Welcome to Starex Star, " + name + "!<br>");

// Creating a new session


HttpSession httpSession = request.getSession();
httpSession.setAttribute("uname", name);

// Link to the second servlet


out.print("<a href='servletB'>Press Here to Continue</a>");

out.close();
}
}

package com.servlets;

//Import statements
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.*;

public class HTTPServletEx2 extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Setting content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Resuming the existing session


HttpSession session = request.getSession(false);

if (session != null) {
// Retrieving the stored name
String name = (String) session.getAttribute("uname");
// Printing the name and message
out.print(name + ", you have reached the second page.");
} else {
out.print("No active session found. Please go back and enter your
name.");
}

out.close();
}
}
Program No 9.
Aim:- To demonstrate basic JSP scripting elements and expressions including string manipulation and displaying the
current date using JSP.

<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Welcome to JSP File</h1>
<% String name="Parveen Kumar";
int leng=name.length();%>
<h3>Length of String <%=name %> is = <%=leng %><br></h1>
<%= new Date().toString() %>

<a href="Login"> Login Servlet</a>

</body>
</html>

package com.servlets;

//Import statements

import java.io.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;

@WebServlet(urlPatterns="/Login",name="LoginServlet")
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Setting content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.println("Welcome to Starex Star Servlet");

out.close();
}
}

Output:-
Program No 10.
Aim :- To demonstrate basic Hibernate CRUD operation (Create) using annotation-based
configuration.

Student.java

package com.example;

import jakarta.persistence.*;

@Entity
@Table(name = "student")
public class Student {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

private String name;


private String city;

// Getters and Setters


public int getId() {
return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getCity() {


return city;
}

public void setCity(String city) {


this.city = city;
}
}

2. hibernate.cfg.xml (Configuration File – place in src/main/resources)

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


<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property
name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/parveendb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">Pky@1234</property>
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>

<mapping class="com.example.Student"/>
</session-factory>
</hibernate-configuration>

3. InsertStudent.java (Main Class)


package com.example;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class InsertStudent {


public static void main(String[] args) {

// Configure Hibernate and build session factory


SessionFactory factory = new
Configuration().configure().buildSessionFactory();

// Open session
Session session = factory.openSession();
session.beginTransaction();

// Create student object


Student student = new Student();
student.setName("Parveen Kumar");
student.setCity("Gurgaon");

// Save student object


session.save(student);

// Commit transaction
session.getTransaction().commit();
session.close();

System.out.println("Student data inserted successfully!");


}
}

Maven Depandency
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.15.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
</dependency>
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>

Output:-
Program No 11.
Aim:- To create a Java RMI-based application that performs basic arithmetic operations remotely using
client-server architecture.

1. Calculator.java
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Calculator extends Remote {


int add(int a, int b) throws RemoteException;
int subtract(int a, int b) throws RemoteException;
}

CalculatorImpl.java

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class CalculatorImpl extends UnicastRemoteObject implements Calculator {


protected CalculatorImpl() throws RemoteException {
super();
}

public int add(int a, int b) throws RemoteException {


return a + b;
}

public int subtract(int a, int b) throws RemoteException {


return a - b;
}
}

2. CalculatorServer
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class CalculatorServer {


public static void main(String[] args) {
try {
Calculator calculator = new CalculatorImpl();
LocateRegistry.createRegistry(1099);
Registry registry = LocateRegistry.getRegistry();
registry.rebind("CalculatorService", calculator);

System.out.println("Calculator Server is running...");


} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}

CalculatorClient.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Scanner;

public class CalculatorClient {


public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
Calculator calculator = (Calculator) registry.lookup("CalculatorService");

Scanner scanner = new Scanner(System.in);

// Taking user input


System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
System.out.print("Choose operation (add/subtract): ");
String operation = scanner.next();

int result = 0;
if (operation.equalsIgnoreCase("add")) {
result = calculator.add(num1, num2);
} else if (operation.equalsIgnoreCase("subtract")) {
result = calculator.subtract(num1, num2);
} else {
System.out.println("Invalid operation.");
scanner.close();
return;
}

System.out.println("Result: " + result);


scanner.close();
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
Output:-
Program No 12.
Aim:- Write a Java program to implement the Singleton Design Pattern for managing database
operations, ensuring that only one instance of the DatabaseOperations class exists throughout the
application.

package creational.singleton;

public class Driver {

public static void main(String[] args) {


DatabaseOperations obj1 = DatabaseOperations.getInstance();
DatabaseOperations obj2 = DatabaseOperations.getInstance();

if (obj1 != obj2) {
throw new IllegalStateException("single pattern failed");
}
System.out.println("object 1 ==> " + obj1);
System.out.println("object 2 ==> " + obj2);
}
}

package creational.singleton;

public class DatabaseOperations {

private static DatabaseOperations instance = null;

// no one from outside can create object


private DatabaseOperations() {
}

public void readFromDatabase() {


// read from database
}

public void writeIntoDatabase() {


// write into database
}

public static DatabaseOperations getInstance() {


if (instance == null) {
instance = new DatabaseOperations();
}
return instance;
}
}
Output:-

You might also like