Advanced Java Practical Solutions
Advanced Java Practical Solutions
Set A:
2. Write a java program to display all the EName from the Emp table. Assume the
Emp (ENo, EName, Salary) table is already created.
→ import java.sql.*;
public class DisplayEName {
public static void main(String[] args) {
try (Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/yourDatabase",
"username", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT EName FROM Emp")) {
while (rs.next()) {
System.out.println(rs.getString("EName"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
3. Write a java program to create a Student table with attributes Rno, Sname, Per.
→
import java.sql.*;
public class CreateStudentTable {
public static void main(String[] args) {
try (Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/yourDatabase",
"username", "password");
Statement stmt = con.createStatement()) {
String query = "CREATE TABLE Student (Rno INT, Sname VARCHAR(50), Per
FLOAT)";
stmt.executeUpdate(query);
System.out.println("Student table created.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
4. Write a java program to delete the salary column from the Emp table. Assume the
Emp table with attributes ENO, EName and salary is already created.
→
import java.sql.*;
public class DeleteColumn {
public static void main(String[] args) {
try (Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/yourDatabase",
"username", "password");
Statement stmt = con.createStatement()) {
String query = "ALTER TABLE Emp DROP COLUMN salary";
stmt.executeUpdate(query);
System.out.println("Salary column deleted.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
5. Write a java program to delete the details of a given Teacher. Assume the Teacher
table with attributes tno, tname, subject is already created.
→
import java.sql.*;
public class DeleteTeacher {
public static void main(String[] args) {
try (Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/yourDatabase",
"username", "password");
PreparedStatement pstmt = con.prepareStatement("DELETE FROM Teacher
WHERE tno = ?")) {
pstmt.setInt(1, 101); // Replace 101 with desired Teacher number
int rows = pstmt.executeUpdate();
System.out.println(rows + " record(s) deleted.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Set B:
frame.add(new JScrollPane(table));
frame.setSize(400, 300);
frame.setVisible(true);
}
}
3. Write a java program to make the changes in data which is in ResultSet if you
make the changes in data in the database.
→
import java.sql.*;
public class UpdateResultSet {
public static void main(String[] args) {
try (Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/yourDatabase",
"username", "password");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT * FROM yourTable")) {
while (rs.next()) {
if (rs.getInt("id") == 1) { // Replace with your condition
rs.updateString("columnName", "newValue"); // Replace with your
column and value
rs.updateRow();
}
}
System.out.println("Updates applied.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Set C:
2. Write a java program to update the salary of a given employee and display
updated details in JTable. (Use Swing). Assume the Emp (ENo, EName, Sal) table is
already created.
→
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.sql.*;
public class UpdateSalary {
public static void main(String[] args) {
JFrame frame = new JFrame("Updated Employee Details");
DefaultTableModel model = new DefaultTableModel(new String[]{"ENo",
"EName", "Sal"}, 0);
JTable table = new JTable(model);
try (Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/yourDatabase",
"username", "password");
PreparedStatement pstmt = con.prepareStatement("UPDATE Emp SET Sal = ?
WHERE ENo = ?");
Statement stmt = con.createStatement()) {
// Update salary
pstmt.setDouble(1, 50000); // Replace with new salary
pstmt.setInt(2, 1); // Replace with employee number
pstmt.executeUpdate();
// Fetch updated data
ResultSet rs = stmt.executeQuery("SELECT * FROM Emp");
while (rs.next()) {
model.addRow(new Object[]{rs.getInt("ENo"), rs.getString("EName"),
rs.getDouble("Sal")});
}
} catch (SQLException e) {
e.printStackTrace();
}
frame.add(new JScrollPane(table));
frame.setSize(400, 300);
frame.setVisible(true);
}
}
Assignment 2
Set A:
4. Write a program in which the thread sleeps for 6 sec in the loop in reverse order
from 100 to 1 and change the name of the thread.
→
public class ReverseThread extends Thread {
public ReverseThread(String name) {
super(name);
}
public void run() {
for (int i = 100; i >= 1; i--) {
System.out.println(getName() + ": " + i);
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ReverseThread thread = new ReverseThread("ReverseCounter");
thread.start();
}
}
5. Write a java program to display all the vowels from a given String. Each vowel
should display after 3 seconds.
→
public class VowelDisplay extends Thread {
private String input;
public VowelDisplay(String input) {
this.input = input;
}
public void run() {
for (char ch : input.toCharArray()) {
if ("AEIOUaeiou".indexOf(ch) != -1) {
System.out.println(ch);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new VowelDisplay("Hello World").start();
}
}
Set B:
Set C:
Set A:
2. Write a java program to accept a number in the client application, send it to the
server, the server will check whether it is Armstrong or not and send results
accordingly to the client.
→
~~ Server Code
import java.io.*;
import java.net.*;
public class ArmstrongServer {
public static void main(String[] args) {
try (ServerSocket server = new ServerSocket(5000)) {
System.out.println("Server is running...");
Socket socket = server.accept();
BufferedReader br = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
int num = Integer.parseInt(br.readLine());
if (isArmstrong(num)) {
pw.println(num + " is an Armstrong number.");
} else {
pw.println(num + " is not an Armstrong number.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static boolean isArmstrong(int n) {
int temp = n, sum = 0;
while (temp != 0) {
int digit = temp % 10;
sum += digit * digit * digit;
temp /= 10;
}
return sum == n;
}
}
~~ Client Code
import java.io.*;
import java.net.*;
public class ArmstrongClient {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 5000);
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
BufferedReader serverBr = new BufferedReader(new
InputStreamReader(socket.getInputStream()))) {
System.out.print("Enter a number: ");
int num = Integer.parseInt(br.readLine());
pw.println(num);
System.out.println("Server Response: " + serverBr.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
~~ Client Code
import java.io.*;
import java.net.*;
public class HiClient {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 5000);
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true)) {
pw.println("Hi");
} catch (IOException e) {
e.printStackTrace();
}
}
}
4. Write a java program to accept a user name in the client application and greet the
user according to the time on the server machine.
→
~~ Server Code
import java.io.*;
import java.net.*;
import java.time.LocalTime;
public class GreetServer {
public static void main(String[] args) {
try (ServerSocket server = new ServerSocket(5000)) {
System.out.println("Server is running...");
Socket socket = server.accept();
BufferedReader br = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
String name = br.readLine();
LocalTime time = LocalTime.now();
String greeting = "Good ";
if (time.isBefore(LocalTime.NOON)) greeting += "Morning, ";
else if (time.isBefore(LocalTime.of(18, 0))) greeting += "Afternoon, ";
else greeting += "Evening, ";
pw.println(greeting + name);
} catch (IOException e) {
e.printStackTrace();
}
}
}
~~ Client Code
import java.io.*;
import java.net.*;
public class GreetClient {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 5000);
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
BufferedReader serverBr = new BufferedReader(new
InputStreamReader(socket.getInputStream()))) {
System.out.print("Enter your name: ");
String name = br.readLine();
pw.println(name);
System.out.println("Server Response: " + serverBr.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
5. Write a java program to accept a string in the client application and display the
vowels from that string on the server terminal.
→
~~ Server Code
import java.io.*;
import java.net.*;
public class VowelServer {
public static void main(String[] args) {
try (ServerSocket server = new ServerSocket(5000)) {
System.out.println("Server is running...");
Socket socket = server.accept();
BufferedReader br = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String input = br.readLine();
System.out.print("Vowels: ");
for (char ch : input.toCharArray()) {
if ("AEIOUaeiou".indexOf(ch) != -1) {
System.out.print(ch + " ");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
~~ Client Code
import java.io.*;
import java.net.*;
public class VowelClient {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 5000);
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true)) {
System.out.print("Enter a string: ");
String input = br.readLine();
pw.println(input);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Set B:
2. Write a java program to accept a filename in the client application and check
whether it is available on the server machine or not, if it is there then display its
contents on the client's terminal otherwise display the message "File Not Found".
(Write Client and Server applications on different terminals.)
→
~~ Server Code
import java.io.*;
import java.net.*;
public class FileServer {
public static void main(String[] args) {
try (ServerSocket server = new ServerSocket(5000)) {
System.out.println("Server is running...");
Socket socket = server.accept();
BufferedReader br = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
String filename = br.readLine();
File file = new File(filename);
if (file.exists() && file.isFile()) {
BufferedReader fileReader = new BufferedReader(new FileReader(file));
String line;
while ((line = fileReader.readLine()) != null) {
pw.println(line);
}
fileReader.close();
} else {
pw.println("File Not Found");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
~~ Client Code
import java.io.*;
import java.net.*;
public class FileClient {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 5000);
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
BufferedReader serverBr = new BufferedReader(new
InputStreamReader(socket.getInputStream()))) {
System.out.print("Enter the filename: ");
String filename = br.readLine();
pw.println(filename);
String line;
while ((line = serverBr.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Set C:
2. Write a java program to send and receive the messages from multiple terminals.
→
~~ Server Code (Supports Multiple Clients)
import java.io.*;
import java.net.*;
import java.util.concurrent.*;
public class MultiChatServer {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(10);
try (ServerSocket server = new ServerSocket(5000)) {
System.out.println("Server is running...");
while (true) {
Socket client = server.accept();
pool.execute(new ClientHandler(client));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ClientHandler implements Runnable {
private Socket client;
public ClientHandler(Socket client) {
this.client = client;
}
public void run() {
try (BufferedReader br = new BufferedReader(new
InputStreamReader(client.getInputStream()));
PrintWriter pw = new PrintWriter(client.getOutputStream(), true)) {
String msg;
while ((msg = br.readLine()) != null) {
System.out.println("Client: " + msg);
pw.println("Echo: " + msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
~~ Client Code
import java.io.*;
import java.net.*;
public class MultiChatClient {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 5000);
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
BufferedReader serverBr = new BufferedReader(new
InputStreamReader(socket.getInputStream()))) {
String msg;
while (true) {
System.out.print("You: ");
msg = br.readLine();
pw.println(msg);
System.out.println("Server: " + serverBr.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Assignment 4
Set A:
1. Design a servlet that provides information about a HTTP request from a client,
such as IP address and browser type. The servlet also provides information about
the server on which the servlet is running, such as the operating system type, and
the names of loaded servlets.
→ import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RequestInfoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Client Information
out.println("<h2>Client Information</h2>");
out.println("IP Address: " + request.getRemoteAddr() + "<br>");
out.println("Browser: " + request.getHeader("User-Agent") + "<br>");
// Server Information
out.println("<h2>Server Information</h2>");
out.println("OS: " + System.getProperty("os.name") + "<br>");
out.println("Loaded Servlets: " + this.getServletContext().getServletNames() +
"<br>");
}
}
4. Write a JSP application to accept the details of Emp (Eno, EName, Salary) and
display it in Tabular format on the browser.
→
<html>
<body>
<form method="post">
Employee No: <input type="text" name="eno" /><br>
Employee Name: <input type="text" name="ename" /><br>
Salary: <input type="text" name="salary" /><br>
<input type="submit" value="Submit" />
</form>
<%
if (request.getParameter("eno") != null) {
String eno = request.getParameter("eno");
String ename = request.getParameter("ename");
String salary = request.getParameter("salary");
out.println("<table border='1'>");
out.println("<tr><th>Eno</th><th>EName</th><th>Salary</th></tr>");
out.println("<tr><td>" + eno + "</td><td>" + ename + "</td><td>" + salary +
"</td></tr>");
out.println("</table>");
}
%>
</body>
</html>
Set B:
1. Design an HTML page which passes customer numbers to a search servlet. The
servlet searches for the customer number in a database (customer table) and
returns customer details if found the number otherwise displays an error message.
→
~~ HTML Form
<form method="post" action="CustomerSearchServlet">
Enter Customer Number: <input type="text" name="custNo" />
<input type="submit" value="Search" />
</form>
~~ Search Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CustomerSearchServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String custNo = request.getParameter("custNo");
// Assume you fetch customer details from DB (mock data here)
if (custNo.equals("123")) {
out.println("<h3>Customer Details:</h3>");
out.println("Name: John Doe<br>");
out.println("Email: john.doe@example.com<br>");
} else {
out.println("<h3>Error: Customer Not Found</h3>");
}
}
}
4. Write a JSP application to accept a username and greet the user according to the
system Time.
→
<html>
<body>
<form method="post">
Enter Username: <input type="text" name="username" />
<input type="submit" value="Greet" />
</form>
<%
if (request.getParameter("username") != null) {
String username = request.getParameter("username");
java.util.Date date = new java.util.Date();
int hours = date.getHours();
String greeting = (hours < 12) ? "Good Morning" : (hours < 18) ? "Good
Afternoon" : "Good Evening";
out.println("<h3>" + greeting + ", " + username + "!</h3>");
}
%>
</body>
</html>
Set C:
3. Write a JSP application to accept the details of Teacher (TID, TName, Salary) and
display it in tabular format.
→
<html>
<body>
<form method="post">
Teacher ID: <input type="text" name="tid" /><br>
Teacher Name: <input type="text" name="tname" /><br>
Salary: <input type="text" name="salary" /><br>
<input type="submit" value="Submit" />
</form>
<%
if (request.getParameter("tid") != null) {
String tid = request.getParameter("tid");
String tname = request.getParameter("tname");
String salary = request.getParameter("salary");
out.println("<table border='1'>");
out.println("<tr><th>TID</th><th>TName</th><th>Salary</th></tr>");
out.println("<tr><td>" + tid + "</td><td>" + tname + "</td><td>" + salary +
"</td></tr>");
out.println("</table>");
}
%>
</body>
</html>
Assignment 5
Set A:
~~ Java Code
public class Message {
private String message;
public void setMessage(String message) {
this.message = message;
}
public void display() {
System.out.println(message);
}
}
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringExample {
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("spring-config.xml");
Message msg = (Message) context.getBean("messageBean");
msg.display();
}
}
~~ Main Application
public class SpringDateExample {
public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("spring-config.xml");
DateDisplay dateDisplay = (DateDisplay) context.getBean("dateBean");
dateDisplay.displayDate();
}
}
~~ Main Application
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HelloHibernate {
public static void main(String[] args) {
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();
Greeting greeting = new Greeting();
greeting.setId(1);
greeting.setMessage("Hello");
session.save(greeting);
session.getTransaction().commit();
Greeting retrieved = session.get(Greeting.class, 1);
System.out.println("Message: " + retrieved.getMessage());
session.close();
factory.close();
}
}
Set B:
2. Design an Employee login form application using spring form MVC validation.
→
~~ Controller Class
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class LoginController {
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String showForm(Model model) {
model.addAttribute("employee", new Employee());
return "login";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String processForm(@ModelAttribute("employee") Employee employee,
Model model) {
if (employee.getUsername().equals("admin") &&
employee.getPassword().equals("password")) {
model.addAttribute("message", "Welcome, " + employee.getUsername());
return "success";
} else {
model.addAttribute("message", "Invalid Credentials");
return "login";
}
}
}
~~ JSP Files
> login.jsp
<html>
<body>
<h2>Employee Login</h2>
<form action="login" method="post">
Username: <input type="text" name="username" /><br>
Password: <input type="password" name="password" /><br>
<input type="submit" value="Login" />
</form>
<p>${message}</p>
</body>
</html>
> success.jsp
<html>
<body>
<h2>${message}</h2>
</body>
</html>