slip 1
Write a java program to scroll the text from left to right and vice versa
continuously
import javax.swing.*;
public class TextScroll extends JFrame implements Runnable {
    private JLabel label;
    private String text;
    private boolean leftToRight;
    private int scrollSpeed;
    public TextScroll(String text, int scrollSpeed) {
        super("Text Scroll");
        this.text = text;
        this.scrollSpeed = scrollSpeed;
        this.label = new JLabel(text, JLabel.CENTER);
        add(label);
        setSize(400, 100);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        leftToRight = true;
    }
    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(scrollSpeed);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (leftToRight) {
                text = text.substring(1) + text.charAt(0);
            } else {
                text = text.charAt(text.length() - 1) + text.substring(0,
text.length() - 1);
            }
            label.setText(text);
            repaint();
        }
    }
    public static void main(String[] args) {
        String text = "Scrolling Text";
        int scrollSpeed = 100; // Adjust the scroll speed here (milliseconds)
        TextScroll frame = new TextScroll(text, scrollSpeed);
        Thread t = new Thread(frame);
        t.start();
    }
}
B)B) Write a socket program in java for chatting application.(Use Swing)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class ChatApplication extends JFrame {
    private JTextArea chatArea;
    private   JTextField inputField;
    private   JButton sendButton;
    private   Socket socket;
    private   PrintWriter out;
    private   BufferedReader in;
    public ChatApplication() {
        setTitle("Chat Application");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 300);
        chatArea = new JTextArea();
        chatArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(chatArea);
        add(scrollPane, BorderLayout.CENTER);
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new BorderLayout());
        inputField = new JTextField();
        sendButton = new JButton("Send");
        sendButton.addActionListener(new SendButtonListener());
        inputPanel.add(inputField, BorderLayout.CENTER);
        inputPanel.add(sendButton, BorderLayout.EAST);
        add(inputPanel, BorderLayout.SOUTH);
        setVisible(true);
        // Connect to server
        try {
            socket = new Socket("localhost", 8888); // Change to the server's IP
address and port
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
            // Start listening for incoming messages
            new Thread(new IncomingMessageListener()).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private class SendButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String message = inputField.getText();
            out.println(message);
            chatArea.append("You: " + message + "\n");
            inputField.setText("");
        }
    }
    private class IncomingMessageListener implements Runnable {
        @Override
        public void run() {
            try {
                 String message;
                 while ((message = in.readLine()) != null) {
                     chatArea.append("Friend: " + message + "\n");
                 }
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(ChatApplication::new);
    }
}
slip 2
A) Write a JSP program to check whether given number is Perfect or not. (Use
Include
directive).
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
     <meta charset="UTF-8">
     <title>Perfect Number Checker</title>
</head>
<body>
     <h1>Perfect Number Checker</h1>
    <%
         // Function to check if a number is perfect
         boolean isPerfect(int num) {
             int sum = 0;
             for (int i = 1; i <= num / 2; i++) {
                 if (num % i == 0) {
                     sum += i;
                 }
             }
             return sum == num;
         }
         // Check if number parameter exists and is not empty
         String numberParam = request.getParameter("number");
         boolean isNumberProvided = numberParam != null && !numberParam.isEmpty();
         if (isNumberProvided) {
             int number = Integer.parseInt(numberParam);
             boolean perfect = isPerfect(number);
    %>
            <p>Number: <%= number %></p>
            <p><%= perfect ? "The number is perfect." : "The number is not
perfect." %></p>
    <%
        } else {
    %>
            <form action="" method="get">
                 Enter a number: <input type="number" name="number">
                 <input type="submit" value="Check">
            </form>
      <%
           }
      %>
</body>
</html>
B) Write a java program in multithreading using applet for drawing flag
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class FlagApplet extends Applet implements Runnable {
    private Thread animationThread;
    private int flagHeight;
    private boolean flagAnimating;
      public void init() {
          flagHeight = 100; // Set the initial height of the flag
          flagAnimating = true;
          animationThread = new Thread(this);
          animationThread.start();
      }
      public void paint(Graphics g) {
          drawFlag(g);
      }
      public void run() {
          try {
              while (flagAnimating) {
                  flagHeight += 10; // Adjust the flag's height increment
                  repaint();
                  Thread.sleep(1000); // Adjust the animation speed
              }
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      }
      private void drawFlag(Graphics g) {
          // Draw sky
          g.setColor(Color.CYAN);
          g.fillRect(0, 0, getWidth(), getHeight());
           // Draw ground
           g.setColor(Color.GREEN);
           g.fillRect(0, getHeight() - 100, getWidth(), 100);
           // Draw flag pole
           g.setColor(Color.BLACK);
           g.fillRect(100, getHeight() - flagHeight, 10, flagHeight);
           // Draw flag
           g.setColor(Color.RED);
           g.fillRect(110, getHeight() - flagHeight, 50, flagHeight / 2);
           g.setColor(Color.WHITE);
           g.fillRect(110, getHeight() - flagHeight + flagHeight / 2, 50, flagHeight /
2);
      }
    public void stop() {
        flagAnimating = false;
    }
}
slip 3
A) Write a socket program in Java to check whether given number is prime or not.
Display result on client terminal.
import java.io.*;
import java.net.*;
public class PrimeServer {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("Server started. Waiting for client...");
            Socket clientSocket = serverSocket.accept();
            System.out.println("Client connected.");
            BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                int number = Integer.parseInt(inputLine);
                boolean isPrime = isPrime(number);
                out.println(isPrime ? number + " is prime." : number + " is not
prime.");
            }
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // Function to check if a number is prime
    private static boolean isPrime(int num) {
        if (num <= 1) {
            return false;
        }
        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }
}
 client code
import java.io.*;
import java.net.*;
public class PrimeClient {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("localhost", 8888);
            BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
            System.out.print("Enter a number: ");
            String number = reader.readLine();
            out.println(number);
            String response = in.readLine();
            System.out.println("Server response: " + response);
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
     }
}
B) Write a java program using applet for bouncing ball, for each bounce color of
ball
should change randomly.
import java.applet.*;
import java.awt.*;
import java.util.Random;
public class BouncingBallApplet extends Applet implements Runnable {
    private Thread animationThread;
    private int x, y; // Position of the ball
    private int dx = 5, dy = 5; // Velocity of the ball
    private int ballSize = 50; // Diameter of the ball
    private Color ballColor;
    public void init() {
        setSize(400, 400);
        x = getWidth() / 2;
        y = getHeight() / 2;
        ballColor = getRandomColor();
        animationThread = new Thread(this);
        animationThread.start();
    }
    public void paint(Graphics g) {
        g.setColor(ballColor);
        g.fillOval(x, y, ballSize, ballSize);
    }
    public void run() {
        try {
            while (true) {
                // Move the ball
                x += dx;
                y += dy;
                // Check for collision with walls
                if (x <= 0 || x + ballSize >= getWidth()) {
                    dx = -dx; // Reverse direction horizontally
                    ballColor = getRandomColor(); // Change color
                }
                if (y <= 0 || y + ballSize >= getHeight()) {
                    dy = -dy; // Reverse direction vertically
                    ballColor = getRandomColor(); // Change color
                }
                repaint();
                Thread.sleep(50); // Adjust the animation speed
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    private Color getRandomColor() {
        Random rand = new Random();
        int r = rand.nextInt(256);
        int g = rand.nextInt(256);
        int b = rand.nextInt(256);
        return new Color(r, g, b);
    }
}
slip 4
A) Write a Java Program to delete details of students whose initial character of
their
name is ‘S’.
import java.sql.*;
public class DeleteStudents {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/your_database_name"; //
Change the database URL
    static final String USER = "your_username"; // Change the username
    static final String PASS = "your_password"; // Change the password
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("Connecting to database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            System.out.println("Creating statement...");
            stmt = conn.createStatement();
            // SQL query to delete students whose name starts with 'S'
            String sql = "DELETE FROM students WHERE name LIKE 'S%'";
            int rowsAffected = stmt.executeUpdate(sql);
            System.out.println("Rows affected: " + rowsAffected);
        } catch (SQLException se) {
            se.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException se2) {
            }
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
        System.out.println("Deletion completed.");
    }
}
B) Write a SERVLET program 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 currently loaded servlets.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Enumeration;
public class RequestInfoServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head><title>Request Information</title></head>");
        out.println("<body>");
        // Client information
        out.println("<h2>Client Information:</h2>");
        out.println("<p>IP Address: " + request.getRemoteAddr() + "</p>");
        out.println("<p>Browser Type: " + request.getHeader("User-Agent") +
"</p>");
        // Server information
        out.println("<h2>Server Information:</h2>");
        out.println("<p>Server Name: " + request.getServerName() + "</p>");
        out.println("<p>Server Port: " + request.getServerPort() + "</p>");
        out.println("<p>Server Software: " + getServletContext().getServerInfo() +
"</p>");
        // Servlet information
        out.println("<h2>Servlet Information:</h2>");
        Enumeration<String> servletNames = getServletContext().getServletNames();
        while (servletNames.hasMoreElements()) {
            out.println("<p>Servlet Name: " + servletNames.nextElement() + "</p>");
        }
        out.println("</body></html>");
        out.close();
    }
}
slip 5
A) Write a JSP program to calculate sum of first and last digit of a given number.
Display sum in Red Color with font size 18.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
     <meta charset="UTF-8">
     <title>Sum of First and Last Digit</title>
