0% found this document useful (0 votes)
4 views35 pages

Adv Java Slip Sol

The document contains multiple Java programming tasks including creating a text scrolling application, a chat application using sockets, a JSP program for checking perfect numbers, and an applet for drawing a flag. It also includes a socket program for checking prime numbers, a bouncing ball applet, and a servlet for providing HTTP request information. Additionally, there are tasks for deleting student names starting with 'S', calculating the sum of first and last digits of a number, and implementing a traffic signal using multithreading in an applet.

Uploaded by

hackerpratik959
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)
4 views35 pages

Adv Java Slip Sol

The document contains multiple Java programming tasks including creating a text scrolling application, a chat application using sockets, a JSP program for checking perfect numbers, and an applet for drawing a flag. It also includes a socket program for checking prime numbers, a bouncing ball applet, and a servlet for providing HTTP request information. Additionally, there are tasks for deleting student names starting with 'S', calculating the sum of first and last digits of a number, and implementing a traffic signal using multithreading in an applet.

Uploaded by

hackerpratik959
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

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

continuously.
import [Link].*;
import [Link].*;
import [Link].*;
public class BlinkText extends JFrame implements Runnable
{
Thread t;
Label l1;
int f;
public BlinkText()
{
t=new Thread(this);
[Link]();
setLayout(null);
l1=new Label("Hello JAVA");
[Link](100,100,100,40);
add(l1);
setSize(300,300);
setVisible(true);
f=0;
}
public void run()
{
try
{
if(f==0)
{
[Link](200);
[Link]("");
f=1;
}
if(f==1)
{
[Link](200);
[Link]("Hello Java");
f=0;
}
}catch(Exception e)
{
[Link](e);
}
run();
}
public static void main(String args[])
{
new BlinkText();
}
}
B) Write a socket program in java for chatting application.(Use Swing)
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

class MyServer extends JFrame implements ActionListener


{
static JTextField t1=new JTextField(20);
static JButton b1=new JButton("Send");
static JTextArea ta=new JTextArea(5,20);
static DataOutputStream dos;
static DataInputStream dis;
static ServerSocket st;
static Socket s;
static String r;
MyServer() throws IOException
{
setLayout(new FlowLayout());
add(t1);add(b1);add(ta);
[Link](this);
setVisible(true);
setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

st=new ServerSocket(1281);
s=[Link]();
dos=new DataOutputStream([Link]());
dis=new DataInputStream([Link]());
while(true)
{
r=[Link]();
[Link]("client:"+r+"\n");
}
}
public void actionPerformed(ActionEvent e)
{
String cmd=[Link]();
if([Link]("send"))
{
try
{
r=[Link]();
[Link](r);
}
catch(Exception p)
{
}
}
}
}
class Slip1_BChatServer
{
public static void main(String[] d ) throws IOException
{
new MyServer();

Slip 2 A)Write a jsp program to check whether given number is Perfect or not. (Use Include
directive).

[Link] (Main Page)


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Perfect Number Checker</title>
</head>
<body>

<center>
<h2>Perfect Number Checker</h2>

<form method="post">
Enter a Number:
<input type="number" name="number" required/>
<input type="submit" value="Check"/>
</form>

<%@ include file="[Link]" %>


</center>

</body>
</html>

[Link] (Included File)


<%
String numStr = [Link]("number");

if(numStr != null && ![Link]()) {


int num = [Link](numStr);
int sum = 0;

// Find divisors and calculate sum


for(int i = 1; i < num; i++) {
if(num % i == 0) {
sum = sum + i;
}
}

// Check if perfect number


if(sum == num && num != 0) {
[Link]("<div style='color:green; font-size:18px; margin-top:20px;'>");
[Link]("✅ " + num + " is a PERFECT NUMBER!");
[Link]("<br>Divisors: ");

// Display divisors
for(int i = 1; i < num; i++) {
if(num % i == 0) {
[Link](i + " ");
}
}
[Link]("<br>Sum of divisors = " + sum);
[Link]("</div>");
} else {
[Link]("<div style='color:red; font-size:18px; margin-top:20px;'>");
[Link]("❌ " + num + " is NOT a perfect number!");
[Link]("<br>Sum of divisors = " + sum);
[Link]("</div>");
}
}
%>

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


import [Link];
import [Link];
import [Link];

/*
<applet code="FlagApplet" width="400" height="300">
</applet>
*/

public class FlagApplet extends Applet {

StripeThread saffron, white, green;

public void init() {


saffron = new StripeThread(this, [Link], 50);
white = new StripeThread(this, [Link], 100);
green = new StripeThread(this, [Link], 150);

[Link]();
[Link]();
[Link]();
}
}
class StripeThread extends Thread {

Applet app;
Color color;
int y;

StripeThread(Applet app, Color color, int y) {


[Link] = app;
[Link] = color;
this.y = y;
}

public void run() {


try {
[Link](500); // delay to show multithreading
Graphics g = [Link]();
[Link](color);
[Link](50, y, 300, 50);

// Draw Ashoka Chakra in white stripe


if (color == [Link]) {
[Link]([Link]);
[Link](175, y + 10, 30, 30);
}

} catch (Exception e) {
[Link](e);
}
}
}

Slip 3 A) Write a socket program in Java to check whether given number is prime or not.
Display result on client terminal
Server Program ([Link])
import [Link].*;
import [Link].*;

