Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views91 pages

Adv Java Slips Solutions

The document contains multiple Java programming tasks, including applet-based applications for scrolling text, chatting, and drawing flags, as well as socket programming for prime number checking and student record deletion using SQL. It also includes JSP programs for validating email and calculating the sum of digits, along with servlet examples for visit counting and server information display. Additionally, there are multithreading examples for bouncing balls, traffic signals, and blinking images.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views91 pages

Adv Java Slips Solutions

The document contains multiple Java programming tasks, including applet-based applications for scrolling text, chatting, and drawing flags, as well as socket programming for prime number checking and student record deletion using SQL. It also includes JSP programs for validating email and calculating the sum of digits, along with servlet examples for visit counting and server information display. Additionally, there are multithreading examples for bouncing balls, traffic signals, and blinking images.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

Slip 1

Write a java program to scroll the text from left to right and vice versa continuously.

import java.applet.Applet;

import java.awt.*;

public class Slip1A extends Applet implements Runnable {

int x, y, z;

Thread t;

public void init() {

x = 50;

y = 50;

z = 1;

t = new Thread(this);

t.start();

public void mpostion() {

x = x + 10 * z;

if (x > this.getWidth())

z = -1;

if (x < 0)

z = 1;

public void run() {

while (true) {
repaint();

mpostion();

try {

Thread.sleep(100);

} catch (Exception e) {

public void paint(Graphics g) {

g.drawString("SVPM", x, y);

Write a socket program in java for chatting application.(Use Swing)

import java.awt.*;

import java.awt.event.*;

import java.net.*;

import java.io.*;

public class Slip1B extends Frame implements ActionListener, Runnable {

Button b1;

TextField t1;

TextArea ta;
Thread t;

BufferedReader br;

PrintWriter pw;

public Slip1B() {

Frame f = new Frame("Server");

f.setLayout(new FlowLayout());

b1 = new Button("Send");

b1.addActionListener(this);

t1 = new TextField(15);

ta = new TextArea(12, 20);

f.add(t1);

f.add(ta);

f.add(b1);

try {

ServerSocket ss = new ServerSocket(2000);

Socket s = ss.accept();

System.out.println(s);

br = new BufferedReader(new InputStreamReader(s.getInputStream()));

pw = new PrintWriter(s.getOutputStream(), true);

} catch (Exception e) {

t = new Thread(this);
t.start();

f.setSize(400, 400);

f.setVisible(true);

public void actionPerformed(ActionEvent ae) {

pw.println(t1.getText());

t1.setText("");

public void run() {

while (true) {

try {

String str = br.readLine();

ta.append(str + "\n");

} catch (Exception e) {

public static void main(String[] args) {

Slip1B c = new Slip1B();

}
}

//Client

import java.awt.*;

import java.awt.event.*;

import java.net.*;

import java.io.*;

public class Slip1B1 extends Frame implements ActionListener, Runnable {

Button b1;

TextField t1;

TextArea ta;

Thread t;

Socket s;

BufferedReader br;

PrintWriter pw;

public Slip1B1() {

Frame f = new Frame("Client");

f.setLayout(new FlowLayout());

b1 = new Button("Send");

b1.addActionListener(this);

t1 = new TextField(15);
ta = new TextArea(12, 20);

f.add(t1);

f.add(ta);

f.add(b1);

try {

s = new Socket("localhost",2000);

br = new BufferedReader(new InputStreamReader(s.getInputStream()));

pw = new PrintWriter(s.getOutputStream(), true);

} catch (Exception e) {

t = new Thread(this);

t.start();

f.setSize(400, 400);

f.setVisible(true);

public void actionPerformed(ActionEvent ae) {

pw.println(t1.getText());

t1.setText("");

public void run() {

while (true) {
try {

String str = br.readLine();

ta.append(str + "\n");

} catch (Exception e) {

public static void main(String[] args) {

Slip1B1 c = new Slip1B1();

Slip 2

Write a JSP program to check whether given number is Perfect or not. (Use Include directive). [15 M]

Slip2A.html

<html>

<body>

<h1>Find Perfect Number</h1>

<form action="http://127.0.0.1:8080/java/Slip2A.jsp" method="GET">

Enter Number : <input type='text' name='no'>

<input type='submit' value='SUBMIT'>

</form>
</body>

</html>

Slip2A.jsp

<%@ page language="java" %>

<html>

<body>

<%

int n = Integer.parseInt(request.getParameter("no"));

int n1=0;

for(int i=1; i<n; i++){

if(n%i==0){

n1+=i;

if(n1==n){

out.println("Perfect Number");

}else{

out.println("not Perfect Number");

%>

</body>
</html>

Write a java program in multithreading using applet for drawing flag.

import java.awt.*;

public class Slip2B extends Frame{

int f = 0;

public Slip2B(){

Signal s = new Signal();

s.start();

setSize(500,500);

setVisible(true);

public void paint (Graphics g){

switch (f){

case 0 :

g.drawLine(150, 50, 150, 300);

case 1 :

g.drawRect(150, 50, 100, 90);

}
}

class Signal extends Thread{

public void run(){

while(true){

f = (f+1)%2;

repaint();

try{

Thread.sleep(1000);

}catch(Exception e){

public static void main(String args[]){

new Slip2B();

Slip 3

Write a socket program in Java to check whether given number is prime or not. Display result on client
terminal. [15 M]

//Client
import java.io.*;

import java.net.*;

public class Slip3A {

public static void main(String args[]) throws Exception {

Socket s = new Socket("localhost", 7500);

DataInputStream din = new DataInputStream(System.in);

System.out.print("Enter any number:");

String n = din.readLine();

System.out.println("====================");

DataOutputStream dos = new DataOutputStream(s.getOutputStream());

dos.writeBytes(n + "\n");

DataInputStream dis = new DataInputStream(s.getInputStream());

System.out.println(dis.readLine());

//Server
import java.io.*;

import java.net.*;

public class Slip3A1 {

public static void main(String args[]) throws Exception {

ServerSocket ss = new ServerSocket(7500);

Socket s = ss.accept();

DataInputStream dis = new DataInputStream(s.getInputStream());

int n = Integer.parseInt(dis.readLine());

int i, cnt = 0;

for (i = 2; i < n; i++) {

if (n % i == 0)

cnt++;

break;

DataOutputStream dos = new DataOutputStream(s.getOutputStream());

if (cnt == 0)

dos.writeBytes(n + " is prime number.");


else

dos.writeBytes(n + " is not prime number.");

s.close();

Write a java program using applet for bouncing ball, for each bounce color of ball should change
randomly.

import java.awt.*;

import java.awt.event.*;

public class Slip3B extends Frame implements Runnable {

private int x, y, w, h, f;

private Color c = Color.red;

public Slip3B() {

setTitle("Bouncing Boll");

setSize(400, 400);

setVisible(true);

w = getWidth();

h = getHeight();

x = (int) (Math.random() * getWidth());


y = (int) (Math.random() * getHeight());

Thread t = new Thread(this);

t.start();

public void run() {

while (true) {

switch (f) {

case 0:

y++;

if (y > h - 50) {

c = new Color((int) (Math.random() * 256), (int)


(Math.random() * 256),

(int) (Math.random() * 256));

f = 1;

break;

case 1:

y--;

if (y < 0) {

c = new Color((int) (Math.random() * 256), (int)


(Math.random() * 256),

(int) (Math.random() * 256));

f = 0;
}

repaint();

try {

Thread.sleep(10);

} catch (Exception e) {

public void paint(Graphics g) {

super.paint(g);

g.setColor(c);

g.fillOval(x, y, 20, 20);

public static void main(String args[]) {

new Slip3B();

Slip 4

Write a Java Program to delete details of students whose initial character of their name is ‘S’. [15 M]

import java.sql.*;
class Slip4A {

public static void main(String args[]) throws Exception {

Connection con;

Statement stmt;

Class.forName("com.mysql.jdbc.Driver");

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bcadb", "r


oot", "");

stmt = con.createStatement();

int n = stmt.executeUpdate("delete from student where sname like 'S%'");

System.out.println(n + " rows deleted..");

con.close();

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.*;

public class Slip4B extends HttpServlet implements Servlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOE


xception, ServletException {

res.setContentType("html/text");

PrintWriter pw = res.getWriter();

pw.println("<html><body><h1><b>INFORMATION OF SERVER</b></h1>");

pw.println("<br>Server Name:" + req.getServerName());

pw.println("<br>Server Port:" + req.getServerPort());

pw.println("<br> Ip Address:" + req.getRemoteAddr());

pw.println("<br> CLient Browser:" + req.getHeader("User-Agent"));

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

pw.close();

Slip 5

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. [15 M]

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>
<title>Sum of First and Last Digits</title>

</head>

<body>

<h2>Enter a Number:</h2>

<form action="sum.jsp" method="post">

<input type="number" name="num" required>

<input type="submit" value="Calculate">

</form>

<%

if(request.getParameter("num")!=null) {

int num = Integer.parseInt(request.getParameter("num"));

int lastDigit = num % 10;

int firstDigit = num;

while(firstDigit>=10) {

firstDigit = firstDigit / 10;

int sum = firstDigit + lastDigit;

%>

<h2 style="color:red; font-size:18px;">Sum of First and Last Digits: <%=sum%></h2>

<%

%>
</body>

</html>

Write a java program in multithreading using applet for Traffic signal.

import java.awt.*;

public class Slip5B extends Frame {

int f = 0;

public Slip5B() {

Signal s = new Signal();

s.start();

setSize(500, 500);

setVisible(true);

public void paint(Graphics g) {

switch (f) {

case 0:

g.setColor(Color.red);
g.fillOval(60, 60, 50, 50);

g.setColor(Color.black);

g.fillOval(60, 120, 50, 50);

g.fillOval(60, 180, 50, 50);

break;

case 1:

g.setColor(Color.yellow);

g.fillOval(60, 120, 50, 50);

g.setColor(Color.black);

g.fillOval(60, 60, 50, 50);

g.fillOval(60, 180, 50, 50);

break;

case 2:

g.setColor(Color.green);

g.fillOval(60, 180, 50, 50);

g.setColor(Color.black);

g.fillOval(60, 120, 50, 50);

g.fillOval(60, 60, 50, 50);

break;

}
class Signal extends Thread {

public void run() {

while (true) {

f = (f + 1) % 3;

repaint();

try {

Thread.sleep(1000);

} catch (Exception e) {

public static void main(String args[]) {

new Slip5B();

Slip 6

Write a java program to blink image on the Frame continuously.

import java.awt.*;

public class Slip6A extends Frame {


int f = 0;

public Slip6A() {

Blink s = new Blink();

s.start();

setSize(500, 500);

setVisible(true);

class Blink extends Thread {

public void run() {

while (true) {

f = (f + 1) % 2;

repaint();

try {

Thread.sleep(500);

} catch (Exception e) {

}
public void paint(Graphics g) {

Toolkit t = Toolkit.getDefaultToolkit();

Image img = t.getImage("./car.png");

switch (f) {

case 0:

g.drawImage(img, 150, 100, this);

public static void main(String args[]) {

new Slip6A();

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.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class VisitCounterServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

int visits = 0;

Cookie[] cookies = request.getCookies();

if (cookies != null) {

for (Cookie cookie : cookies) {

if (cookie.getName().equals("visitCount")) {

visits = Integer.parseInt(cookie.getValue());

visits++;

Cookie visitCookie = new Cookie("visitCount", Integer.toString(visits));

response.addCookie(visitCookie);

response.setContentType("text/html");

PrintWriter out = response.getWriter();

if (visits == 1) {

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

out.println("<h2>Welcome to my website!</h2>");

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

} else {

out.println("<html><head><title>Visit Count</title></head><body>");

out.println("<h2>You have visited this website " + visits + " times.</h2>");

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

out.close();

Slip 7

Write a JSP script to validate given E-Mail ID. [15 M]

<%@ page language="java" %>

<%

String email = request.getParameter("email"); // retrieve email from form data

String regex = "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$"; // regular expression for email validation

if (email.matches(regex)) {

out.println("Valid email address"); // if email matches the regex, print "Valid email address"

} else {

out.println("Invalid email address"); // if email does not match the regex, print "Invalid email address"

%>

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 java.awt.event.*;

import javax.swing.*;

class alpha extends Thread {


public void run() {

System.out.println("********* java program using multithreading


*********");

public class Slip7B {

public static void main(String[] args) {

alpha a1 = new alpha();

System.out.print(a1);

JFrame f = new JFrame("Slip7B");

final JTextField tf = new JTextField();

tf.setBounds(50, 50, 150, 20);

JButton b = new JButton("Display");

b.setBounds(50, 100, 95, 30);

b.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

for(int i=0; i<=100; i++){

tf.setText("Enter String"+ i);

a1.start();

}
});

f.add(b);

f.add(tf);

f.setSize(400, 400);

f.setLayout(null);

f.setVisible(true);

Slip 8

Write a Java Program to display all the employee names whose initial character of a name is ‘A’. [15 M]

import java.io.*;

import java.sql.*;

class Slip8A {

public static void main(String args[]) throws Exception {

Statement stmt;

ResultSet rs;

Class.forName("com.mysql.jdbc.Driver");

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306


/bcadb", "root", "");
stmt = con.createStatement();

rs = stmt.executeQuery("select ename from emp where ename like 'A%'");

System.out.println("<<<<Employee Name>>>>>");

System.out.println("==================");

while (rs.next()) {

System.out.println(rs.getString(1));

con.close();

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 Slip8B extends Applet implements Runnable {

Thread t;

String str;
public void start() {

t = new Thread(this);

t.start();

public void run() {

try {

while (true) {

Date date = new Date();

SimpleDateFormat Nowtime = new SimpleDateFormat("hh:mm:ss");

str = Nowtime.format(date);

repaint();

t.sleep(1000);

} catch (Exception e) {

public void paint(Graphics g) {

g.drawString(str, 120, 100);

}
Slip 9

Write a Java Program to create a Emp (ENo, EName, Sal) table and insert record into it. (Use
PreparedStatement Interface) [15 M]

import java.sql.*;

import java.io.*;

class Slip9A {

public static void main(String args[]) throws Exception {

Connection con;

PreparedStatement pstmt;

int e1, s;

String enm;

Class.forName("com.mysql.jdbc.Driver");

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bcadb", "r


oot", "");

pstmt = con.prepareStatement("create table employee1(eid int(8),ename


varchar(20),sal int(8))");

pstmt.executeUpdate();

System.out.println("Table Created Successfully!!!!!!");

System.out.println("=====================================");
DataInputStream din = new DataInputStream(System.in);

System.out.println("Enter Employee Id, Name and Salary");

e1 = Integer.parseInt(din.readLine());

enm = din.readLine();

s = Integer.parseInt(din.readLine());

pstmt = con.prepareStatement("insert into employee1 values(?,?,?)");

pstmt.setInt(1, e1);

pstmt.setString(2, enm);

pstmt.setInt(3, s);

pstmt.executeUpdate();

System.out.println("Record Inserted Successfully!!!!!!");

con.close();

}
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 import="java.util.*" %>

<%

// Create a session object if one doesn't exist

HttpSession session = request.getSession(true);

// Get the cart object from the session

Map<String, Integer> cart = (Map<String, Integer>)session.getAttribute("cart");

if (cart == null) {

cart = new HashMap<String, Integer>();

session.setAttribute("cart", cart);

// Add items to the cart

if (request.getParameter("item") != null) {

String item = request.getParameter("item");

int quantity = Integer.parseInt(request.getParameter("quantity"));

if (cart.containsKey(item)) {

quantity += cart.get(item);

cart.put(item, quantity);

}
// Calculate the page total

int pageTotal = 0;

for (Map.Entry<String, Integer> entry : cart.entrySet()) {

String item = entry.getKey();

int quantity = entry.getValue();

int price = getPrice(item);

pageTotal += price * quantity;

// Display the shopping cart

out.println("<h1>Shopping Cart</h1>");

out.println("<table>");

out.println("<tr><th>Item</th><th>Quantity</th><th>Price</th></tr>");

for (Map.Entry<String, Integer> entry : cart.entrySet()) {

String item = entry.getKey();

int quantity = entry.getValue();

int price = getPrice(item);

int total = price * quantity;

out.println("<tr><td>" + item + "</td><td>" + quantity + "</td><td>" + total + "</td></tr>");

out.println("</table>");
// Display the page total

out.println("<h2>Page Total: " + pageTotal + "</h2>");

// Display the checkout button

out.println("<form action=\"checkout.jsp\"><input type=\"submit\" value=\"Checkout\"></form>");

%>

Slip 10

Write a java Program in Hibernate to display “Hello world” message. [15 M]

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

public class HelloWorld {

public static void main(String[] args) {

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


Session session = sessionFactory.openSession();

System.out.println("Hello world");

session.close();
sessionFactory.close();
}
}

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.http.*;

public class ProductDetailsServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


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

try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase",
"root", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Products");

out.println("<html><head><title>Product Details</title></head><body><table
border='1'><tr><th>ProdCode</th><th>PName</th><th>Price</th></tr>");
while (rs.next()) {
String prodCode = rs.getString("ProdCode");
String pName = rs.getString("PName");
String price = rs.getString("Price");
out.println("<tr><td>" + prodCode + "</td><td>" + pName + "</td><td>" + price +
"</td></tr>");
}
out.println("</table></body></html>");
con.close();
} catch (Exception e) {
out.println(e);
}
}
}

Slip 11

Write a java program to display IPAddress and name of client machine.

import java.net.InetAddress;

public class ClientMachineInfo {


public static void main(String[] args) {
try {
InetAddress clientAddr = InetAddress.getLocalHost();
System.out.println("IP address of client machine: " + clientAddr.getHostAddress());
System.out.println("Name of client machine: " + clientAddr.getHostName());
} catch (Exception e) {
System.out.println("Error while getting client machine info: " + e.getMessage());
}
}
}

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.util.Scanner;
public class ProductSalesDetails {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Prompt user to enter start and end dates


System.out.print("Enter start date (YYYY-MM-DD): ");
String startDate = sc.next();
System.out.print("Enter end date (YYYY-MM-DD): ");
String endDate = sc.next();

// Define database connection variables


String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "password";

// Define SQL query to fetch sales details of product between two dates
String query = "SELECT PID, PName, Qty, Rate, Amount FROM Sales WHERE SaleDate BETWEEN ?
AND ?";

try {
// Establish database connection
Connection conn = DriverManager.getConnection(url, user, password);

// Prepare SQL statement with parameters for start and end dates
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, startDate);
pstmt.setString(2, endDate);

// Execute the SQL statement and get the result set


ResultSet rs = pstmt.executeQuery();

// Display the sales details in tabular form


System.out.println("PID\tPName\tQty\tRate\tAmount");
System.out.println("-------------------------------------------------");
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);
}

// Close the database connection


conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Slip 12
Write a java program to count the number of records in a table. [15 M]

import java.io.*;

import java.sql.*;

class Slip12A {

public static void main(String args[]) throws Exception {

Statement stmt;

ResultSet rs;

int cnt = 0;

Class.forName("com.mysql.jdbc.Driver");

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306


/bcadb", "root", "");

stmt = con.createStatement();

rs = stmt.executeQuery("select * from student");

while (rs.next()) {

cnt++;

}
System.out.println("Total number of records in table is : " + cnt);

con.close();

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 MyThread extends Thread {


private String threadName;

public MyThread(String name) {


threadName = name;
}
public void run() {
Random rand = new Random();
int sleepTime = rand.nextInt(5000);
System.out.println(threadName + " sleeping for " + sleepTime + " ms.");
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
System.out.println(threadName + " interrupted.");
}
System.out.println(threadName + " finished.");
}

public static void main(String[] args) {


MyThread t = new MyThread("MyThread");
System.out.println(t.getName() + " created.");
t.start();
try {
t.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println(t.getName() + " dead.");
}
}
Slip 13

Write a java program to display name of currently executing Thread in multithreading. [15 M]

public class Slip13A {

public static void main(String[] args) {

Thread t = Thread.currentThread();

System.out.println("Thread Name is : " + t.getName());

Write a JSP program to display the details of College (CollegeID, Coll_Name, Address) in tabular form on
browser.

<%@page import="java.sql.*"%>
<html>
<head>
<title>College Details</title>
</head>
<body>
<h1>College Details</h1>
<table border="1">
<tr>
<th>College ID</th>
<th>College Name</th>
<th>Address</th>
</tr>
<%
try {
// Load the JDBC driver and establish a connection to the database
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root",
"password");

// Execute a SELECT query to retrieve the college details


Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT CollegeID, Coll_Name, Address FROM College");

// Loop through the result set and display the college details in the table
while (rs.next()) {
%>
<tr>
<td><%= rs.getString("CollegeID") %></td>
<td><%= rs.getString("Coll_Name") %></td>
<td><%= rs.getString("Address") %></td>
</tr>
<%
}

// Clean up resources
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
out.println("Error: " + e.getMessage());
}
%>
</table>
</body>
</html>

Slip 14

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 Checker</title>
</head>
<body>
<h1>Voter Eligibility Checker</h1>
<form method="post" action="check_voter.jsp">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age"><br>
<input type="submit" value="Check Eligibility">
</form>
<%
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));

if(age >= 18) {


out.println("<p>"+ name +", you are eligible to vote.</p>");
} else {
out.println("<p>"+ name +", you are not eligible to vote yet.</p>");
}
%>
</body>
</html>

Write a Java program to display given extension files from a specific directory on

server machine.

import java.io.File;
import java.util.Scanner;

public class DisplayFilesWithExtension {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


System.out.print("Enter the directory path: ");
String directoryPath = scanner.nextLine();

System.out.print("Enter the file extension (without dot): ");


String fileExtension = scanner.nextLine();

File directory = new File(directoryPath);


File[] files = directory.listFiles((dir, name) -> name.endsWith("." + fileExtension));

if (files.length == 0) {
System.out.println("No files found with the given extension in the directory.");
} else {
System.out.println("Files with ." + fileExtension + " extension in the directory:");
for (File file : files) {
System.out.println(file.getName());
}
}
}
}

Slip 15

Write a java program to display each alphabet after 2 seconds between ‘a’ to ‘z’. [15 M]

public class Slip15A {

public static void main(String args[]) {

alpha a1 = new alpha();


a1.start();

class alpha extends Thread {

public void run() {

try {

for(int i=97; i<=122; i++){

System.out.println((char)i);

sleep(2000);

} catch (Exception e) {

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 StudentDetails extends JFrame implements ActionListener {

JLabel l1, l2, l3, l4, l5;


JTextField t1, t2, t3, t4;
JButton b1, b2;
JComboBox<String> comboBox;
Connection conn = null;
PreparedStatement pst = null;
public StudentDetails() {
setTitle("Student Details");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLocationRelativeTo(null);

l1 = new JLabel("Roll No:");


l2 = new JLabel("Name:");
l3 = new JLabel("Percentage:");
l4 = new JLabel("Gender:");
l5 = new JLabel("Class:");

t1 = new JTextField();
t2 = new JTextField();
t3 = new JTextField();

String[] genders = {"Male", "Female", "Other"};


comboBox = new JComboBox<>(genders);

t4 = new JTextField();

b1 = new JButton("Save");
b2 = new JButton("Cancel");

JPanel p = new JPanel(new GridLayout(6, 2));


p.add(l1);
p.add(t1);
p.add(l2);
p.add(t2);
p.add(l3);
p.add(t3);
p.add(l4);
p.add(comboBox);
p.add(l5);
p.add(t4);
p.add(b1);
p.add(b2);

add(p);

b1.addActionListener(this);
b2.addActionListener(this);

setVisible(true);

// Connect to the database


try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
}

public static void main(String[] args) {


new StudentDetails();
}

public void actionPerformed(ActionEvent ae) {


if (ae.getSource() == b1) { // Save button is clicked
try {
String query = "insert into students(RNo, SName, Per, Gender, Class) values (?, ?, ?, ?, ?)";
pst = conn.prepareStatement(query);
pst.setInt(1, Integer.parseInt(t1.getText()));
pst.setString(2, t2.getText());
pst.setDouble(3, Double.parseDouble(t3.getText()));
pst.setString(4, (String) comboBox.getSelectedItem());
pst.setInt(5, Integer.parseInt(t4.getText()));
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Data saved successfully!");
t1.setText("");
t2.setText("");
t3.setText("");
t4.setText("");
} catch (SQLException ex) {
System.out.println("Error: " + ex.getMessage());
}
} else if (ae.getSource() == b2) { // Cancel button is clicked
System.exit(0);
}
}
}

Slip 16

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 language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<% String username = request.getParameter("username");
String password = request.getParameter("password");
if (username != null && password != null && username.equals(password)) { %>
<h1>Login Successfully</h1>
<% } else { %>
<h1>Login Failed</h1>
<% } %>
</body>
</html>

HTML Code:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="login.jsp" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br>
<input type="submit" value="Login">
</form>
</body>
</html>

Error.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Error</title>
</head>
<body>
<h1>Login Failed</h1>
<p>Please check your username and password and try again.</p>
</body>
</html>
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 {


public static void main(String[] args) {
try {
// Connect to database
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentdb",
"root", "");

// Prepare SQL statement to insert student details


String insertSql = "INSERT INTO students (rno, sname, per) VALUES (?, ?, ?)";
PreparedStatement insertStmt = conn.prepareStatement(insertSql);

// Insert 5 student records


insertStmt.setInt(1, 1);
insertStmt.setString(2, "John");
insertStmt.setFloat(3, 85.0f);
insertStmt.executeUpdate();

insertStmt.setInt(1, 2);
insertStmt.setString(2, "Jane");
insertStmt.setFloat(3, 90.0f);
insertStmt.executeUpdate();

insertStmt.setInt(1, 3);
insertStmt.setString(2, "Bob");
insertStmt.setFloat(3, 80.0f);
insertStmt.executeUpdate();

insertStmt.setInt(1, 4);
insertStmt.setString(2, "Alice");
insertStmt.setFloat(3, 95.0f);
insertStmt.executeUpdate();

insertStmt.setInt(1, 5);
insertStmt.setString(2, "Tom");
insertStmt.setFloat(3, 75.0f);
insertStmt.executeUpdate();

// Prepare SQL statement to retrieve student with highest percentage


String selectSql = "SELECT * FROM students WHERE per = (SELECT MAX(per) FROM students)";
PreparedStatement selectStmt = conn.prepareStatement(selectSql);

// Execute SQL statement and display results


ResultSet rs = selectStmt.executeQuery();
while (rs.next()) {
int rno = rs.getInt("rno");
String sname = rs.getString("sname");
float per = rs.getFloat("per");
System.out.println("Roll No: " + rno + ", Name: " + sname + ", Percentage: " + per);
}

// Close resources
rs.close();
selectStmt.close();
insertStmt.close();
conn.close();

} catch (Exception e) {
e.printStackTrace();
}
}
}

Slip 17

Write a java program to accept a String from user and display each vowel from a

String after 3 seconds.

import java.io.*;

public class Slip17A {

public static void main(String args[]) {

alpha a1 = new alpha();

a1.start();

class alpha extends Thread {

public void run(){


try{

DataInputStream din = new DataInputStream(System.in);

System.out.print("Enter String : ");

String str = din.readLine();

String str1 = str.toLowerCase();

for(int i=0; i<=str1.length(); i++){

if(str1.charAt(i)=='a' || str1.charAt(i)=='e'|| str1.charAt(i)=='


i' || str1.charAt(i)=='o' || str1.charAt(i)=='u' ){

System.out.println(str1.charAt(i));

sleep(3000);

}catch(Exception e){}

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”.

Server file

import java.io.*;

import java.net.*;
public class Server {

public static void main(String[] args) throws Exception {

ServerSocket ss = new ServerSocket(5400);

while (true) {

Socket s = ss.accept();

DataOutputStream dos = new DataOutputStream(s.getOutputStream());

File f = new File("E:\addvans-java\src\jsp\server.text");

if (f.exists()) {

Scanner sc = new Scanner(f);

while (sc.hasNextLine()) {

String str = sc.nextLine();

dos.writeUTF(f.getName() + " = file content = " + str);

} else {

String stra = "file is not Exists on SERVER";


dos.writeUTF(" Error -- " + stra);

client file

import java.net.*;

import java.io.*;

public class Client {

public static void main(String[] args) throws IOException {

Socket s = new Socket("localhost", 5400);

DataInputStream dis = new DataInputStream(s.getInputStream());

System.out.print("result = ");

System.out.print(dis.readUTF());

}
Slip 18

Write a java program to calculate factorial of a number. (Use sleep () method). [15 M]

import java.io.*;

public class Slip18A {

public static void main(String args[]) {

alpha a1 = new alpha();

a1.start();

class alpha extends Thread {

public void run() {

try {

DataInputStream br = new DataInputStream(System.in);

System.out.print("Enter Number : ");

int n = Integer.parseInt(br.readLine());

int a = 0, b = 1;

for (int i = 1; i <= n; ++i) {

System.out.print(a + " | ");

int c = a + b;

a = b;

b = c;

sleep(1000);
}

} catch (Exception e) {

Write a java program for simple standalone chatting application.

Server Code:

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

public class ChatServer {


public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(5000); // Start server on port 5000
System.out.println("Server started. Waiting for clients to connect...");

Socket clientSocket = serverSocket.accept(); // Wait for client to connect


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

BufferedReader in = new BufferedReader(new


InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

BufferedReader consoleIn = new BufferedReader(new InputStreamReader(System.in));

String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Client: " + inputLine); // Display client message

String response = consoleIn.readLine(); // Read server response from console


out.println(response); // Send server response to client
}

in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
}

Client Code:

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

public class ChatClient {


public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 5000); // Connect to server on port 5000

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));


PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

BufferedReader consoleIn = new BufferedReader(new InputStreamReader(System.in));

String inputLine;
while ((inputLine = consoleIn.readLine()) != null) {
out.println(inputLine); // Send client message to server

String response = in.readLine(); // Read server response


System.out.println("Server: " + response); // Display server response
}

in.close();
out.close();
socket.close();
}
}

Slip 19

Write a JSP program which accept UserName in a TextBox and greets the user according to the time on
server machine. [15 M]

File : Slip19A.jsp

<%

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

java.util.Date d=new java.util.Date();

int hr=d.getHours();
if(hr<12) {

out.println("Good Morning : "+name);

if(hr>12 && hr<16)

out.println(" Good Afternoon : "+name);

if(hr>16)

out.println(" Good Evening:"+name);

%>

File : Slip19A.html

<html>

<body>

<form action="http://localhost:8080/jsp/Slip19A/Slip19A.jsp" method="post">

<input type="text" name="username">

<input type="submit">

</form>

</body>

</html>
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 java.sql.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class Slip4B extends JFrame implements ActionListener {

JButton jb;

JTextField t1, t2, t3;

Container c;

Connection con;

Statement st;

ResultSet rs;

public Slip4B() {

c = getContentPane();

c.setLayout(null);

t1 = new JTextField();
t1.setFont(new Font("Arial", Font.PLAIN, 20));

t1.setSize(200, 30);

t1.setLocation(100, 50);

c.add(t1);

t2 = new JTextField();

t2.setFont(new Font("Arial", Font.PLAIN, 20));

t2.setSize(200, 30);

t2.setLocation(100, 100);

c.add(t2);

t3 = new JTextField();

t3.setFont(new Font("Arial", Font.PLAIN, 20));

t3.setSize(200, 30);

t3.setLocation(100, 150);

c.add(t3);

jb = new JButton(">> DISPLAY FIRST RECORD<<");

jb.setFont(new Font("Arial", Font.PLAIN, 20));

jb.setSize(200, 30);

jb.addActionListener(this);

jb.setLocation(100, 200);

c.add(jb);
setVisible(true);

setSize(800, 500);

public void actionPerformed(ActionEvent aq) {

try {

Class.forName("com.mysql.jdbc.Driver");

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Server
", "root", "12345");

if (aq.getSource() == jb) {

st = con.createStatement(rs.TYPE_SCROLL_SENSITIVE, rs.CONCUR_READ
_ONLY);

rs = st.executeQuery("Select * from Student;");

rs.first();

t1.setText(Integer.toString(rs.getInt(1)));

t2.setText(rs.getString(2));

t3.setText(Integer.toString(rs.getInt(3)));

con.close();

} catch (Exception ex) {

public static void main(String args[]) throws Exception {


new Slip4B();

Slip 20

Write a JDBC program to delete the details of given employee (ENo EName Salary). Accept employee ID
through command line. [15 M]

import java.sql.*;

public class EmployeeDelete {


public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: EmployeeDelete <employee_id>");
return;
}
int employeeId = Integer.parseInt(args[0]);

try {
// Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");

// Connect to the database


Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost/mydatabase", "username", "password");

// Prepare the SQL statement


PreparedStatement pstmt = conn.prepareStatement(
"DELETE FROM Emp WHERE ENo = ?");
pstmt.setInt(1, employeeId);

// Execute the SQL statement


int rowsDeleted = pstmt.executeUpdate();
if (rowsDeleted == 0) {
System.out.println("No employee found with ID " + employeeId);
} else {
System.out.println("Employee with ID " + employeeId + " deleted successfully");
}

// Close the database connection


pstmt.close();
conn.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Write a java program in multithreading using applet for drawing temple.

import java.awt.*;

public class Slip20B extends Frame {

int f = 0;

public Slip20B() {

Signal s = new Signal();

s.start();

setSize(500, 500);

setVisible(true);

public void paint(Graphics g) {

switch (f) {

case 0:

g.drawRect(100, 150, 90, 120);

case 1:

g.drawRect(130, 230, 20, 40);

case 2:

g.drawLine(150, 100, 100, 150);


case 3:

g.drawLine(150, 100, 190, 150);

case 4:

g.drawLine(150, 50, 150, 100);

case 5:

g.drawRect(150, 50, 20, 20);

class Signal extends Thread {

public void run() {

while (true) {

f = (f + 1) % 5;

repaint();

try {

Thread.sleep(1000);

} catch (Exception e) {

}
public static void main(String args[]) {

new Slip20B();

Slip 21

Write a java program to display name and priority of a Thread. [15 M]

public class Slip21A {

public static void main(String args[]) {

Thread t = Thread.currentThread();

t.setPriority(2);

System.out.println("Thread Name : "+t.getName());

System.out.println("Thread Prioriy : "+t.getPriority());

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.*;
import java.sql.*;

public class StudentServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


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

// Retrieve student details from form


String seatNo = request.getParameter("seatNo");
String studName = request.getParameter("studName");
String studentClass = request.getParameter("class");
int totalMarks = Integer.parseInt(request.getParameter("totalMarks"));

// Calculate percentage and grade


float percentage = (float) totalMarks / 5;
String grade;
if (percentage >= 80) {
grade = "A";
} else if (percentage >= 60) {
grade = "B";
} else if (percentage >= 40) {
grade = "C";
} else {
grade = "D";
}

// Display student details and grade


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>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></html>");
}
}

Slip 22

Write a java program to display Date and Time of Server machine on client machine. [15 M]

import java.io.*;

import java.net.*;

import java.util.Date;

class Slip22A {

public static void main(String args[]) throws Exception {


Socket s = new Socket("localhost", 4545);

DataInputStream dis = new DataInputStream(s.getInputStream());

System.out.print("Current Date and Time : " + dis.readLine());

//Server

import java.io.*;

import java.net.*;

import java.util.Date;

class Slip22A1 {

public static void main(String args[]) throws Exception {

ServerSocket ss = new ServerSocket(4545);

Socket s = ss.accept();

Date d = new Date();

DataOutputStream dos = new DataOutputStream(s.getOutputStream());

dos.writeBytes(d + "\n");

s.close();
}

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 language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Account Details</title>
</head>
<body>
<h1>Account Details</h1>
<form method="post" action="addAccount.jsp">
Account Number: <input type="text" name="accountNumber" /><br>
Account Type: <input type="text" name="accountType" /><br>
Balance: <input type="text" name="balance" /><br>
<input type="submit" value="Add Account" />
</form>

<%-- Connect to database --%>


<%
String dbUrl = getServletContext().getInitParameter("db.url");
String dbUsername = getServletContext().getInitParameter("db.username");
String dbPassword = getServletContext().getInitParameter("db.password");
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
} catch (ClassNotFoundException | SQLException e) {
out.println("Failed to connect to database.");
e.printStackTrace();
return;
}

// Add account to database


String accountNumber = request.getParameter("accountNumber");
String accountType = request.getParameter("accountType");
double balance = Double.parseDouble(request.getParameter("balance"));
String sql = "INSERT INTO accounts (account_number, account_type, balance) VALUES (?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, accountNumber);
statement.setString(2, accountType);
statement.setDouble(3, balance);
int rowsInserted = statement.executeUpdate();
statement.close();
if (rowsInserted > 0) {
out.println("Account added successfully.");
} else {
out.println("Failed to add account.");
}

// Display accounts from database


sql = "SELECT * FROM accounts";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);

out.println("<h2>Accounts</h2>");
out.println("<table border='1'>");
out.println("<tr><th>Account Number</th><th>Account Type</th><th>Balance</th></tr>");
while (rs.next()) {
String accNo = rs.getString("account_number");
String accType = rs.getString("account_type");
double accBal = rs.getDouble("balance");
out.println("<tr><td>" + accNo + "</td><td>" + accType + "</td><td>" + accBal + "</td></tr>");
}
out.println("</table>");
rs.close();
stmt.close();
connection.close();
%>
</body>
</html>

Slip 23

Write a Java Program to display the details of College(CID, CName, address, Year) on JTable. [15 M]

import java.sql.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class CollegeDetailsProgram extends JFrame {


private JTable table;

public CollegeDetailsProgram() {
setTitle("College Details");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);

// Create a table model with column names


String[] columnNames = {"CID", "CName", "Address", "Year"};
DefaultTableModel model = new DefaultTableModel(columnNames, 0);

// Connect to the database and retrieve the college details


try {
// Step 1: Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");

// Step 2: Establish the connection to the database


String url = "jdbc:mysql://localhost/mydatabase";
String username = "root";
String password = "password";
Connection connection = DriverManager.getConnection(url, username, password);

// Step 3: Retrieve the college details from the database


String query = "SELECT * FROM college";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
while (resultSet.next()) {
String cid = resultSet.getString("CID");
String cname = resultSet.getString("CName");
String address = resultSet.getString("Address");
int year = resultSet.getInt("Year");
model.addRow(new Object[]{cid, cname, address, year});
}

// Step 4: Close the database resources


resultSet.close();
statement.close();
connection.close();
} catch (ClassNotFoundException e) {
System.out.println("JDBC driver not found.");
} catch (SQLException e) {
System.out.println("SQL exception occurred: " + e.getMessage());
}

// Create the JTable and add it to the JFrame


table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);

// Show the JFrame


setVisible(true);
}

public static void main(String[] args) {


new CollegeDetailsProgram();
}
}
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 java.sql.*;
import java.util.Properties;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginServlet extends HttpServlet {


private static final long serialVersionUID = 1L;
private Connection connection;

@Override
public void init() throws ServletException {
// Load database configuration from properties file
Properties props = new Properties();
try {
props.load(getServletContext().getResourceAsStream("/dbconfig.properties"));
String dbUrl = props.getProperty("db.url");
String dbUsername = props.getProperty("db.username");
String dbPassword = props.getProperty("db.password");

// Establish a connection to the database


connection = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
} catch (IOException | SQLException e) {
throw new ServletException("Failed to initialize database connection.", e);
}
}

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doPost(request, response);
}

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Get the username and password from the request parameters
String username = request.getParameter("username");
String password = request.getParameter("password");

// Check if the username and password are valid


boolean isValidUser = false;
try {
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, username);
statement.setString(2, password);
ResultSet resultSet = statement.executeQuery();
isValidUser = resultSet.next();
statement.close();
} catch (SQLException e) {
throw new ServletException("Failed to search for user.", e);
}

// Send appropriate response based on search results


if (isValidUser) {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>Welcome, " + username + "!</h2>");
out.println("</body></html>");
} else {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid username or
password.");
}
}

@Override
public void destroy() {
// Close the database connection
try {
connection.close();
} catch (SQLException e) {
throw new RuntimeException("Failed to close database connection.", e);
}
}
}

Slip 24

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. [15 M]

<%@ 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>
<style>
.red-text {
color: red;
}
</style>
</head>
<body>
<h1>Number to Words Converter</h1>
<form action="convert.jsp" method="post">
<label for="number">Enter a number:</label>
<input type="text" id="number" name="number" />
<br /><br />
<input type="submit" value="Convert to Words" />
</form>

<%-- Check if the number parameter is present in the request --%>


<% if (request.getParameter("number") != null) { %>
<%-- Convert the number to words --%>
<%
String number = request.getParameter("number");
String[] words = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
String result = "";
for (int i = 0; i < number.length(); i++) {
int digit = Character.getNumericValue(number.charAt(i));
result += words[digit] + " ";
}
%>
<%-- Display the result in red color --%>
<h2><span class="red-text"><%= result %></span></h2>
<% } %>
</body>
</html>

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;

public class EmpTable {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("\nEmp Table Menu:");
System.out.println("1. Insert record");
System.out.println("2. Update record");
System.out.println("3. Delete record");
System.out.println("4. Search by ENo");
System.out.println("0. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
insertRecord();
break;
case 2:
updateRecord();
break;
case 3:
deleteRecord();
break;
case 4:
searchRecord();
break;
case 0:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice, please try again.");
}
} while (choice != 0);
scanner.close();
}

private static void insertRecord() {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter ENo: ");
int ENo = scanner.nextInt();
System.out.print("Enter EName: ");
String EName = scanner.next();
System.out.print("Enter salary: ");
double salary = scanner.nextDouble();
System.out.print("Enter Desg: ");
String Desg = scanner.next();
// TODO: Add code to insert record into Emp table
System.out.println("Record inserted successfully.");
}

private static void updateRecord() {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter ENo to update: ");
int ENo = scanner.nextInt();
// TODO: Check if record with ENo exists
System.out.print("Enter new EName: ");
String EName = scanner.next();
System.out.print("Enter new salary: ");
double salary = scanner.nextDouble();
System.out.print("Enter new Desg: ");
String Desg = scanner.next();
// TODO: Add code to update record in Emp table
System.out.println("Record updated successfully.");
}

private static void deleteRecord() {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter ENo to delete: ");
int ENo = scanner.nextInt();
// TODO: Check if record with ENo exists
// TODO: Add code to delete record from Emp table
System.out.println("Record deleted successfully.");
}

private static void searchRecord() {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter ENo to search: ");
int ENo = scanner.nextInt();
// TODO: Add code to search for record in Emp table based on ENo
// TODO: Print the record if found, otherwise print "Record not found."
}
}

Slip 25

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. [15 M]

//Client

import java.io.*;

import java.net.*;

class Slip25A {

public static void main(String args[]) throws Exception {

Socket s = new Socket("localhost", 2121);

DataInputStream din = new DataInputStream(System.in);

System.out.print("Enter the number : ");

String n = din.readLine();

DataOutputStream dos = new DataOutputStream(s.getOutputStream());


dos.writeBytes(n + "\n");

System.out.println("<<<<Factors>>>>");

int arr[] = new int[15];

DataInputStream dis = new DataInputStream(s.getInputStream());

for (int i = 0; i < 15; i++) {

arr[i] = dis.readInt();

System.out.println(arr[i] + " ");

//Server

import java.io.*;

import java.net.*;

import java.util.Date;
class Slip25A1 {

public static void main(String args[]) throws Exception {

ServerSocket ss = new ServerSocket(2121);

Socket s = ss.accept();

DataInputStream dis = new DataInputStream(s.getInputStream());

int n = Integer.parseInt(dis.readLine());

int arr[] = new int[15];

int i, j = 0;

DataOutputStream dos = new DataOutputStream(s.getOutputStream());

for (i = 1; i <= n; i++) {

if (n % i == 0) {

arr[j] = i;

dos.writeInt(arr[j]);

j++;

} else {

arr[j] = arr[j - 1];

s.close();

}
Write a Java Program for the following: Assume database is already created.

import java.sql.*;

public class DatabaseProgram {


public static void main(String[] args) {
try {
// Step 1: Load the JDBC driver
Class.forName("com.mysql.jdbc.Driver");

// Step 2: Establish the connection to the database


String url = "jdbc:mysql://localhost/mydatabase";
String username = "root";
String password = "password";
Connection connection = DriverManager.getConnection(url, username, password);

// Step 3: Perform some database operations


// Example: Execute a SQL query to retrieve all records from a table
String query = "SELECT * FROM mytable";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
double salary = resultSet.getDouble("salary");
String department = resultSet.getString("department");
System.out.println("Record: " + id + ", " + name + ", " + salary + ", " + department);
}

// Step 4: Close the database resources


resultSet.close();
statement.close();
connection.close();
} catch (ClassNotFoundException e) {
System.out.println("JDBC driver not found.");
} catch (SQLException e) {
System.out.println("SQL exception occurred: " + e.getMessage());
}
}
}

Slip 26

Write a java program to display list of college names from college table. (Assume College table (CID,
CName, addr) is already created. [15 M]

import java.sql.*;
class Slip26A {

public static void main(String args[]) throws Exception {

Class.forName("com.mysql.jdbc.Driver");

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306


/bcadb", "root", "");

Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery("select cname from college");

System.out.println("<<<<College Name>>>>");

System.out.println("===================");

while (rs.next()) {

System.out.println(rs.getString(1));

con.close();

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.IOException;
import java.io.PrintWriter;
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("/hobbyServlet")
public class HobbyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String COOKIE_NAME = "selectedHobby";

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>My Hobbies</title>");
out.println("</head>");
out.println("<body>");
out.println("<h3>Select your favorite hobby:</h3>");
out.println("<form 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='submit' value='Submit' />");
out.println("<input type='reset' value='Reset' />");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
String selectedHobby = request.getParameter("hobby");

// Check if the cookie with the same name already exists


boolean cookieExists = false;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(COOKIE_NAME)) {
cookieExists = true;
break;
}
}
}

// If cookie does not exist, create it and add it to the response


if (!cookieExists) {
Cookie hobbyCookie = new Cookie(COOKIE_NAME, selectedHobby);
hobbyCookie.setMaxAge(60 * 60 * 24 * 365); // set cookie to last 1 year
response.addCookie(hobbyCookie);
}

// Display a message to the user


response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>My Hobbies</title>");
out.println("</head>");
out.println("<body>");
out.println("<h3>Your selected hobby is: " + selectedHobby + "</h3>");
out.println("<p>Cookie created successfully!</p>");
out.println("</body>");
out.println("</html>");
}
}

Slip 27

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. [15 M]

<%@ page language="java" %>


<html>
<head>
<title>Teacher Details Example</title>
</head>
<body>
<h1>Teacher Details Example</h1>

<form method="post">
TID: <input type="text" name="tid"><br><br>
TName: <input type="text" name="tname"><br><br>
Desg: <input type="text" name="desg"><br><br>
Subject: <input type="text" name="subject"><br><br>
Qualification: <input type="text" name="qualification"><br><br>
<input type="submit" value="Submit">
</form>

<br><br>

<%
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");

if (tid != null && !tid.isEmpty() && tname != null && !tname.isEmpty() &&
desg != null && !desg.isEmpty() && subject != null && !subject.isEmpty() &&
qualification != null && !qualification.isEmpty()) {
out.println("<h3>Teacher Details:</h3>");
out.println("TID: " + tid + "<br>");
out.println("TName: " + tname + "<br>");
out.println("Desg: " + desg + "<br>");
out.println("Subject: " + subject + "<br>");
out.println("Qualification: " + qualification + "<br>");
}
%>

</body>
</html>

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 {
// Connect to database
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase",
"username", "password");

// Create statement with scrollable ResultSet


Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("SELECT * FROM Teacher");

// Move to last row


rs.last();

// Get row count


int rowCount = rs.getRow();

System.out.println("Total number of rows: " + rowCount);

// Move to first row


rs.first();

// Print all rows


while (rs.next()) {
System.out.println("TID: " + rs.getInt("TID") +
", TName: " + rs.getString("TName") +
", Salary: " + rs.getDouble("Salary") +
", Subject: " + rs.getString("Subject"));
}
// Move to previous row
rs.previous();

// Print the data of the previous row


System.out.println("Previous Row Data: TID=" + rs.getInt("TID") +
", TName=" + rs.getString("TName") +
", Salary=" + rs.getDouble("Salary") +
", Subject=" + rs.getString("Subject"));

// Move to next row


rs.next();

// Print the data of the next row


System.out.println("Next Row Data: TID=" + rs.getInt("TID") +
", TName=" + rs.getString("TName") +
", Salary=" + rs.getDouble("Salary") +
", Subject=" + rs.getString("Subject"));

// Move to first row again


rs.first();

// Close ResultSet, statement, and connection


rs.close();
stmt.close();
conn.close();

} catch (SQLException e) {
e.printStackTrace();
}

Slip 28

Write a java program for the implementation of synchronization. [15 M]

class msg {

synchronized void dis(){

System.out.println("Hi");

synchronized void disp(){


System.out.println("Bye");

class Demo1 implements Runnable{

msg m;

Demo1(msg m1){

m = m1;

Thread t = new Thread(this);

t.start();

public void run(){

while(true){

m.dis();

class Demo2 implements Runnable{

msg m;

Demo2(msg m2){

m = m2;

Thread t = new Thread(this);

t.start();
}

public void run(){

while(true){

m.disp();

class Slip28A{

public static void main(String args[]){

msg mg = new msg();

Demo1 d1 = new Demo1(mg);

Demo2 d2 = new Demo2(mg);

Write a Java program to design a following screen:

If user selects EmpNo from Choice component then details of selected employee must be displayed in
JTable.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.sql.*;

import javax.swing.table.*;

import java.util.*;
public class Slip28B extends JFrame implements ItemListener

JFrame f1;

JLabel l1;

JComboBox cmb;

JPanel p1;

JTable jt;

JScrollPane jp;

DefaultTableModel dtm;

GridLayout g1,g2;

Connection con;

Statement stmt;

ResultSet rs;

public Slip28B()

l1= new JLabel("Select Emp No");

cmb= new JComboBox();

dtm=new DefaultTableModel();

dtm.addColumn("Emp No");

dtm.addColumn("Emp Name");
dtm.addColumn("Emp Salary");

jt=new JTable(dtm);

g1=new GridLayout(1,2);

p1= new JPanel();

p1.setLayout(g1);

p1.add(l1); p1.add(cmb);

g2=new GridLayout(2,1);

f1=new JFrame();

f1.setLayout(g2);

jp=new JScrollPane(jt);

add(p1,BorderLayout.NORTH);

add(jp,BorderLayout.CENTER);

this.setSize(500,500);

this.setVisible(true);

cmb.addItemListener(this);

try

Class.forName("com.mysql.jdbc.Driver");

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bcadb","root
","");

stmt=con.createStatement();

rs=stmt.executeQuery("select * from emp");


cmb.addItem("--");

}catch(Exception e){}

public void itemStateChanged(ItemEvent ie)

try

while(rs.next())

cmb.addItem(rs.getInt(1));

int en=Integer.parseInt(cmb.getSelectedItem().toString());

rs=stmt.executeQuery("select * from emp where eid="+en+"");

if(rs.next())

Vector v=new Vector();

v.add(rs.getInt(1));

v.add(rs.getString(2));
v.add(rs.getInt(3));

if(dtm.getRowCount()>0)

dtm.removeRow(0);

dtm.addRow(v);

//con.close();

}catch(Exception e1){}

public static void main(String args[])

new Slip28B();

Slip 29

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. [15 M]

import java.io.*;

public class Slip29A {

public static void main(String args[]) {

try {

DataInputStream br = new DataInputStream(System.in);


System.out.println("********* java program using multithreading
*********");

System.out.print("Enter Number : ");

int n = Integer.parseInt(br.readLine());

OddNumber a1 = new OddNumber(n);

a1.start();

PrimeNumber a2 = new PrimeNumber(n);

a2.start();

} catch (Exception e) {}

class OddNumber extends Thread {

int odd;

OddNumber(int n) {

odd = n;

public void run() {

System.out.println("****** Odd Numbers *******");

for (int i = 1; i <= odd; i++) {


if (i % 2 != 0) {

System.out.print(i + " | ");

System.out.println();

class PrimeNumber extends Thread {

int prime;

PrimeNumber(int n){

prime = n;

public void run() {

System.out.println("****** Prime Numbers *******");

for (int i = 2; i <= prime; i++) {

boolean isPrime = true;

for (int j = 2; j <= i / 2; j++) {

if (i % j == 0) {

isPrime = false;

break;

}
if (isPrime == true)

System.out.print(i + " | ");

Write a SERVLET program to change inactive time interval of session.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ChangeSessionTimeoutServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Set content type


response.setContentType("text/html");

// Get current session


HttpSession session = request.getSession();

// Get current timeout value


int currentTimeout = session.getMaxInactiveInterval();

// Print current timeout value


PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h3>Current Session Timeout: " + currentTimeout + " seconds</h3>");

// Display form to change timeout value


out.println("<form method='post' action='" + request.getContextPath() +
"/ChangeSessionTimeoutServlet'>");
out.println("Enter new timeout value (in seconds): <input type='text' name='timeout'>");
out.println("<input type='submit' value='Change'>");
out.println("</form>");

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

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Get new timeout value from form data
int newTimeout = Integer.parseInt(request.getParameter("timeout"));

// Get current session


HttpSession session = request.getSession();

// Set new timeout value


session.setMaxInactiveInterval(newTimeout);

// Redirect to doGet method to display updated timeout value


response.sendRedirect(request.getContextPath() + "/ChangeSessionTimeoutServlet");

Slip 30

Write a JSP script to accept a String from a user and display it in reverse order. [15 M]

<%@ page language="java" %>


<html>
<head>
<title>Reverse String Example</title>
</head>
<body>
<h1>Reverse String Example</h1>

<form method="post">
Enter a String: <input type="text" name="inputString"><br><br>
<input type="submit" value="Reverse">
</form>

<br><br>

<%
String inputString = request.getParameter("inputString");
if (inputString != null && !inputString.isEmpty()) {
String reversedString = new StringBuilder(inputString).reverse().toString();
out.println("Original String: " + inputString + "<br>");
out.println("Reversed String: " + reversedString);
}
%>

</body>
</html>
Write a java program in multithreading using applet for moving car.

import java.applet.Applet;

import java.awt.*;

public class Slip30B extends Applet implements Runnable {

int x, z;

Thread t;

Image pic;

public void init() {

x = 50;

pic = getImage(getDocumentBase(), "./car.png");

t = new Thread(this);

t.start();

public void run() {

while (true) {

repaint();

x = x + 10;

if (x >= this.getWidth()) {

System.exit(0);
}

try {

Thread.sleep(100);

} catch (Exception e) {

public void paint(Graphics g) {

g.drawLine(0, 165, this.getWidth(), 165);

g.drawImage(pic, x, 120, this);

You might also like