</head>
<body>
     <h1>Sum of First and Last Digit</h1>
     <%!
           // Function to calculate sum of first and last digits
           int sumOfFirstAndLastDigit(int number) {
               if (number < 10) {
                   return number * 2; // If number has only one digit, sum is twice of
it
               } else {
                   int lastDigit = number % 10;
                   int firstDigit = 0;
                   while (number >= 10) {
                        number /= 10;
                        firstDigit = number;
                   }
                   return firstDigit + lastDigit;
               }
           }
     %>
     <%
           int inputNumber = Integer.parseInt(request.getParameter("number"));
           int sum = sumOfFirstAndLastDigit(inputNumber);
     %>
    <p style="color: red; font-size: 18px;">Sum of first and last digit of <%=
inputNumber %> is <%= sum %></p>
</body>
</html>
B) Write a java program in multithreading using applet for Traffic signal
import java.applet.*;
import java.awt.*;
public class TrafficSignalApplet extends Applet implements Runnable {
    private Thread animationThread;
    private int currentSignal = 0; // 0: Red, 1: Green, 2: Yellow
    private final int[] signalDurations = {5000, 7000, 2000}; // Duration of each
signal in milliseconds
     public void init() {
         setSize(100, 300);
         animationThread = new Thread(this);
         animationThread.start();
     }
    public void paint(Graphics g) {
        g.setColor(Color.BLACK);
        g.fillRect(45, 30, 10, 240); // Pole
        g.setColor(Color.RED);
        g.fillOval(30, 30, 40, 40); // Red
        g.setColor(Color.GREEN);
        g.fillOval(30, 90, 40, 40); // Green
        g.setColor(Color.YELLOW);
        g.fillOval(30, 150, 40, 40); // Yellow
    }
    public void run() {
        try {
            while (true) {
                Thread.sleep(signalDurations[currentSignal]);
                currentSignal = (currentSignal + 1) % 3;
                repaint();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
slip 6
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BlinkingImage extends JFrame implements Runnable {
    private JLabel imageLabel;
    private ImageIcon imageIcon;
    private boolean blinking;
    public BlinkingImage() {
        setTitle("Blinking Image");
        setSize(300, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        imageIcon = new ImageIcon("image.jpg"); // Change "image.jpg" to your image
file path
        imageLabel = new JLabel(imageIcon);
        add(imageLabel, BorderLayout.CENTER);
        blinking = true;
        Thread thread = new Thread(this);
        thread.start();
    }
    @Override
    public void run() {
        try {
            while (blinking) {
                Thread.sleep(500); // Blinking interval in milliseconds
                imageLabel.setVisible(!imageLabel.isVisible());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            BlinkingImage frame = new BlinkingImage();
            frame.setVisible(true);
        });
    }
}
B) Write a SERVLET program which counts how many times a user has visited a web
  page. If user is visiting the page for the first time, display a welcome message.
If the
  user is revisiting the page, display the number of times visited. (Use Cookie)
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/VisitCounterServlet")
public class VisitCounterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
        // Get the cookies from the request
        Cookie[] cookies = request.getCookies();
        int visitCount = 0;
        // Check if cookies exist
        if (cookies != null) {
            // Look for a cookie named "visitCount"
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("visitCount")) {
                    // If found, retrieve the value and parse it to an integer
                    visitCount = Integer.parseInt(cookie.getValue());
                    break;
                }
            }
        }
        // Increase visit count by 1
        visitCount++;
        // Create a new cookie to store the visit count
        Cookie visitCookie = new Cookie("visitCount", String.valueOf(visitCount));
        // Set the cookie's max age to 1 day (in seconds)
        visitCookie.setMaxAge(24 * 60 * 60); // 1 day in seconds
        response.addCookie(visitCookie);
        // Set the response content type
        response.setContentType("text/html");
        // Write the response message
        response.getWriter().println("<html><head><title>Visit Counter
Servlet</title></head><body>");
        // Check if it's the first visit
        if (visitCount == 1) {
            response.getWriter().println("<h2>Welcome! This is your first
visit.</h2>");
        } else {
            response.getWriter().println("<h2>You have visited this page " +
visitCount + " times.</h2>");
        }
           response.getWriter().println("</body></html>");
      }
}
slip 7
A) Write a JSP script to validate given E-Mail ID.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
     <meta charset="UTF-8">
     <title>Email Validation</title>
</head>
<body>
     <h1>Email Validation</h1>
      <%
           String email = request.getParameter("email");
           boolean isValid = validateEmail(email);
      %>
      <% if (isValid) { %>
          <p>The email <%= email %> is valid.</p>
      <% } else { %>
          <p>The email <%= email %> is not valid.</p>
      <% } %>
</body>
</html>
<%!
    // Function to validate email
    boolean validateEmail(String email) {
        if (email == null || email.isEmpty()) {
            return false;
        } else {
            // Regex pattern for email validation
            String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-
zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
            return email.matches(emailRegex);
        }
    }
%>
B) Write a Multithreading program in java to display the number’s between 1 to 100
 continuously in a TextField by clicking on button. (use Runnable Interface).
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NumberDisplay extends JFrame {
private JTextField textField;
private JButton startButton;
private volatile boolean running;
public NumberDisplay() {
    setTitle("Number Display");
    setSize(300, 100);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    textField = new JTextField(20);
    textField.setEditable(false);
    startButton = new JButton("Start");
    startButton.addActionListener(new StartButtonListener());
    JPanel panel = new JPanel();
    panel.add(textField);
    panel.add(startButton);
    add(panel);
    setVisible(true);
}
private class NumberRunnable implements Runnable {
    @Override
    public void run() {
        try {
            for (int i = 1; i <= 100; i++) {
                if (!running) {
                    return;
                }
                SwingUtilities.invokeLater(() -> {
                    textField.setText(String.valueOf(i));
                });
                Thread.sleep(1000); // Adjust the interval as needed
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
private class StartButtonListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        if (!running) {
            running = true;
            Thread numberThread = new Thread(new NumberRunnable());
            numberThread.start();
            startButton.setText("Stop");
        } else {
            running = false;
            startButton.setText("Start");
        }
    }
}
public static void main(String[] args) {
    SwingUtilities.invokeLater(NumberDisplay::new);
     }
}
slip 8
A) Write a Java Program to display all the employee names whose initial character
of a
  name is ‘A’.
import java.sql.*;
public class EmployeeNamesWithAJDBC {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/your_database_name"; //
Change the database URL
    static final String USER = "your_username"; // Change the username
    static final String PASS = "your_password"; // Change the password
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("Connecting to database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            System.out.println("Creating statement...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT * FROM employees WHERE name LIKE 'A%'";
            ResultSet rs = stmt.executeQuery(sql);
            System.out.println("Employee names whose initial character is 'A':");
            while (rs.next()) {
                String name = rs.getString("name");
                System.out.println(name);
            }
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException se) {
            se.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException se2) {
            }
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
        System.out.println("Query executed successfully.");
    }
}
B) Write a java program in multithreading using applet for Digital watch.
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.text.*;
public class DigitalWatchApplet extends Applet implements Runnable {
    private Thread thread;
    private volatile boolean running;
    public void init() {
        setSize(200, 100);
        thread = new Thread(this);
        running = true;
        thread.start();
    }
    public void run() {
        try {
            while (running) {
                repaint();
                Thread.sleep(1000); // Update time every second
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public void paint(Graphics g) {
        // Get the current time
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        String time = dateFormat.format(date);
        // Display the time on the applet
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setColor(Color.WHITE);
        g.setFont(new Font("Arial", Font.BOLD, 20));
        g.drawString(time, 50, 50);
    }
    public void stop() {
        running = false;
    }
}
slip 9
A) Write a Java Program to create a Emp (ENo, EName, Sal) table and insert record
into it. (Use PreparedStatement Interface)
import java.sql.*;
public class InsertEmpRecord {
    // JDBC URL, username, and password
    static final String JDBC_URL =
"jdbc:mysql://localhost:3306/your_database_name"; // Change the database URL
    static final String USER = "your_username"; // Change the username
    static final String PASS = "your_password"; // Change the password
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            // Register JDBC driver
            Class.forName("com.mysql.jdbc.Driver");
            // Open a connection
            System.out.println("Connecting to database...");
            conn = DriverManager.getConnection(JDBC_URL, USER, PASS);
            // Create SQL query to create Emp table
            String createTableSQL = "CREATE TABLE IF NOT EXISTS Emp (" +
                    "ENo INT AUTO_INCREMENT PRIMARY KEY," +
                    "EName VARCHAR(255)," +
                    "Sal DOUBLE)";
            // Create table
            Statement stmt = conn.createStatement();
            stmt.executeUpdate(createTableSQL);
            System.out.println("Emp table created successfully");
            // SQL query to insert record into Emp table
            String insertSQL = "INSERT INTO Emp (EName, Sal) VALUES (?, ?)";
            // Create PreparedStatement object
            pstmt = conn.prepareStatement(insertSQL);
            // Set parameters for PreparedStatement
            pstmt.setString(1, "John");
            pstmt.setDouble(2, 50000);
            // Execute PreparedStatement to insert record
            pstmt.executeUpdate();
            System.out.println("Record inserted successfully");
        } catch (SQLException se) {
            se.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Close resources
            try {
                if (pstmt != null) pstmt.close();
            } catch (SQLException se) {
            }
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }
}
B) Write a JSP program to create an online shopping mall. User must be allowed to
do
purchase from two pages. Each page should have a page total. The third page should
display a bill, which consists of a page total of whatever the purchase has been
done
and print the total. (Use Session)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
     <meta charset="UTF-8">
     <title>Online Shopping Mall</title>