public class PrimeServer {


public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(5000);
[Link]("Server started...");

Socket s = [Link]();
[Link]("Client connected");

DataInputStream dis = new DataInputStream([Link]());


DataOutputStream dos = new DataOutputStream([Link]());

int num = [Link]();


boolean isPrime = true;
if (num <= 1)
isPrime = false;
else {
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}

if (isPrime)
[Link]("Number is Prime");
else
[Link]("Number is Not Prime");

[Link]();
[Link]();
} catch (Exception e) {
[Link](e);
}
}
}

Client Program ([Link])


import [Link].*;
import [Link].*;
import [Link];

public class PrimeClient {


public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 5000);

DataInputStream dis = new DataInputStream([Link]());


DataOutputStream dos = new DataOutputStream([Link]());

Scanner sc = new Scanner([Link]);

[Link]("Enter a number: ");


int num = [Link]();

[Link](num);

String result = [Link]();


[Link]("Result from Server: " + result);

[Link]();
} catch (Exception e) {
[Link](e);
}
}
}

B) Write a java program using applet for bouncing ball, for each bounce color of ball should
change randomly.
import [Link].*;
import [Link];
import [Link];

/*
* <applet code="[Link]" width=400 height=300></applet>
*/

public class BouncingBallApplet extends Applet implements Runnable {


private int x = 50, y = 50; // Ball's current position
private int dx = 5, dy = 5; // Ball's movement speed and direction
private int radius = 20; // Ball's radius
private Color ballColor = [Link]; // Initial ball color
private Random random;
private Thread animationThread;
private Dimension appletSize;

public void init() {


random = new Random();
appletSize = getSize();
// Set a background color for visibility
setBackground([Link]);
}

public void start() {


if (animationThread == null) {
animationThread = new Thread(this);
[Link]();
}
}

public void stop() {


animationThread = null;
}

public void run() {


while (animationThread != null) {
try {
[Link](30); // Sleep for a short time to create animation
} catch (InterruptedException e) {
[Link]();
}
// Update ball position and check for bounces
moveBall();
repaint(); // Calls the paint method
}
}
private void moveBall() {
// Move the ball
x += dx;
y += dy;

// Check for horizontal wall collisions


if (x - radius < 0 || x + radius > [Link]) {
dx = -dx; // Reverse horizontal direction
changeColor();
// Keep ball inside bounds if it slightly exceeds the edge
if (x - radius < 0) x = radius;
if (x + radius > [Link]) x = [Link] - radius;
}

// Check for vertical wall collisions


if (y - radius < 0 || y + radius > [Link]) {
dy = -dy; // Reverse vertical direction
changeColor();
// Keep ball inside bounds if it slightly exceeds the edge
if (y - radius < 0) y = radius;
if (y + radius > [Link]) y = [Link] - radius;
}
}

private void changeColor() {


// Generate a new random color using random RGB values
int r = [Link](256);
int g = [Link](256);
int b = [Link](256);
ballColor = new Color(r, g, b);
}

public void paint(Graphics g) {


// Use double buffering to prevent flickering
Image buffer = createImage([Link], [Link]);
Graphics offscreen = [Link]();
[Link](getBackground());
[Link](0, 0, [Link], [Link]);

[Link](ballColor);
[Link](x - radius, y - radius, radius * 2, radius * 2);

[Link](buffer, 0, 0, this);
}

// Update method to handle double buffering correctly


public void update(Graphics g) {
paint(g);
}
}
Slip 4 A) Write a Java Program to delete details of students whose initial character of their
name is ‘S’
import [Link].*;

public class SimpleStudentDeletion {


public static void main(String[] args) {
// Create ArrayList to store student names
ArrayList<String> students = new ArrayList<>();

// Add student names


[Link]("John");
[Link]("Sarah");
[Link]("Mike");
[Link]("Steve");
[Link]("Emma");
[Link]("Sam");
[Link]("Lisa");

// Display original list


[Link]("Original Student List: " + students);

// Remove students whose name starts with 'S' or 's'


for (int i = 0; i < [Link](); i++) {
if ([Link](i).toUpperCase().charAt(0) == 'S') {
[Link](i);
i--; // Adjust index after removal
}
}

// Display final list


[Link]("After removing names starting with 'S': " + students);
}
}

