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

Advance Java Slip Solution

The document contains various Java programming tasks, including creating applets for text scrolling, socket programming for chat applications, JSP programs for number validation, and multithreading examples like bouncing balls and traffic signals. It also includes database operations for deleting student records and servlet examples for handling HTTP requests and visit counting using cookies. Each section provides code snippets and explanations for implementing the specified functionalities.

Uploaded by

Shreya Gosavi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views

Advance Java Slip Solution

The document contains various Java programming tasks, including creating applets for text scrolling, socket programming for chat applications, JSP programs for number validation, and multithreading examples like bouncing balls and traffic signals. It also includes database operations for deleting student records and servlet examples for handling HTTP requests and visit counting using cookies. Each section provides code snippets and explanations for implementing the specified functionalities.

Uploaded by

Shreya Gosavi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 49

A) Write a java program to scroll the text from left to right and vice

versa continuously.

Answer :

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

/*

* <applet code="Slip1A.class" width="300" height="300">

* </applet>

*/

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

Answer :

//Server

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
A) Write a JSP program to check whether given number is Perfect or
not. (Use Include

directive).

Answer :

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>

B) Write a java program in multithreading using applet for drawing


flag.

Answer :

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();

}
SLIP3

A) Write a socket program in Java to check whether given number is


prime or not.

Display result on client terminal.

Answer :

//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();

}
B) Write a java program using applet for bouncing ball, for each bounce
color of ball

should change randomly.

Answer :

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();

}
SLIP4

A) Write a Java Program to delete details of students whose initial character of


their

name is ‘S’.

Answer :

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();

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.

Answer :
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


IOException, 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();

}
SLIP5

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.

Answer :

<%@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>

Output :

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

Answer :

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();

}
SLIP6

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

Answer :

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();

}
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)

Answer :

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();

SLIP7

A) Write a JSP script to validate given E-Mail ID.

Answer :

<%@ 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"

%>

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

Answer :

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

}
SLIP8

A) Write a Java Program to display all the employee names whose initial
character of a

name is ‘A’.

Answer :

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();

B) Write a java program in multithreading using applet for Digital watch.

Answer :

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

}
/*

* <applet code="Slip8B.class" width="300" height="300">

* </applet>

*/

SLIP9

A) Write a Java Program to create a Emp (ENo, EName, Sal) table and insert
record

into it. (Use PreparedStatement Interface)

Answer :

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();

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)

Answer :

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

%>
SLIP10

A) Write a java Program in Hibernate to display “Hello world” message.

Answer :

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();
}
}

Output :

B) Write a SERVLET program to display the details of Product (ProdCode, PName,

Price) on the browser in tabular format. (Use database)

Answer :

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);
}
}
}
SLIP11

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

Answer :

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());
}
}
}

Output :
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).

Answer :

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();
}
}
}
SLIP12

A) Write a java program to count the number of records in a table.

Answer :

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();

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.

Answer :

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.");
}
}
SLIP13

A) Write a java program to display name of currently executing Thread in

multithreading.

Answer :
public class Slip13A {

public static void main(String[] args) {

Thread t = Thread.currentThread();

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

B) Write a JSP program to display the details of College (CollegeID, Coll_Name,

Address) in tabular form on browser.

Answer :

<%@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>
SLIP14

A) Write a JSP program to accept Name and Age of Voter and check whether he
is

eligible for voting or not.

Answer :

<%@ 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>

Output :

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

server machine.

Answer :

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());
}
}
}
}
SLIP15

A) Write a java program to display each alphabet after 2 seconds between ‘a’ to
‘z’.

Answer :

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) {

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

Answer :

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);
}
}
}

You might also like