</head>
<body>
     <h1>Page 1: Products</h1>
     <form action="Page2.jsp" method="post">
         <label>Product 1: $10</label><br>
         <input type="checkbox" name="product1" value="10"><br>
         <label>Product 2: $20</label><br>
         <input type="checkbox" name="product2" value="20"><br>
         <input type="submit" value="Next">
     </form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
     <meta charset="UTF-8">
     <title>Online Shopping Mall</title>
</head>
<body>
     <h1>Page 2: Products</h1>
     <form action="Page3.jsp" method="post">
         <label>Product 3: $30</label><br>
         <input type="checkbox" name="product3" value="30"><br>
         <label>Product 4: $40</label><br>
         <input type="checkbox" name="product4" value="40"><br>
         <input type="submit" value="Checkout">
     </form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
     <meta charset="UTF-8">
     <title>Online Shopping Mall - Bill</title>
</head>
<body>
     <h1>Bill</h1>
     <%
         // Retrieve selected products from session
         String product1 = (String) session.getAttribute("product1");
         String product2 = (String) session.getAttribute("product2");
         String product3 = (String) session.getAttribute("product3");
         String product4 = (String) session.getAttribute("product4");
        // Calculate total
        int total = Integer.parseInt(product1 != null ? product1 : "0") +
                    Integer.parseInt(product2 != null ? product2 : "0") +
                    Integer.parseInt(product3 != null ? product3 : "0") +
                    Integer.parseInt(product4 != null ? product4 : "0");
    %>
    <p>Product 1: $<%= product1 != null   ?   product1   :   "0"   %></p>
    <p>Product 2: $<%= product2 != null   ?   product2   :   "0"   %></p>
    <p>Product 3: $<%= product3 != null   ?   product3   :   "0"   %></p>
    <p>Product 4: $<%= product4 != null   ?   product4   :   "0"   %></p>
    <h2>Total: $<%= total %></h2>