B) Write a SERVLET program that provides information about a HTTP request from a client,
such as IP address and browser type. The servlet also provides information about the server
on which the servlet is running, such as the operating system type, and the names of
currently loaded servlets.
import [Link].*;
import [Link].*;
import [Link].*;

public class SimpleRequestInfoServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();

// Client Info
[Link]("<html><body>");
[Link]("<h2>Client Information:</h2>");
[Link]("IP Address: " + [Link]() + "<br>");
[Link]("Browser: " + [Link]("User-Agent") + "<br><br>");

// Server Info
[Link]("<h2>Server Information:</h2>");
[Link]("OS: " + [Link]("[Link]") + "<br>");
[Link]("Server Name: " + [Link]() + "<br>");
[Link]("Server Port: " + [Link]() + "<br>");
[Link]("Java Version: " + [Link]("[Link]") + "<br><br>");

// Loaded Servlets
[Link]("<h2>Loaded Servlets:</h2>");
[Link]("- RequestInfoServlet (current)<br>");
[Link]("- Default Servlet<br>");
[Link]("- JSP Servlet<br>");

[Link]("</body></html>");
}
}

Slip 5 A) Write a JSP program to calculate sum of first and last digit of a given number.
Display sum in Red Color with font size 18.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<title>First + Last Digit Sum</title>
</head>
<body>

<center>
<h2>Sum of First and Last Digit</h2>

<form method="post">
<input type="number" name="n" required placeholder="Enter any number"/>
<input type="submit" value="Find Sum"/>
</form>

<%
String n = [Link]("n");
if (n != null) {
int num = [Link](n);
num = [Link](num);

int last = num % 10;


int first = num;

while(first >= 10) {


first = first / 10;
}

int sum = first + last;

[Link]("<h3 style='color:red; font-size:18px;'>");


[Link]("First Digit: " + first + "<br/>");
[Link]("Last Digit: " + last + "<br/>");
[Link]("SUM = " + sum);
[Link]("</h3>");
}
%>
</center>

</body>
</html>

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


import [Link].*;
import [Link].*;

public class TrafficSignalApplet extends Applet implements Runnable {

Thread thread;
String currentLight = "RED";

public void init() {


setBackground(Color.LIGHT_GRAY);
setSize(300, 400);

// Start the thread


thread = new Thread(this);
[Link]();
}

public void run() {


while (true) {
try {
// RED light for 5 seconds
currentLight = "RED";
[Link](5000);

// YELLOW light for 2 seconds


currentLight = "YELLOW";
[Link](2000);

// GREEN light for 5 seconds


currentLight = "GREEN";
[Link](5000);
} catch (InterruptedException e) {
[Link]();
}
}
}

public void paint(Graphics g) {


// Draw traffic signal pole
[Link](Color.DARK_GRAY);
[Link](140, 50, 20, 300);

// Draw traffic signal box


[Link]([Link]);
[Link](70, 60, 160, 200);

// Draw RED light


if ([Link]("RED")) {
[Link]([Link]);
} else {
[Link](Color.DARK_GRAY);
}
[Link](105, 80, 90, 60);

// Draw YELLOW light


if ([Link]("YELLOW")) {
[Link]([Link]);
} else {
[Link](Color.DARK_GRAY);
}
[Link](105, 130, 90, 60);

// Draw GREEN light


if ([Link]("GREEN")) {
[Link]([Link]);
} else {
[Link](Color.DARK_GRAY);
}
[Link](105, 180, 90, 60);

// Display current light text


[Link]([Link]);
[Link](new Font("Arial", [Link], 14));
[Link]("Current: " + currentLight + " Light", 100, 290);

// Display instruction
if ([Link]("RED")) {
[Link]("STOP!", 130, 330);
} else if ([Link]("YELLOW")) {
[Link]("READY!", 130, 330);
} else {
[Link]("GO!", 130, 330);
}
}
}

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

import [Link].*;
import [Link].*;

public class BlinkImage extends Frame implements Runnable {

Image img;
boolean visible = true;
Thread t;

public BlinkImage() {
// Load image (keep image in same folder or give full path)
img = [Link]().getImage("[Link]");

setSize(400, 400);
setTitle("Blinking Image");
setVisible(true);

// Close window
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});

// Start thread
t = new Thread(this);
[Link]();
}

public void paint(Graphics g) {


if (visible) {
[Link](img, 100, 100, this);
}
}

public void run() {


while (true) {
try {
visible = !visible; // toggle visibility
repaint(); // redraw frame
[Link](500); // delay (milliseconds)
} catch (InterruptedException e) {
[Link](e);
}
}
}

public static void main(String[] args) {


new BlinkImage();
}
}

B) Write a SERVLET program which counts how many times a user has visited a web
page. If user is visiting the page for the first time, display a welcome message. If the
user is revisiting the page, display the number of times visited. (Use Cookie)

import [Link];
import [Link];
import [Link].*;
import [Link].*;
public class Slip6Q2 extends HttpServlet{
static int i=1;
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException {
[Link]("text/html");
PrintWriter out=[Link]();
String k=[Link](i);
Cookie c=new Cookie("visit",k);
[Link](c);
int j=[Link]([Link]());
if(j==1) {
[Link]("Welcome to web page ");
}
else {
[Link]("You are visited at "+i+" times");
}
i++;
}
}

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

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<title>Email Validator</title>
</head>
<body>

<center>
<h2>Email ID Validation</h2>

<form method="post">
Email: <input type="text" name="email" />
<input type="submit" value="Check" />
</form>
<%
String email = [Link]("email");

if(email != null && ![Link]()) {

// Simple regex for email validation


String regex = "^[A-Za-z0-9+_.-]+@(.+)$";

if([Link](regex) && [Link](".")) {


[Link]("<p style='color:green; font-size:18px;'>");
[Link]("Valid Email ID: " + email);
[Link]("</p>");
} else {
[Link]("<p style='color:red; font-size:18px;'>");
[Link](" Invalid Email ID: " + email);
[Link]("</p>");
}
}
%>
</center>

</body>
</html>

B) Write a Multithreading program in java to display the number’s between 1 to 100


continuously in a TextField by clicking on button. (use Runnable Interface).

import [Link].*;
import [Link].*;

public class Slip7Q2 implements Runnable{


static TextArea textArea;
public static void main(String[] args) {
JFrame mainframe = new JFrame("Display the number from 1 to 100");
textArea = new TextArea();
[Link](10, 30, 300, 300);
[Link](textArea);
[Link](500, 500);
[Link](null);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
Slip7Q2 obj = new Slip7Q2();
Thread t1 = new Thread(obj);
[Link]();
}

@Override
public void run() {
for (int i = 1; i<=100; i++){
[Link]([Link](i)+"\n");
}
}
}

slip 8 A) Write a Java Program to display all the employee names whose initial character of
a name is ‘A’

import [Link].*;

public class EmployeeNamesA {


public static void main(String[] args) {

// Create ArrayList of employee names


ArrayList<String> employees = new ArrayList<>();

// Add employee names


[Link]("Amit");
[Link]("Rahul");
[Link]("Anjali");
[Link]("Suresh");
[Link]("Aparna");
[Link]("Vikram");
[Link]("Akshay");
[Link]("Priya");

[Link]("All Employee Names: " + employees);


[Link]("\nEmployees whose name starts with 'A':");

// Display names starting with 'A' or 'a'


for(String name : employees) {
if([Link]().charAt(0) == 'A') {
[Link]("✓ " + name);
}
}
}
}

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

import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];

public class Slip8Q2 extends Applet implements Runnable {

Thread t1 = null;
int hours = 0, minutes = 0, seconds = 0;
String time = "";
public void init() {
setBackground( [Link]);
}
public void start() {
t1 = new Thread( this );
[Link]();
}

public void run() {


try {
while (true) {
Calendar cal = [Link]();
hours = [Link]( Calendar.HOUR_OF_DAY );
if ( hours > 12 ) hours -= 12;
minutes = [Link]( [Link] );
seconds = [Link]( [Link] );
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
Date d = [Link]();
time = [Link]( d );
repaint();
[Link]( 1000 );
}
}
catch (Exception ignored) { }
}
public void paint( Graphics g ) {
[Link]( [Link] );
[Link](new Font("",[Link],100));
[Link]( time, 100, 150 );
}
}
/*<applet code= "[Link]" height="300" width="600"></applet>*/

Slip 9 A) Write a Java Program to create a Emp (ENo, EName, Sal) table and insert record
into it. (Use PreparedStatement Interface)

import [Link].*;