</body>
</html>
slip 10
A) Write a java Program in Hibernate to   display “Hello world” message.
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class HelloWorldDAO {
    public static void main(String[] args) {
        // Create configuration object
        Configuration cfg = new Configuration().configure();
        // Create session factory
        SessionFactory sessionFactory = cfg.buildSessionFactory();
        // Create session
        Session session = sessionFactory.openSession();
        // Begin transaction
        Transaction tx = session.beginTransaction();
        // Display "Hello world" message
        System.out.println("Hello world");
        // Commit transaction
        tx.commit();
        // Close session
        session.close();
    }
}
B) Write a SERVLET program to display the details of Product (ProdCode, PName,
Price) on the browser in tabular format. (Use database)
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/ProductDetailsServlet")
public class ProductDetailsServlet extends HttpServlet {
    private static final String JDBC_URL =
"jdbc:mysql://localhost:3306/your_database_name"; // Change the database URL
    private static final String USER = "your_username"; // Change the username
    private static final String PASS = "your_password"; // Change the password
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // Establish database connection
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(JDBC_URL, USER, PASS);
            // Execute SQL query to fetch product details
            stmt = conn.createStatement();
            String sql = "SELECT ProdCode, PName, Price FROM Product";
            rs = stmt.executeQuery(sql);
            // Generate HTML table to display product details
            out.println("<html>");
            out.println("<head><title>Product Details</title></head>");
            out.println("<body>");
            out.println("<h2>Product Details</h2>");
            out.println("<table border='1'>");
            out.println("<tr><th>ProdCode</th><th>PName</th><th>Price</th></tr>");
            while (rs.next()) {
                out.println("<tr>");
                out.println("<td>" + rs.getString("ProdCode") + "</td>");
                out.println("<td>" + rs.getString("PName") + "</td>");
                out.println("<td>" + rs.getDouble("Price") + "</td>");
                out.println("</tr>");
            }
            out.println("</table>");
            out.println("</body>");
            out.println("</html>");
        } catch (SQLException se) {
            se.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }
}
slip 11
A) Write a java program to display IPAddress and name of client machine
import java.net.*;
public class ClientInfo {
    public static void main(String[] args) {
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            System.out.println("IP Address: " + localHost.getHostAddress());
            System.out.println("Client Machine Name: " + localHost.getHostName());
        } catch (UnknownHostException e) {
            System.err.println("Error occurred while retrieving client information:
" + e.getMessage());
        }
    }
}
B) Write a Java program to display sales details of Product (PID, PName, Qty, Rate,
Amount) between two selected dates. (Assume Sales table is already created).
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class SalesDetailsBetweenDates {
    static final String JDBC_URL =
"jdbc:mysql://localhost:3306/your_database_name"; // Change the database URL
    static final String USER = "your_username"; // Change the username
    static final String PASS = "your_password"; // Change the password
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            // Register JDBC driver
            Class.forName("com.mysql.jdbc.Driver");
            // Open a connection
            System.out.println("Connecting to database...");
            conn = DriverManager.getConnection(JDBC_URL, USER, PASS);
            // Prepare SQL query to select sales details between two dates
            String sql = "SELECT PID, PName, Qty, Rate, Qty * Rate AS Amount FROM
Sales WHERE SalesDate BETWEEN ? AND ?";
            pstmt = conn.prepareStatement(sql);
            // Set parameters for the PreparedStatement
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            java.util.Date startDate = dateFormat.parse("2024-01-01"); // Change
the start date
            java.util.Date endDate = dateFormat.parse("2024-12-31"); // Change the
end date
            pstmt.setDate(1, new java.sql.Date(startDate.getTime()));
            pstmt.setDate(2, new java.sql.Date(endDate.getTime()));
            // Execute the query
            rs = pstmt.executeQuery();
            // Print the sales details
            System.out.println("Sales details between " + startDate + " and " +
endDate + ":");
            System.out.println("PID\tPName\tQty\tRate\tAmount");
            while (rs.next()) {
                int PID = rs.getInt("PID");
                String PName = rs.getString("PName");
                int Qty = rs.getInt("Qty");
                double Rate = rs.getDouble("Rate");
                double Amount = rs.getDouble("Amount");
                System.out.println(PID + "\t" + PName + "\t" + Qty + "\t" + Rate +
"\t" + Amount);
            }
        } catch (SQLException se) {
            se.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Close resources
            try {
                if (rs != null) rs.close();
                if (pstmt != null) pstmt.close();
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }
}
slip 12
A) Write a java program to count the number of records in a table
import java.sql.*;
public class CountRecords {
    static final String JDBC_URL =
"jdbc:mysql://localhost:3306/your_database_name"; // Change the database URL
    static final String USER = "your_username"; // Change the username
    static final String PASS = "your_password"; // Change the password
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // Register JDBC driver
            Class.forName("com.mysql.jdbc.Driver");
            // Open a connection
            System.out.println("Connecting to database...");
            conn = DriverManager.getConnection(JDBC_URL, USER, PASS);
            // Execute SQL query to count the number of records in a table
            stmt = conn.createStatement();
            String sql = "SELECT COUNT(*) AS recordCount FROM YourTableName"; //
Replace YourTableName with your actual table name
            rs = stmt.executeQuery(sql);
            // Retrieve and print the record count
            if (rs.next()) {
                int recordCount = rs.getInt("recordCount");
                System.out.println("Number of records in the table: " +
recordCount);
            }
        } catch (SQLException se) {
            se.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // Close resources
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }
}
B) Write a program in java which will show lifecycle (creation, sleep, and dead) of
a
thread. Program should print randomly the name of thread and value of sleep time.
The
name of the thread should be hard coded through constructor. The sleep time of a
thread
will be a random integer in the range 0 to 4999.
import java.util.Random;
public class ThreadLifecycleDemo {
    public static void main(String[] args) {
        // Create and start a new thread
        MyThread thread = new MyThread("Thread 1");
        thread.start();
    }
    static class MyThread extends Thread {
        public MyThread(String name) {
            super(name);
        }
        @Override
        public void run() {
            try {
                System.out.println(getName() + " is created.");
                Random random = new Random();
                int sleepTime = random.nextInt(5000); // Generate random sleep time
between 0 to 4999 milliseconds
                System.out.println(getName() + " will sleep for " + sleepTime + "
milliseconds.");
                Thread.sleep(sleepTime); // Sleep for the generated random time
                System.out.println(getName() + " is dead.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
slip 13
A) Write a java program to display name of currently executing Thread in
multithreading.
public class CurrentThreadDemo {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new MyRunnable(), "Thread 1");
        Thread thread2 = new Thread(new MyRunnable(), "Thread 2");
        thread1.start();
        thread2.start();
    }
    static class MyRunnable implements Runnable {
        @Override
        public void run() {
            String threadName = Thread.currentThread().getName();
            System.out.println("Currently executing thread: " + threadName);
        }
    }
}
B) Write a JSP program to display the details of College (CollegeID, Coll_Name,
Address) in tabular form on browser.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
     <meta charset="UTF-8">
     <title>College Details</title>
</head>
<body>
     <h1>College Details</h1>
     <table border="1">
         <tr>
              <th>CollegeID</th>
              <th>College Name</th>
              <th>Address</th>
         </tr>
         <%
              try {
                  // Load the MySQL JDBC driver
                  Class.forName("com.mysql.jdbc.Driver");
                // Establish the database connection
                Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database_name",
"your_username", "your_password");
                // Prepare SQL query
                String sql = "SELECT CollegeID, Coll_Name, Address FROM College";
                PreparedStatement pstmt = conn.prepareStatement(sql);
                // Execute the query
                ResultSet rs = pstmt.executeQuery();
                // Iterate through the result set and display the details in the
table
                while (rs.next()) {
                    out.println("<tr>");
                    out.println("<td>" + rs.getInt("CollegeID") + "</td>");
                    out.println("<td>" + rs.getString("Coll_Name") + "</td>");
                    out.println("<td>" + rs.getString("Address") + "</td>");
                    out.println("</tr>");
                }
                // Close the resources
                rs.close();
                pstmt.close();
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
         %>
     </table>
</body>
</html>
slip 14
A) Write a JSP program to accept Name and Age of Voter and check whether he is
eligible for voting or not.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
     <meta charset="UTF-8">
     <title>Voter Eligibility Result</title>
</head>
<body>
     <h1>Voter Eligibility Result</h1>
     <%
         // Retrieve name and age parameters from the request
         String name = request.getParameter("name");
         int age = Integer.parseInt(request.getParameter("age"));
        // Check eligibility based on age
        String message;
        if (age >= 18) {
            message = "Congratulations, " + name + "! You are eligible for
voting.";
        } else {
            message = "Sorry, " + name + ". You are not eligible for voting.";
        }
    %>
    <p><%= message %></p>
</body>
</html>
B) Write a Java program to display given extension files from a specific directory
on
 server machine.
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class ListFilesByExtension {
    public static void main(String[] args) {
        String directoryPath = "your_directory_path"; // Change the directory path
        String extension = ".txt"; // Change the file extension
        List<String> filesWithExtension = listFilesByExtension(directoryPath,
extension);
        System.out.println("Files with extension '" + extension + "' in directory
'" + directoryPath + "':");
        for (String file : filesWithExtension) {
            System.out.println(file);
        }
    }
    public static List<String> listFilesByExtension(String directoryPath, String
extension) {
        List<String> filesWithExtension = new ArrayList<>();
        File directory = new File(directoryPath);
        // Check if directory exists and is a directory
        if (directory.exists() && directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                 for (File file : files) {
                     // Check if file is a regular file and has the specified
extension
                     if (file.isFile() && file.getName().endsWith(extension)) {
                         filesWithExtension.add(file.getName());
                     }
                 }
            }
        } else {
            System.out.println("Directory does not exist or is not a directory.");
        }
        return filesWithExtension;
    }
}
slip 15
A) Write a java program to display each alphabet after 2 seconds between ‘a’ to ‘z’
public class DisplayAlphabets {
    public static void main(String[] args) {
        for (char ch = 'a'; ch <= 'z'; ch++) {
            printWithDelay(ch);
        }
    }
    public static void printWithDelay(final char ch) {
        new Thread(() -> {
            try {
                Thread.sleep(2000); // Delay for 2 seconds
                System.out.println(ch);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
B) Write a Java program to accept the details of Student (RNo, SName, Per, Gender,
Class) and store into the database. (Use appropriate Swing Components and
PreparedStatement Interface).
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class StudentDetailsForm extends JFrame implements ActionListener {
    private JTextField txtRNo, txtSName, txtPer, txtGender, txtClass;
    private JButton btnSave;
    public StudentDetailsForm() {
        setTitle("Student Details Form");
        setSize(400, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(6, 2));
        panel.add(new JLabel("Roll Number:"));
        txtRNo = new JTextField();
        panel.add(txtRNo);
        panel.add(new JLabel("Student Name:"));
        txtSName = new JTextField();
        panel.add(txtSName);
        panel.add(new JLabel("Percentage:"));
        txtPer = new JTextField();
        panel.add(txtPer);
        panel.add(new JLabel("Gender:"));
        txtGender = new JTextField();
        panel.add(txtGender);
        panel.add(new JLabel("Class:"));
        txtClass = new JTextField();
        panel.add(txtClass);
        btnSave = new JButton("Save");
        btnSave.addActionListener(this);
        panel.add(btnSave);
        add(panel);
        setVisible(true);
    }
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == btnSave) {
            saveStudentDetails();
        }
    }
    private void saveStudentDetails() {
        String RNo = txtRNo.getText();
        String SName = txtSName.getText();
        String Per = txtPer.getText();
        String Gender = txtGender.getText();
        String Class = txtClass.getText();
        try {
            // Establish database connection
            Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database_name",
"your_username", "your_password");
            // Prepare SQL query
            String sql = "INSERT INTO Student (RNo, SName, Per, Gender, Class)
VALUES (?, ?, ?, ?, ?)";
            PreparedStatement pstmt = conn.prepareStatement(sql);
             // Set parameters
             pstmt.setString(1,   RNo);
             pstmt.setString(2,   SName);
             pstmt.setString(3,   Per);
             pstmt.setString(4,   Gender);
             pstmt.setString(5,   Class);
            // Execute the query
            int rowsInserted = pstmt.executeUpdate();
            if (rowsInserted > 0) {
                 JOptionPane.showMessageDialog(this, "Student details saved
successfully.");
                 clearFields();
            } else {
                 JOptionPane.showMessageDialog(this, "Failed to save student
details.");
            }
             // Close resources
             pstmt.close();
             conn.close();
         } catch (SQLException ex) {
             ex.printStackTrace();
             JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());
         }
     }
     private void clearFields() {
         txtRNo.setText("");
         txtSName.setText("");
         txtPer.setText("");
         txtGender.setText("");
         txtClass.setText("");
     }
     public static void main(String[] args) {
         new StudentDetailsForm();
     }
}
slip 16
A) Write a JSP script to accept username and password from user, if they are same
then
display “Login Successfully” message in Login.html file, otherwise display “Login
Failed” Message in Error.html file.
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%
     // Retrieve username and password from request parameters
     String username = request.getParameter("username");
     String password = request.getParameter("password");
     // Check if username and password are the same
     if (username != null && password != null && username.equals(password)) {
         // Redirect to Login.html with "Login Successfully" message
         response.sendRedirect("Login.html?message=Login%20Successfully");
     } else {
        // Redirect to Error.html with "Login Failed" message
        response.sendRedirect("Error.html?message=Login%20Failed");
    }
%>
B) Write a Java program to accept the details of students (rno, sname, per) at
least 5
Records, store it into database and display the details of student having highest
percentage. (Use PreparedStatement Interface)
import java.sql.*;
public class StudentDetails {
    static final String JDBC_URL =
"jdbc:mysql://localhost:3306/your_database_name"; // Change the database URL
    static final String USER = "your_username"; // Change the username
    static final String PASS = "your_password"; // Change the password
    public static void main(String[] args) {
        try {
            // Establish database connection
            Connection conn = DriverManager.getConnection(JDBC_URL, USER, PASS);
            // Insert student details into database
            insertStudentDetails(conn);
            // Display details of student with highest percentage
            displayHighestPercentageStudent(conn);
            // Close connection
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    private static void insertStudentDetails(Connection conn) throws SQLException {
        // Prepare SQL query
        String sql = "INSERT INTO Student (RNo, SName, Per) VALUES (?, ?, ?)";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        // Student details (you can modify these or get them from user input)
        Object[][] studentDetails = {
            {101, "John", 85.5},
            {102, "Alice", 91.2},
            {103, "Bob", 78.9},
            {104, "Emily", 89.6},
            {105, "Michael", 95.3}
        };
        // Insert each student's details into the database
        for (Object[] student : studentDetails) {
            pstmt.setInt(1, (int) student[0]); // RNo
            pstmt.setString(2, (String) student[1]); // SName
            pstmt.setDouble(3, (double) student[2]); // Per
            pstmt.executeUpdate();
        }
        System.out.println("Student details inserted successfully.");
        pstmt.close();
    }
    private static void displayHighestPercentageStudent(Connection conn) throws
SQLException {
        // Prepare SQL query to find student with highest percentage
        String sql = "SELECT RNo, SName, Per FROM Student WHERE Per = (SELECT
MAX(Per) FROM Student)";
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        // Display details of student with highest percentage
        if (rs.next()) {
            System.out.println("\nDetails of student with highest percentage:");
            System.out.println("Roll Number: " + rs.getInt("RNo"));
            System.out.println("Student Name: " + rs.getString("SName"));
            System.out.println("Percentage: " + rs.getDouble("Per"));
        } else {
            System.out.println("\nNo student records found.");
        }
        rs.close();
        stmt.close();
    }
}
slip 17
A) Write a java program to accept a String from user and display each vowel from a
String after 3 seconds.
import java.util.Scanner;
public class DisplayVowels {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String input = scanner.nextLine();
        for (int i = 0; i < input.length(); i++)   {
            char ch = input.charAt(i);
            if (isVowel(ch)) {
                System.out.println("Vowel found:   " + ch);
                try {
                    Thread.sleep(3000); // Sleep   for 3 seconds
                } catch (InterruptedException e)   {
                    e.printStackTrace();
                }
            }
        }
    }
     private static boolean isVowel(char ch) {
         ch = Character.toLowerCase(ch); // Convert to lowercase to handle both
upper and lower case vowels
         return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
     }
}
B) Write a Java program to check whether given file is present on server or not, if
it is
  there then display its contents on client’s terminal otherwise display the message