public class EmployeeTableDemo {

public static void main(String[] args) {

try {
// 1. Load and register JDBC driver
[Link]("[Link]");

// 2. Establish connection
Connection con = [Link](
"jdbc:mysql://localhost:3306/testdb",
"root",
"password"
);
// 3. Create Statement
Statement stmt = [Link]();

// 4. Create Emp table


String createTableSQL = "CREATE TABLE IF NOT EXISTS Emp (" +
"ENo INT PRIMARY KEY, " +
"EName VARCHAR(50), " +
"Sal DECIMAL(10,2))";

[Link](createTableSQL);
[Link]("✓ Emp table created successfully!");

// 5. Insert records using PreparedStatement


String insertSQL = "INSERT INTO Emp (ENo, EName, Sal) VALUES (?, ?, ?)";
PreparedStatement pstmt = [Link](insertSQL);

// Insert first record


[Link](1, 101);
[Link](2, "John Doe");
[Link](3, 50000.00);
[Link]();

// Insert second record


[Link](1, 102);
[Link](2, "Jane Smith");
[Link](3, 60000.00);
[Link]();

// Insert third record


[Link](1, 103);
[Link](2, "Bob Wilson");
[Link](3, 55000.00);
[Link]();

[Link]("✓ Records inserted successfully!");

// 6. Display the records


ResultSet rs = [Link]("SELECT * FROM Emp");

[Link]("\nEmployee Records:");
[Link]("-----------------------------------");
while([Link]()) {
[Link]("ENo: " + [Link]("ENo") +
", EName: " + [Link]("EName") +
", Sal: " + [Link]("Sal"));
}

// 7. Close connections
[Link]();
[Link]();
[Link]();
[Link]();

} catch (ClassNotFoundException e) {
[Link]("JDBC Driver not found: " + e);
} catch (SQLException e) {
[Link]("SQL Error: " + e);
}
}
}

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)

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

import [Link].*;

public class ClientInfo {


public static void main(String[] args) {
try {
// Get local host information
InetAddress localhost = [Link]();

// Get IP Address
String ipAddress = [Link]();

// Get Host Name


String hostName = [Link]();

// Display information
[Link]("=== Client Machine Information ===");
[Link]("Host Name: " + hostName);
[Link]("IP Address: " + ipAddress);

} catch (UnknownHostException e) {
[Link]("Error: Unable to get host information");
[Link]();
}
}
}

B) Write a Java program to display sales details of Product (PID, PName, Qty, Rate, Amount)
between two selected dates. (Assume Sales table is already created).

import [Link].*;
import [Link];

public class SimpleSalesReport {


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

[Link]("[Link]");
Connection con = [Link]("jdbc:mysql://localhost:3306/testdb", "root", "password");
Scanner sc = new Scanner([Link]);

[Link]("Start Date (YYYY-MM-DD): ");


String start = [Link]();
[Link]("End Date (YYYY-MM-DD): ");
String end = [Link]();

PreparedStatement ps = [Link]("SELECT * FROM Sales WHERE SaleDate BETWEEN ? AND ?");


[Link](1, start);
[Link](2, end);

ResultSet rs = [Link]();

[Link]("\nPID\tPName\t\tQty\tRate\tAmount\tSaleDate");
[Link]("------------------------------------------------");

double total = 0;
while([Link]()) {
[Link]([Link]("PID") + "\t" +
[Link]("PName") + "\t" +
[Link]("Qty") + "\t" +
[Link]("Rate") + "\t" +
[Link]("Amount") + "\t" +
[Link]("SaleDate"));
total += [Link]("Amount");
}

[Link]("------------------------------------------------");
[Link]("TOTAL: " + total);

[Link]();
[Link]();
}
}

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

import [Link].*;

public class CountRecords {


public static void main(String[] args) {
try {
// Connect to database
Connection con = [Link](
"jdbc:mysql://localhost:3306/testdb",
"root",
"password"
);

// Query to count records


String query = "SELECT COUNT(*) FROM Sales";
Statement stmt = [Link]();
ResultSet rs = [Link](query);

// Get the count


if([Link]()) {
int count = [Link](1);
[Link]("Total records in Sales table: " + count);
}

[Link]();
[Link]();
[Link]();

} catch(SQLException e) {
[Link]("Error: " + [Link]());
}
}
}

B) Write a program in java which will show lifecycle (creation, sleep, and dead) of a thread.
Program should print randomly the name of thread and value of sleep time. The name of
the thread should be hard coded through constructor. The sleep time of a thread will be a
random integer in the range 0 to 4999.

import [Link];

class MyThread extends Thread {


private String threadName;
private int sleepTime;
private Random rand;

// Constructor - hard coded name


public MyThread(String name) {
[Link] = name;
[Link] = new Random();
[Link] = [Link](5000); // 0 to 4999
}

public void run() {


try {
// Thread is running
[Link]("" + threadName + " is CREATED and STARTED");
[Link]("" + threadName + " will sleep for " + sleepTime + " milliseconds");

// Thread goes to sleep


[Link](sleepTime);
// Thread wakes up
[Link]("" + threadName + " woke up after " + sleepTime + "ms");

} catch (InterruptedException e) {
[Link]("" + threadName + " was interrupted");
}

// Thread is dead
[Link]("" + threadName + " is DEAD (Thread execution completed)");
[Link]("-------------------------------------------");
}
}

public class ThreadLifecycleDemo {


public static void main(String[] args) {
[Link]("=== THREAD LIFECYCLE DEMO ===\n");

// Create threads with hardcoded names


MyThread t1 = new MyThread("Thread-A");
MyThread t2 = new MyThread("Thread-B");
MyThread t3 = new MyThread("Thread-C");

// Start threads
[Link]();
[Link]();
[Link]();

[Link]("Main thread continues while child threads run...\n");


}
}

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


multithreading.

public class CurrentThreadDemo {


public static void main(String[] args) {
// Get current thread
Thread currentThread = [Link]();

// Display thread name


[Link]("Currently executing thread: " + [Link]());
}
}

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

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<title>College Details</title>
</head>
<body>

<center>
<h2>College Details</h2>

<table border="1" cellpadding="10" cellspacing="0">


<tr bgcolor="lightblue">
<th>College ID</th>
<th>College Name</th>
<th>Address</th>
</tr>
<tr>
<td>101</td>
<td>ABC College of Engineering</td>
<td>New Delhi, India</td>
</tr>
<tr>
<td>102</td>
<td>XYZ Institute of Technology</td>
<td>Mumbai, India</td>
</tr>
<tr>
<td>103</td>
<td>PQR Science College</td>
<td>Bangalore, India</td>
</tr>
<tr>
<td>104</td>
<td>LMN Arts & Commerce College</td>
<td>Chennai, India</td>
</tr>
</table>
</center>

</body>
</html>

Slip 14 A) Write a JSP program to accept Name and Age of Voter and check whether he is
eligible for voting or not.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<title>Voter Eligibility Checker</title>
</head>
<body>

<center>
<h2>Voter Eligibility Check</h2>
<form method="post">
Name: <input type="text" name="name" required/><br/><br/>
Age: <input type="number" name="age" required/><br/><br/>
<input type="submit" value="Check Eligibility"/>
</form>

<%
String name = [Link]("name");
String ageStr = [Link]("age");

if(name != null && ageStr != null) {


int age = [Link](ageStr);

if(age >= 18) {


[Link]("<h3 style='color:green'>Hello " + name + ", You are eligible for voting!</h3>");
} else {
[Link]("<h3 style='color:red'>Sorry " + name + ", You are not eligible for voting!</h3>");
[Link]("<p>You need to wait " + (18 - age) + " more years.</p>");
}
}
%>
</center>

</body>
</html>

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

import [Link].*;