“File
  Not Found”.
import java.io.*;
import java.net.*;
public class Server {
    public static void main(String[] args) {
        int portNumber = 12345; // Change to your desired port number
        try {
            ServerSocket serverSocket = new ServerSocket(portNumber);
            System.out.println("Server is running...");
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("Client connected.");
                BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
                PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
                String fileName = in.readLine();
                File file = new File(fileName);
                if (file.exists()) {
                    out.println("File found.");
                    BufferedReader fileReader = new BufferedReader(new
FileReader(file));
                    String line;
                    while ((line = fileReader.readLine()) != null) {
                         out.println(line);
                    }
                    fileReader.close();
                } else {
                    out.println("File not found.");
                }
                clientSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.*;
import java.net.*;
public class Client {
    public static void main(String[] args) {
         String serverAddress = "localhost"; // Change to the server's IP address or
hostname
         int portNumber = 12345; // Change to the server's port number
        try {
            Socket socket = new Socket(serverAddress, portNumber);
            BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
            System.out.print("Enter file name: ");
            String fileName = userInput.readLine();
            out.println(fileName);
            String response;
            while ((response = in.readLine()) != null) {
                if (response.equals("File found.")) {
                    System.out.println("File contents:");
                    String line;
                    while ((line = in.readLine()) != null) {
                        System.out.println(line);
                    }
                } else if (response.equals("File not found.")) {
                    System.out.println("File not found.");
                }
            }
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
slip 18
A) Write a java program to calculate factorial of a number. (Use sleep () method).
public class FactorialCalculator {
    public static void main(String[] args) {
        int number = 5; // Change this to the desired number
        System.out.println("Calculating factorial of " + number + "...");
        long factorial = calculateFactorial(number);
        System.out.println("Factorial of " + number + " is: " + factorial);
    }
    public static long calculateFactorial(int n) {
        long result = 1;
        for (int i = 1; i <= n; i++) {
            result *= i;
            // Add a short delay after each step
            try {
                Thread.sleep(500); // Sleep for 500 milliseconds (0.5 seconds)
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
B) Write a java program for simple standalone chatting application.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class ChatServer {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(5000);
            System.out.println("Server started. Waiting for client to connect...");
              Socket clientSocket = serverSocket.accept();
              System.out.println("Client connected.");
            BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
            BufferedReader consoleInput = new BufferedReader(new
InputStreamReader(System.in));
            String clientMessage, serverMessage;
              while (true) {
                  // Read client's message
                  clientMessage = in.readLine();
                  if (clientMessage.equals("exit")) {
                      break;
                  }
                  System.out.println("Client: " + clientMessage);
                  // Send server's message
                  System.out.print("You: ");
                  serverMessage = consoleInput.readLine();
                  out.println(serverMessage);
                  if (serverMessage.equals("exit")) {
                      break;
                  }
              }
              serverSocket.close();
              clientSocket.close();
          } catch (IOException e) {
              e.printStackTrace();
          }
    }
}
import   java.io.BufferedReader;
import   java.io.IOException;
import   java.io.InputStreamReader;
import   java.io.PrintWriter;
import   java.net.Socket;
public class ChatClient {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("localhost", 5000);
            BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader consoleInput = new BufferedReader(new
InputStreamReader(System.in));
            String serverMessage, clientMessage;
            while (true) {
                // Send client's message
                System.out.print("You: ");
                clientMessage = consoleInput.readLine();
                out.println(clientMessage);
                if (clientMessage.equals("exit")) {
                    break;
                }
                // Read server's message
                serverMessage = in.readLine();
                if (serverMessage.equals("exit")) {
                    break;
                }
                System.out.println("Server: " + serverMessage);
            }
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
     }
}
slip 19
A) Write a JSP program which accept UserName in a TextBox and greets the user
according to the time on server machine.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
     <meta charset="UTF-8">
     <title>Greeting Page</title>
</head>
<body>
     <h1>Greeting Page</h1>
    <%-- Get the current hour of the day --%>
    <% java.util.Calendar calendar = java.util.Calendar.getInstance();
       int hour = calendar.get(java.util.Calendar.HOUR_OF_DAY);
    %>
    <%-- Get the username from the form --%>
    <% String userName = request.getParameter("username");
       if (userName == null || userName.trim().isEmpty()) {
           userName = "Guest";
       }
    %>
    <%-- Generate the greeting message based on the current hour --%>
    <% String greetingMessage = "";
       if (hour >= 0 && hour < 12) {
           greetingMessage = "Good morning, " + userName + "!";
       } else if (hour >= 12 && hour < 18) {
           greetingMessage = "Good afternoon, " + userName + "!";
       } else {
             greetingMessage = "Good evening, " + userName + "!";
         }
    %>
    <p><%= greetingMessage %></p>
     <form action="GreetingPage.jsp" method="post">
         <label for="username">Enter your name:</label>
         <input type="text" id="username" name="username">
         <input type="submit" value="Submit">
     </form>
</body>
</html>
B) Write a Java program to display first record from student table (rno, sname,
per)
onto the TextFields by clicking on button. (Assume Student table is already
created).import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class DisplayFirstRecord extends JFrame {
    private JTextField txtRNo, txtSName, txtPer;
    private JButton btnDisplay;
    public DisplayFirstRecord() {
        setTitle("Display First Record");
        setSize(300, 150);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
          JPanel panel = new JPanel();
          panel.setLayout(new GridLayout(4, 2));
          panel.add(new JLabel("Roll Number:"));
          txtRNo = new JTextField();
          panel.add(txtRNo);
          panel.add(new JLabel("Student Name:"));
          txtSName = new JTextField();
          panel.add(txtSName);
          panel.add(new JLabel("Percentage:"));
          txtPer = new JTextField();
          panel.add(txtPer);
          btnDisplay = new JButton("Display First Record");
          btnDisplay.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  displayFirstRecord();
              }
          });
          panel.add(btnDisplay);
          add(panel);
          setVisible(true);
    }
    private void displayFirstRecord() {
        try {
            // Establish database connection
            Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database_name",
"your_username", "your_password");
            // Prepare SQL query to fetch the first record from student table
            String sql = "SELECT * FROM Student LIMIT 1";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            // Display first record onto text fields
            if (rs.next()) {
                txtRNo.setText(rs.getString("rno"));
                txtSName.setText(rs.getString("sname"));
                txtPer.setText(rs.getString("per"));
            } else {
                JOptionPane.showMessageDialog(this, "No records found in the
student table.");
            }
            // Close resources
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());
        }
    }
    public static void main(String[] args) {
        new DisplayFirstRecord();
    }
}
slip 20
A) Write a JDBC program to delete the details of given employee (ENo EName
Salary). Accept employee ID through command line.
import java.sql.*;
public class DeleteEmployeeDetails {
    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("Usage: java DeleteEmployeeDetails <employee_id>");
            return;
        }
        int employeeId = Integer.parseInt(args[0]);
        try {
            // Establish database connection
            Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database_name",
"your_username", "your_password");
            // Prepare SQL query to delete employee details based on employee ID
            String sql = "DELETE FROM Employee WHERE ENo = ?";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, employeeId);
            // Execute the query
            int rowsAffected = pstmt.executeUpdate();
            if (rowsAffected > 0) {
                System.out.println("Employee details deleted successfully.");
            } else {
                System.out.println("No employee found with ID " + employeeId);
            }
            // Close resources
            pstmt.close();
            conn.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
}
B) Write a java program in multithreading using applet for drawing temple
import java.applet.*;
import java.awt.*;
public class TempleApplet extends Applet {
    public void paint(Graphics g) {
        // Draw temple base
        g.setColor(Color.YELLOW);
        g.fillRect(100, 200, 200, 200);
        // Draw temple pillars
        g.setColor(Color.GRAY);
        g.fillRect(120, 150, 50, 200);
        g.fillRect(230, 150, 50, 200);
        // Draw temple roof
        int[] xPoints = {100, 300, 200};
        int[] yPoints = {200, 200, 50};
        g.setColor(Color.RED);
        g.fillPolygon(xPoints, yPoints, 3);
        // Draw temple door
        g.setColor(Color.BLUE);
        g.fillRect(180, 300, 40, 100);
    }
}
slip 21
A) Write a java program to display name and priority of a Thread.
public class ThreadInfo {
    public static void main(String[] args) {
        // Create a new thread
        Thread thread = new Thread(() -> {
            // Display name and priority of the thread
            System.out.println("Thread Name: " + Thread.currentThread().getName());
            System.out.println("Thread Priority: " +
Thread.currentThread().getPriority());
        });
        // Set name and priority of the thread
        thread.setName("CustomThread");
        thread.setPriority(Thread.NORM_PRIORITY);
        // Start the thread
        thread.start();
    }
}
B) Write a SERVLET program in java to accept details of student (SeatNo,
Stud_Name, Class, Total_Marks). Calculate percentage and grade obtained and display
details on page.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class StudentDetailsServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
        // Set response content type
        response.setContentType("text/html");
        // Get student details from request parameters
        String seatNo = request.getParameter("seatNo");
        String studName = request.getParameter("studName");
        String studentClass = request.getParameter("class");
        int totalMarks = Integer.parseInt(request.getParameter("totalMarks"));
        // Calculate percentage
        double percentage = (totalMarks / 500.0) * 100;
        // Calculate grade based   on percentage
        String grade;
        if (percentage >= 90) {
            grade = "A+";
        } else if (percentage >=   80) {
            grade = "A";
        } else if (percentage >=   70) {
            grade = "B";
        } else if (percentage >=   60) {
            grade = "C";
        } else if (percentage >=   50) {
            grade = "D";
        } else {
            grade = "F";
        }
        // Create HTML response
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head><title>Student Details</title></head>");
        out.println("<body>");
        out.println("<h1>Student Details</h1>");
        out.println("<p>Seat No: " + seatNo + "</p>");
        out.println("<p>Student Name: " + studName + "</p>");
        out.println("<p>Class: " + studentClass + "</p>");
        out.println("<p>Total Marks: " + totalMarks + "</p>");
        out.println("<p>Percentage: " + percentage + "%</p>");
        out.println("<p>Grade: " + grade + "</p>");
        out.println("</body>");
        out.println("</html>");
    }
}
slip 22
A) Write a java program to display Date and Time of Server machine on client
machine.
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(12345); // Choose any
available port
             System.out.println("Server started. Waiting for client to connect...");
             Socket clientSocket = serverSocket.accept();
             System.out.println("Client connected.");
             PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
             // Get current date and time
             Date currentDate = new Date();
             // Send date and time to the client
             out.println(currentDate.toString());
             // Close resources
             out.close();
             clientSocket.close();
             serverSocket.close();
         } catch (IOException e) {
             e.printStackTrace();
         }
    }
}
import java.io.*;
import java.net.*;
public class Client {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("localhost", 12345); // Replace "localhost"
with the server's IP address
            BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
             // Read date and time from server
             String serverDateTime = in.readLine();
             System.out.println("Date and Time from Server: " + serverDateTime);
             // Close resources
             in.close();
             socket.close();
         } catch (IOException e) {
             e.printStackTrace();
         }
    }
}
B) Write a JSP program to accept the details of Account (ANo, Type, Bal) and store
it
into database and display it in tabular form.
<%@ page import="java.sql.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Account Details</title>
</head>
<body>
    <h2>Enter Account Details</h2>
    <form action="SaveAccountDetails.jsp" method="post">
        Account Number: <input type="text" name="ano"><br>
        Account Type: <input type="text" name="type"><br>
        Balance: <input type="text" name="bal"><br>
        <input type="submit" value="Submit">
    </form>
    <h2>Account Details</h2>
    <table border="1">
        <tr>
             <th>Account Number</th>
             <th>Account Type</th>
             <th>Balance</th>
        </tr>
        <%
             try {
                 // Establish database connection
                 Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database_name",
"your_username", "your_password");
                // Execute SQL query to fetch account details
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT * FROM Account");
                // Iterate through result set and display account details in