public class DisplayFilesByExtension {


public static void main(String[] args) {

// Specify directory path


String directoryPath = "C:/Users/YourName/Documents";
String extension = ".txt"; // Change to .pdf, .jpg, etc.

File directory = new File(directoryPath);

// Check if directory exists


if([Link]() && [Link]()) {
File[] files = [Link]();

[Link]("Files with " + extension + " extension in " + directoryPath + ":");


[Link]("------------------------------------------------");

boolean found = false;

for(File file : files) {


if([Link]().endsWith(extension)) {
[Link](“" + [Link]());
found = true;
}
}

if(!found) {
[Link]("No files found with " + extension + " extension");
}
} else {
[Link]("Directory not found!");
}
}
}

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

public class AlphabetWithDelay {


public static void main(String[] args) {

[Link]("Displaying alphabets with 2 seconds delay:\n");

for(char c = 'a'; c <= 'z'; c++) {


[Link](c + " ");

try {
[Link](2000); // Wait for 2 seconds
} catch(InterruptedException e) {
[Link]("Thread interrupted!");
}
}

[Link]("\n\nFinished displaying all alphabets!");


}
}

B) Write a Java program to accept the details of Student (RNo, SName, Per, Gender, Class)
and store into the database. (Use appropriate Swing Components and PreparedStatement
Interface).

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class StudentForm extends JFrame implements ActionListener {

// Swing Components
JLabel lblRNo, lblName, lblPer, lblGender, lblClass;
JTextField txtRNo, txtName, txtPer;
JRadioButton rbMale, rbFemale;
ButtonGroup genderGroup;
JComboBox<String> cmbClass;
JButton btnSave, btnReset, btnExit;

// Database connection
Connection con;
PreparedStatement pstmt;

public StudentForm() {
setTitle("Student Registration Form");
setSize(500, 400);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

// Initialize components
lblRNo = new JLabel("Roll Number:");
[Link](50, 50, 100, 25);
add(lblRNo);

txtRNo = new JTextField();


[Link](180, 50, 200, 25);
add(txtRNo);

lblName = new JLabel("Student Name:");


[Link](50, 90, 100, 25);
add(lblName);

txtName = new JTextField();


[Link](180, 90, 200, 25);
add(txtName);

lblPer = new JLabel("Percentage:");


[Link](50, 130, 100, 25);
add(lblPer);

txtPer = new JTextField();


[Link](180, 130, 200, 25);
add(txtPer);

lblGender = new JLabel("Gender:");


[Link](50, 170, 100, 25);
add(lblGender);

rbMale = new JRadioButton("Male");


[Link](180, 170, 80, 25);
rbFemale = new JRadioButton("Female");
[Link](270, 170, 80, 25);

genderGroup = new ButtonGroup();


[Link](rbMale);
[Link](rbFemale);

add(rbMale);
add(rbFemale);

lblClass = new JLabel("Class:");


[Link](50, 210, 100, 25);
add(lblClass);

String[] classes = {"FY BCA", "SY BCA", "TY BCA", "FY BSc", "SY BSc", "TY BSc"};
cmbClass = new JComboBox<>(classes);
[Link](180, 210, 200, 25);
add(cmbClass);

btnSave = new JButton("Save");


[Link](80, 270, 100, 30);
[Link](this);
add(btnSave);

btnReset = new JButton("Reset");


[Link](200, 270, 100, 30);
[Link](this);
add(btnReset);

btnExit = new JButton("Exit");


[Link](320, 270, 100, 30);
[Link](this);
add(btnExit);

// Connect to database
connectDB();

setVisible(true);
}

void connectDB() {
try {
[Link]("[Link]");
con = [Link](
"jdbc:mysql://localhost:3306/testdb",
"root",
"password"
);

// Create table if not exists


String createTable = "CREATE TABLE IF NOT EXISTS Student (" +
"RNo INT PRIMARY KEY, " +
"SName VARCHAR(50), " +
"Per DECIMAL(5,2), " +
"Gender VARCHAR(10), " +
"Class VARCHAR(20))";
Statement stmt = [Link]();
[Link](createTable);

[Link]("Database connected successfully!");


} catch(Exception e) {
[Link](this, "Database Error: " + [Link]());
}
}

public void actionPerformed(ActionEvent e) {


if([Link]() == btnSave) {
saveStudent();
} else if([Link]() == btnReset) {
resetForm();
} else if([Link]() == btnExit) {
[Link](0);
}
}

void saveStudent() {
try {
// Get values from form
int rno = [Link]([Link]());
String name = [Link]();
double per = [Link]([Link]());

String gender = "";


if([Link]()) gender = "Male";
else if([Link]()) gender = "Female";

String className = (String) [Link]();

// Insert using PreparedStatement


String sql = "INSERT INTO Student (RNo, SName, Per, Gender, Class) VALUES (?, ?, ?, ?, ?)";
pstmt = [Link](sql);
[Link](1, rno);
[Link](2, name);
[Link](3, per);
[Link](4, gender);
[Link](5, className);

int result = [Link]();

if(result > 0) {
[Link](this, "Student Record Saved Successfully!");
resetForm();
}

} catch(NumberFormatException e) {
[Link](this, "Please enter valid numbers!");
} catch(SQLException e) {
if([Link]().contains("Duplicate")) {
[Link](this, "Roll Number already exists!");
} else {
[Link](this, "Database Error: " + [Link]());
}
} catch(Exception e) {
[Link](this, "Error: " + [Link]());
}
}

void resetForm() {
[Link]("");
[Link]("");
[Link]("");
[Link]();
[Link](0);
[Link]();
}

public static void main(String[] args) {


new StudentForm();
}
}

Slip 18 A) Write a java program to calculate factorial of a number. (Use sleep () method).

import [Link];

public class FactorialWithSleep {


public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter a number: ");


int num = [Link]();

long factorial = 1;

[Link]("\nCalculating factorial of " + num + "...\n");

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


factorial *= i;
[Link]("Step " + i + ": Multiply by " + i + " = " + factorial);

try {
[Link](1000); // 1 second delay between steps
} catch(InterruptedException e) {
[Link]("Thread interrupted!");
}
}

[Link]("\n✅ Factorial of " + num + " is: " + factorial);


[Link]();
}
}

B) Write a java program for simple standalone chatting application.


[Link]

import [Link].*;
import [Link].*;
import [Link];

public class ChatServer {


public static void main(String[] args) {
try {
// Create server socket on port 12345
ServerSocket serverSocket = new ServerSocket(12345);
[Link]("Server started. Waiting for client...");

// Accept client connection


Socket socket = [Link]();
[Link]("Client connected!");

// Create input and output streams


DataInputStream dis = new DataInputStream([Link]());
DataOutputStream dos = new DataOutputStream([Link]());
Scanner sc = new Scanner([Link]);

String clientMessage = "", serverMessage = "";

while(true) {
// Receive message from client
clientMessage = [Link]();
[Link]("Client: " + clientMessage);

if([Link]("bye")) {
[Link]("Client disconnected!");
break;
}

// Send message to client


[Link]("You: ");
serverMessage = [Link]();
[Link](serverMessage);

if([Link]("bye")) {
[Link]("Server disconnected!");
break;
}
}

[Link]();
[Link]();
[Link]();

} catch(Exception e) {
[Link]("Error: " + [Link]());
}
}
}

[Link]

import [Link].*;
import [Link].*;
import [Link];