tabular form
                while (rs.next()) {
                    out.println("<tr>");
                    out.println("<td>" + rs.getString("ANo") + "</td>");
                    out.println("<td>" + rs.getString("Type") + "</td>");
                    out.println("<td>" + rs.getDouble("Bal") + "</td>");
                    out.println("</tr>");
                }
                // Close resources
                rs.close();
                stmt.close();
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        %>
    </table>
</body>
</html>
<%@ page import="java.sql.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String ano = request.getParameter("ano");
    String type = request.getParameter("type");
    double bal = Double.parseDouble(request.getParameter("bal"));
    try {
        // Establish database connection
        Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database_name",
"your_username", "your_password");
        // Execute SQL query to insert account details into the database
        PreparedStatement pstmt = conn.prepareStatement("INSERT INTO Account (ANo,
Type, Bal) VALUES (?, ?, ?)");
        pstmt.setString(1, ano);
        pstmt.setString(2, type);
        pstmt.setDouble(3, bal);
        pstmt.executeUpdate();
        // Close resources
        pstmt.close();
        conn.close();
        response.sendRedirect("AccountDetails.jsp"); // Redirect to
AccountDetails.jsp to display updated account details
    } catch (Exception e) {
        e.printStackTrace();
    }
%>
slip 23
A) Write a Java Program to display the details of College(CID, CName, address,
Year)
on JTable.
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;
public class CollegeDetails extends JFrame {
    private JTable table;
    public CollegeDetails() {
        setTitle("College Details");
        setSize(600, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        // Create a table model with column names
        DefaultTableModel model = new DefaultTableModel(new String[]{"CID",
"CName", "Address", "Year"}, 0);
        table = new JTable(model);
        // Add table to a scroll pane
        JScrollPane scrollPane = new JScrollPane(table);
        // Add scroll pane to frame
        add(scrollPane, BorderLayout.CENTER);
        // Fetch data from database and populate the table
        fetchCollegeDetails(model);
        setVisible(true);
    }
    private void fetchCollegeDetails(DefaultTableModel model) {
        try {
            // Establish database connection
            Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database_name",
"your_username", "your_password");
            // Execute SQL query to fetch college details
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM College");
            // Iterate through result set and add data to table model
            while (rs.next()) {
                String cid = rs.getString("CID");
                String cname = rs.getString("CName");
                String address = rs.getString("Address");
                int year = rs.getInt("Year");
                model.addRow(new Object[]{cid, cname, address, year});
            }
            // Close resources
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        new CollegeDetails();
    }
}
B) Write a SERVLET application to accept username and password, search them into
database, if found then display appropriate message on the browser otherwise
display
error message.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class LoginServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
        // Set response content type
        response.setContentType("text/html");
        // Get username and password from request parameters
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // Check if username and password are found in the database
        boolean userFound = checkCredentials(username, password);
        // Prepare response message
        String message = userFound ? "Login successful" : "Invalid username or
password";
         // Send response message to the client
         PrintWriter out = response.getWriter();
         out.println("<html><body>");
         out.println("<h2>" + message + "</h2>");
         out.println("</body></html>");
    }
    private boolean checkCredentials(String username, String password) {
        boolean userFound = false;
        try {
            // Establish database connection
            Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database_name",
"your_username", "your_password");
             // Execute SQL query to check if username and password exist in the
database
            PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM Users
WHERE Username = ? AND Password = ?");
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            ResultSet rs = pstmt.executeQuery();
             // Check if user is found
             userFound = rs.next();
             // Close resources
             rs.close();
             pstmt.close();
             conn.close();
         } catch (SQLException e) {
             e.printStackTrace();
         }
         return userFound;
     }
}
slip 24
A) Create a JSP page to accept a number from a user and display it in words:
Example: 123 – One Two Three. The output should be in red color.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
     <meta charset="UTF-8">
     <title>Number to Words Converter</title>
</head>
<body>
     <h2>Number to Words Converter</h2>
     <form action="" method="post">
         Enter a number: <input type="text" name="number">
         <input type="submit" value="Convert">
     </form>
    <%
         // Function to convert a digit to word
        String toWord(int digit) {
            switch(digit) {
                case 0: return "Zero";
                case 1: return "One";
                case 2: return "Two";
                case 3: return "Three";
                case 4: return "Four";
                case 5: return "Five";
                case 6: return "Six";
                case 7: return "Seven";
                case 8: return "Eight";
                case 9: return "Nine";
                default: return "";
            }
        }
        // Get number from request parameter
        String numberStr = request.getParameter("number");
        if (numberStr != null && !numberStr.isEmpty()) {
            // Display number in words
            out.println("<p style='color:red;'>Number in words: ");
            for (int i = 0; i < numberStr.length(); i++) {
                int digit = Character.getNumericValue(numberStr.charAt(i));
                out.println(toWord(digit) + " ");
            }
            out.println("</p>");
        }
    %>