public class ChatClient {


public static void main(String[] args) {
try {
// Connect to server
Socket socket = new Socket("localhost", 12345);
[Link]("Connected to server!");

// Create input and output streams


DataInputStream dis = new DataInputStream([Link]());
DataOutputStream dos = new DataOutputStream([Link]());
Scanner sc = new Scanner([Link]);

String clientMessage = "", serverMessage = "";

while(true) {
// Send message to server
[Link]("You: ");
clientMessage = [Link]();
[Link](clientMessage);

if([Link]("bye")) {
[Link]("You left the chat!");
break;
}

// Receive message from server


serverMessage = [Link]();
[Link]("Server: " + serverMessage);

if([Link]("bye")) {
[Link]("Server disconnected!");
break;
}
}

[Link]();
[Link]();

} catch(Exception e) {
[Link]("Error: " + [Link]());
}
}
}
Slip 20 A) Write a JDBC program to delete the details of given employee (ENo EName
Salary). Accept employee ID through command line.

import [Link].*;

public class DeleteEmployee {


public static void main(String[] args) {

// Check if employee ID is provided


if([Link] == 0) {
[Link]("Please provide Employee ID!");
[Link]("Usage: java DeleteEmployee <EmployeeID>");
return;
}

int empId = [Link](args[0]);

try {
// Connect to database
Connection con = [Link](
"jdbc:mysql://localhost:3306/testdb",
"root",
"password"
);

// Check if employee exists


String checkQuery = "SELECT * FROM Emp WHERE ENo = ?";
PreparedStatement checkStmt = [Link](checkQuery);
[Link](1, empId);
ResultSet rs = [Link]();

if([Link]()) {
// Display employee details before deletion
[Link]("Employee Found:");
[Link]("ID: " + [Link]("ENo"));
[Link]("Name: " + [Link]("EName"));
[Link]("Salary: " + [Link]("Sal"));

// Delete employee
String deleteQuery = "DELETE FROM Emp WHERE ENo = ?";
PreparedStatement pstmt = [Link](deleteQuery);
[Link](1, empId);

int rowsDeleted = [Link]();

if(rowsDeleted > 0) {
[Link]("\n✅ Employee deleted successfully!");
}

[Link]();
} else {
[Link](" Employee with ID " + empId + " not found!");
}

[Link]();
[Link]();
[Link]();

} catch(SQLException e) {
[Link]("Database Error: " + [Link]());
} catch(NumberFormatException e) {
[Link]("Invalid Employee ID! Please enter a number.");
}
}
}

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

import [Link].*;
import [Link].*;

public class TempleApplet extends Applet implements Runnable {

Thread thread;
int flag = 0;
int lightState = 0;

public void init() {


setBackground([Link]);
setSize(600, 500);

thread = new Thread(this);


[Link]();
}

public void run() {


while(true) {
try {
// Change light colors every second
lightState = (lightState + 1) % 3;
repaint();
[Link](1000);
} catch(InterruptedException e) {}
}
}

public void paint(Graphics g) {


// Draw ground
[Link]([Link]);
[Link](0, 350, 600, 150);

// Draw sun
[Link]([Link]);
[Link](500, 50, 60, 60);
// Temple base
[Link](new Color(210, 180, 140)); // Sand color
[Link](150, 250, 300, 100);

// Temple walls
[Link]([Link]);
[Link](180, 200, 80, 50);
[Link](340, 200, 80, 50);

// Main temple body


[Link](new Color(255, 215, 0)); // Gold color
[Link](230, 150, 140, 100);

// Temple door
[Link](new Color(139, 69, 19)); // Brown
[Link](270, 250, 60, 100);

// Door arch
[Link]([Link]);
[Link](270, 250, 60, 50, 0, 180);

// Temple roof (top)


[Link]([Link]);
int xPoints[] = {200, 300, 400};
int yPoints[] = {150, 80, 150};
[Link](xPoints, yPoints, 3);

// Temple roof decorations


[Link]([Link]);
[Link](290, 70, 20, 20);

// Pillars
[Link]([Link]);
[Link](160, 250, 20, 100);
[Link](420, 250, 20, 100);

// Decorative lights (changing colors)


if(lightState == 0) [Link]([Link]);
else if(lightState == 1) [Link]([Link]);
else [Link]([Link]);

[Link](290, 160, 20, 20);


[Link](310, 160, 20, 20);

// Flags on top
[Link]([Link]);
[Link](297, 55, 6, 30);
[Link](new int[]{297, 330, 297}, new int[]{55, 65, 75}, 3);

// Title
[Link]([Link]);
[Link](new Font("Arial", [Link], 20));
[Link]("HAPPY TEMPLE", 240, 400);
// Animation text
[Link](new Font("Arial", [Link], 12));
[Link]("Temple Lights Changing...", 240, 430);
}
}

You might also like