</body>
</html>
B) Write a menu driven program in Java for the following: Assume Emp table with
attributes ( ENo, EName, salary, Desg ) is already created.
1. Insert
2. Update
3. Delete
4. Search
5. Display
6. Exit.
import java.util.Scanner;
import java.sql.*;
public class EmployeeManagementSystem {
    public static void main(String[] args) {
        try {
            Scanner scanner = new Scanner(System.in);
            int choice;
            do {
                 System.out.println("Employee Management System");
                 System.out.println("1. Insert");
                 System.out.println("2. Update");
                 System.out.println("3. Delete");
                 System.out.println("4. Search");
                 System.out.println("5. Display");
                 System.out.println("6. Exit");
                 System.out.print("Enter your choice: ");
                 choice = scanner.nextInt();
                switch (choice) {
                    case 1:
                        insertEmployee();
                        break;
                    case 2:
                        updateEmployee();
                        break;
                    case 3:
                        deleteEmployee();
                        break;
                    case 4:
                        searchEmployee();
                        break;
                    case 5:
                        displayEmployees();
                        break;
                    case 6:
                        System.out.println("Exiting...");
                        break;
                    default:
                        System.out.println("Invalid choice. Please enter a number
between 1 and 6.");
                }
            } while (choice != 6);
            scanner.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static void insertEmployee() {
        try {
            Scanner scanner = new Scanner(System.in);
            System.out.println("Insert Employee");
            System.out.print("Enter Employee Number: ");
            int eno = scanner.nextInt();
            System.out.print("Enter Employee Name: ");
            String ename = scanner.next();
            System.out.print("Enter Salary: ");
            double salary = scanner.nextDouble();
            System.out.print("Enter Designation: ");
            String desg = scanner.next();
            Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database_name",
"your_username", "your_password");
            PreparedStatement pstmt = conn.prepareStatement("INSERT INTO Emp (ENo,
EName, Salary, Desg) VALUES (?, ?, ?, ?)");
            pstmt.setInt(1, eno);
            pstmt.setString(2, ename);
            pstmt.setDouble(3, salary);
            pstmt.setString(4, desg);
            pstmt.executeUpdate();
            System.out.println("Employee inserted successfully.");
            pstmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static void updateEmployee() {
        try {
            Scanner scanner = new Scanner(System.in);
            System.out.println("Update Employee");
            System.out.print("Enter Employee Number: ");
            int eno = scanner.nextInt();
            System.out.print("Enter New Salary: ");
            double salary = scanner.nextDouble();
            Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database_name",
"your_username", "your_password");
            PreparedStatement pstmt = conn.prepareStatement("UPDATE Emp SET Salary
= ? WHERE ENo = ?");
            pstmt.setDouble(1, salary);
            pstmt.setInt(2, eno);
            int rowsUpdated = pstmt.executeUpdate();
            if (rowsUpdated > 0) {
                System.out.println("Employee updated successfully.");
            } else {
                System.out.println("No employee found with the given Employee
Number.");
            }
            pstmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static void deleteEmployee() {
        try {
            Scanner scanner = new Scanner(System.in);
            System.out.println("Delete Employee");
            System.out.print("Enter Employee Number: ");
            int eno = scanner.nextInt();
            Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database_name",
"your_username", "your_password");
            PreparedStatement pstmt = conn.prepareStatement("DELETE FROM Emp WHERE
ENo = ?");
            pstmt.setInt(1, eno);
            int rowsDeleted = pstmt.executeUpdate();
            if (rowsDeleted > 0) {
                System.out.println("Employee deleted successfully.");
            } else {
                System.out.println("No employee found with the given Employee
Number.");
            }
            pstmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static void searchEmployee() {
        try {
            Scanner scanner = new Scanner(System.in);
            System.out.println("Search Employee");
            System.out.print("Enter Employee Number: ");
            int eno = scanner.nextInt();
            Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database_name",
"your_username", "your_password");
            PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM Emp
WHERE ENo = ?");
            pstmt.setInt(1, eno);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                 System.out.println("Employee Details:");
                 System.out.println("Employee Number: " + rs.getInt("ENo"));
                 System.out.println("Employee Name: " + rs.getString("EName"));
                 System.out.println("Salary: " + rs.getDouble("Salary"));
                 System.out.println("Designation: " + rs.getString("Desg"));
            } else {
                 System.out.println("No employee found with the given Employee
Number.");
            }
            rs.close();
            pstmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static void displayEmployees() {
        try {
            System.out.println("Display Employees");
            Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database_name",
"your_username", "your_password");
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM Emp");
            while (rs.next()) {
                System.out.println("Employee Number: " + rs.getInt("ENo"));
                System.out.println("Employee Name: " + rs.getString("EName"));
                System.out.println("Salary: " + rs.getDouble("Salary"));
                System.out.println("Designation: " + rs.getString("Desg"));
                System.out.println();
            }
            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
slip 25
A) Write a Java program to accept a number through client terminal, send it to the
Server, Server calculates its factors and sends it to the client.
import java.io.*;
import java.net.*;
public class Client {
    public static void main(String[] args) {
        try {
            // Connect to the server
            Socket socket = new Socket("localhost", 12345);
            // Create input and output streams for communication
            BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            // Read number from the user
            BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in));
            System.out.print("Enter a number: ");
            String numberStr = userInput.readLine();
            // Send number to the server
            out.println(numberStr);
            // Read factors from the server and display them
            String factors = in.readLine();
            System.out.println("Factors: " + factors);
            // Close resources
            userInput.close();
            in.close();
            out.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
    public static void main(String[] args) {
        try {
            // Start the server and listen for connections
            ServerSocket serverSocket = new ServerSocket(12345);
            System.out.println("Server started. Waiting for client to connect...");
            Socket clientSocket = serverSocket.accept();
            System.out.println("Client connected.");
            // Create input and output streams for communication
            BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
            // Read number from the client
            String numberStr = in.readLine();
            int number = Integer.parseInt(numberStr);
            // Calculate factors of the number
            List<Integer> factors = calculateFactors(number);
            // Send factors to the client
            out.println(factors.toString());
            // Close resources
            in.close();
            out.close();
            clientSocket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static List<Integer> calculateFactors(int number) {
        List<Integer> factors = new ArrayList<>();
        for (int i = 1; i <= number; i++) {
            if (number % i == 0) {
                factors.add(i);
            }
        }
        return factors;
    }
}
slip 26
A) Write a java program to display list of college names from college table.
(Assume
College table (CID, CName, addr) is already created.
import java.sql.*;
public class CollegeNamesDisplay {
    public static void main(String[] args) {
        try {
            // Establish database connection
            Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database_name",
"your_username", "your_password");
            // Execute SQL query to select college names
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT CName FROM College");
            // Display college names
            System.out.println("List of College Names:");
            while (rs.next()) {
                System.out.println(rs.getString("CName"));
            }
            // Close resources
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
B) Write a SERVLET program to Design an HTML page containing 4 option buttons
(Painting, Drawing, Singing and swimming) and 2 buttons reset and submit. When the
user clicks submit, the server responds by adding cookie containing the selected
hobby
and sends the HTML page to the client. Program should not allow duplicate cookies
to
be written.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HobbySelectionServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
        // Get selected hobby from request parameter
        String hobby = request.getParameter("hobby");
        // Check if hobby cookie already exists
        Cookie[] cookies = request.getCookies();
        boolean hobbyCookieExists = false;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("hobby")) {
                    hobbyCookieExists = true;
                    break;
                }
            }
        }
        // If hobby cookie doesn't exist, create it and add to response
        if (!hobbyCookieExists && hobby != null) {
            Cookie hobbyCookie = new Cookie("hobby", hobby);
            response.addCookie(hobbyCookie);
        }
        // Send HTML response to client
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Hobby Selection</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h2>Select Your Hobby</h2>");
        out.println("<form action='' method='post'>");
        out.println("<input type='radio' name='hobby'
value='Painting'>Painting<br>");
        out.println("<input type='radio' name='hobby'
value='Drawing'>Drawing<br>");
        out.println("<input type='radio' name='hobby'
value='Singing'>Singing<br>");
        out.println("<input type='radio' name='hobby'
value='Swimming'>Swimming<br>");
        out.println("<input type='reset' value='Reset'>");
        out.println("<input type='submit' value='Submit'>");
        out.println("</form>");
        out.println("</body>");
        out.println("</html>");
    }
}
slip 27
A) Write a JSP script to accept the details of Teacher (TID, TName, Desg, Subject ,
Qualification) and display it on the browser. Use appropriate controls for
accepting
data.
<!DOCTYPE html>
<html>
<head>
    <title>Teacher Details</title>
</head>
<body>
    <h2>Teacher Details</h2>
    <%-- Retrieve teacher details from request parameters --%>
    <% String tid = request.getParameter("tid"); %>
    <% String tname = request.getParameter("tname"); %>
    <% String desg = request.getParameter("desg"); %>
    <% String subject = request.getParameter("subject"); %>
    <% String qualification = request.getParameter("qualification"); %>
    <%-- Display teacher details on the browser --%>
    <p>Teacher ID: <%= tid %></p>
    <p>Teacher Name: <%= tname %></p>
    <p>Designation: <%= desg %></p>
    <p>Subject: <%= subject %></p>
    <p>Qualification: <%= qualification %></p>
</body>
</html>
B) Write a Java Program for the implementation of scrollable ResultSet. Assume
Teacher table with attributes (TID, TName, Salary, Subject) is already created.
import java.sql.*;
public class ScrollableResultSetExample {
    public static void main(String[] args) {
        try {
            // Establish database connection
            Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database_name",
"your_username", "your_password");
            // Create a statement with scrollable result set type
            Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
            // Execute SQL query to select all records from Teacher table
            ResultSet rs = stmt.executeQuery("SELECT * FROM Teacher");
            // Move cursor to the last row
            rs.last();
            // Get the total number of rows in the result set
            int rowCount = rs.getRow();
            System.out.println("Total number of records: " + rowCount);
            // Move cursor to the first row
            rs.beforeFirst();
            // Iterate through the result set and display records
            while (rs.next()) {
                int tid = rs.getInt("TID");
                String tname = rs.getString("TName");
                double salary = rs.getDouble("Salary");
                String subject = rs.getString("Subject");
                System.out.println("TID: " + tid + ", TName: " + tname + ", Salary:
" + salary + ", Subject: " + subject);
            }
            // Close resources
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
slip 28
A) Write a java program for the implementation of synchronization.
class Counter {
    private int count = 0;
    // Synchronized method to increment the count
    public synchronized void increment() {
        count++;
    }
    // Synchronized method to decrement the count
    public synchronized void decrement() {
        count--;
    }
    // Method to get the current value of the count
    public int getCount() {
        return count;
    }
}
class IncrementThread extends Thread {
    private Counter counter;
    public IncrementThread(Counter counter) {
        this.counter = counter;
    }
    public void run() {
        for (int i = 0; i < 1000; i++) {
            counter.increment();
        }
    }
}
class DecrementThread extends Thread {
    private Counter counter;
    public DecrementThread(Counter counter) {
        this.counter = counter;
    }
    public void run() {
        for (int i = 0; i < 1000; i++) {
            counter.decrement();
        }
    }
}
public class SynchronizationExample {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        IncrementThread incrementThread = new IncrementThread(counter);
        DecrementThread decrementThread = new DecrementThread(counter);
        // Start the threads
        incrementThread.start();
        decrementThread.start();
        // Wait for both threads to finish
        incrementThread.join();
        decrementThread.join();
        // Print the final count
        System.out.println("Final count: " + counter.getCount());
    }
}
slip 29
A) Write a java program using multithreading for the following:
1. Display all the odd numbers between 1 to n.
2. Display all the prime numbers between 1 to n.
class OddNumbersThread extends Thread {
    private int n;
    public OddNumbersThread(int n) {
        this.n = n;
    }
    public void run() {
        System.out.println("Odd Numbers:");
        for (int i = 1; i <= n; i++) {
            if (i % 2 != 0) {
                System.out.print(i + " ");
            }
        }
        System.out.println();
    }
}
class PrimeNumbersThread extends Thread {
    private int n;
    public PrimeNumbersThread(int n) {
        this.n = n;
    }
    public void run() {
        System.out.println("Prime Numbers:");
        for (int i = 2; i <= n; i++) {
            boolean isPrime = true;
            for (int j = 2; j <= Math.sqrt(i); j++) {
                if (i % j == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                System.out.print(i + " ");
            }
        }
        System.out.println();
    }
}
public class MultithreadingExample {
    public static void main(String[] args) {
        int n = 50; // Change n as needed
        // Create threads for odd numbers and prime numbers
        OddNumbersThread oddNumbersThread = new OddNumbersThread(n);
        PrimeNumbersThread primeNumbersThread = new PrimeNumbersThread(n);
        // Start the threads
        oddNumbersThread.start();
        primeNumbersThread.start();
    }
}
B) Write a SERVLET program to change inactive time interval of session.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/ChangeSessionTimeoutServlet")
public class ChangeSessionTimeoutServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
        // Get the session object
        HttpSession session = request.getSession();
        // Set session inactive time interval to 60 seconds
        session.setMaxInactiveInterval(60);
        response.setContentType("text/html");
        response.getWriter().println("<h3>Session timeout changed to 60
seconds</h3>");
    }
}
slip 30
A) Write a JSP script to accept a String from a user and display it in reverse
order.
<!DOCTYPE html>
<html>
<head>
    <title>Reverse String</title>
</head>
<body>
    <h2>Enter a String</h2>
    <form action="ReverseString.jsp" method="post">
        <input type="text" name="inputString">
        <input type="submit" value="Submit">
    </form>
    <h2>Reversed String</h2>
    <%-- Retrieve input string from request parameter --%>
    <% String inputString = request.getParameter("inputString"); %>
    <%-- Check if inputString is not null and not empty --%>
    <% if (inputString != null && !inputString.isEmpty()) { %>
        <%-- Reverse the inputString using StringBuilder and display --%>
        <p><%= new StringBuilder(inputString).reverse().toString() %></p>
    <% } else { %>
        <p>No input string provided.</p>
    <% } %>
</body>
</html>
B) Write a java program in multithreading using applet for moving car.
import java.applet.Applet;
import java.awt.*;
public class MovingCarApplet extends Applet implements Runnable {
    private int x = 0; // Initial x position of the car
    private int y = 100; // Initial y position of the car
    private Thread carThread; // Thread for moving the car
    private boolean isMoving = true; // Flag to control the car movement
    public void init() {
        // Set the size of the applet window
        setSize(400, 300);
    }
    public void start() {
        // Create a new thread for the car movement
        carThread = new Thread(this);
        carThread.start();
    }
    public void stop() {
        // Stop the car movement thread
        isMoving = false;
        carThread = null;
    }
    public void run() {
        while (isMoving) {
            // Move the car to the right
            x += 5;
            if (x > getWidth()) {
                // Reset x position when the car reaches the right edge of the
applet window
                x = -50;
            }
            // Repaint the applet window to show the updated car position
            repaint();
            // Pause for a short period to control the speed of the car
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public void paint(Graphics g) {
        // Draw the car at the current position
        g.setColor(Color.RED);
        g.fillRect(x, y, 50, 30);
        g.setColor(Color.BLACK);
        g.fillOval(x + 10, y + 30, 10, 10);
        g.fillOval(x + 30, y + 30, 10, 10);
    }
}