0% found this document useful (0 votes)
16 views47 pages

Java Multithreading and GUI Examples

The document contains practical Java programming exercises focused on Object-Oriented Programming and Multithreading. It includes tasks such as displaying alphabets using threads, creating a GUI for employee data entry, managing collections like HashSet and LinkedList, and implementing traffic signals and number generation with multi-threading. Additionally, it covers database operations for creating and managing product records using JDBC.

Uploaded by

umama9091
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)
16 views47 pages

Java Multithreading and GUI Examples

The document contains practical Java programming exercises focused on Object-Oriented Programming and Multithreading. It includes tasks such as displaying alphabets using threads, creating a GUI for employee data entry, managing collections like HashSet and LinkedList, and implementing traffic signals and number generation with multi-threading. Additionally, it covers database operations for creating and managing product records using JDBC.

Uploaded by

umama9091
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

Object Oriented Programming Java 2

Practical Slips

/*
Write a Java program using Multithreading to display all the
alphabets between ‘A’ to
‘Z’ after every 2 seconds.
*/

package [Link];
import [Link].*;
public class slip1_1
{
public static void main(String[] args)
{
Thread t = new Thread(() ->
{
while(true)
{
for(char ch = 'A'; ch <= 'Z'; ch++)
[Link](ch + " ");
[Link]();

try
{
[Link](2000);
}
catch (InterruptedException ex)
{
[Link](slip1_1.[Link]()).log
([Link], null, ex);
}
[Link]("2 seconds are passed....");
}
});

[Link]();
}
}
/*
Slip no 2 Write a Java program to accept the details of Employee
(Eno, EName, Designation,Salary) from a user and store it into
the database. (Use Swing)
*/
package [Link].prac1;
import [Link].*;
import [Link];
import [Link];
import [Link].*;
import [Link].*;
import [Link].*;
class EmpApp {
private JFrame frame;
private JTextField eno, ename, desig, sal;
private JButton clear, insert;

EmpApp() throws SQLException {


frame = new JFrame("Employee App");
[Link](400, 200);
[Link](new GridLayout(5,2));

eno = new JTextField();


ename = new JTextField();
desig = new JTextField();
sal = new JTextField();

[Link](new JLabel("Eno."));
[Link](eno);
[Link](new JLabel("EName"));
[Link](ename);
[Link](new JLabel("Designation"));
[Link](desig);
[Link](new JLabel("Salary"));
[Link](sal);

clear = new JButton("Clear");


insert = new JButton("insert");

Connection conn =
[Link]("jdbc:postgresql://localhost:5432/pos
tgres", "postgres", "bhalchandra");

[Link]((ActionEvent e) -> {
try {
insertEmp(conn, eno, ename, desig, sal);
} catch (IOException | SQLException ex) {
[Link]([Link]()).log(Leve
[Link], null, ex);
}
});

[Link]((ActionEvent e) -> {
[Link]("");
[Link]("");
[Link]("");
[Link]("");
});

[Link](insert);
[Link](clear);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
private static void insertEmp(Connection conn, JTextField
eno, JTextField ename, JTextField desig, JTextField sal)
throws IOException, SQLException {
String sql = "insert into emp values(?, ?, ?, ?)";
PreparedStatement ps = [Link](sql);
[Link](1, [Link]([Link]()));
[Link](2, [Link]());
[Link](3, [Link]());
[Link](4, [Link]([Link]()));
[Link]();
}
}
public class slip1_2
{
public static void main(String[] args) throws SQLException {
new EmpApp();
}
}

/*
Slip no 2 Q1 Write a java program to read ‘N’ names of your
friends, store it into HashSet and
display them in ascending order.
*/
package [Link].practical_slip;
import [Link].*;;
public class slip2_1
{
public static void main(String[] args)
{
HashSet<String> friends = new HashSet<>();
Scanner scan = new Scanner([Link]);
[Link]("Enter N :");
int n = [Link]();
[Link]();
for(int i = 0 ; i<n;i++)
{
[Link]("Enter name :");
String name = [Link]();
[Link](name);
}
TreeSet<String> tree = new TreeSet<>(friends);
[Link](tree);

}
}

/*
Slip no 3 Q1. Write a JSP program to display the details of
Patient (PNo, PName, Address, age,
disease) in tabular form on browser*/

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Patient</h1>
<table border="1">
<tr>
<th>PNo</th>
<th>PName</th>
<th>Address</th>
<th>age</th>
<th>disease</th>
</tr>
<tr>
<td>1</td>
<td>John</td>
<td>xyz</td>
<td>45</td>
<td>kovid</td>
</<tr>
<tr>
<td>2</td>
<td>Brock</td>
<td>abc</td>
<td>48</td>
<td>canser</td>
</<tr>
</table>
</body>
</html>
*/

/*
Slip no 3 Q2. Write a Java program to create LinkedList of
String objects and perform the following:
i. Add element at the end of the list
ii. Delete first element of the list
iii. Display the contents of list in reverse order
*/
package [Link];
import [Link].*;
public class slip3_2 {
public static void main(String[] args) {
LinkedList<String> names = new LinkedList<>();
Scanner sc = new Scanner([Link]);
int ch;
do {
[Link]("Menu");
[Link]("1. Insert at tail");
[Link]("2. Delete head.");
[Link]("3. Display in reverse");
[Link]("4. Exit");
[Link]("------------------------------");
[Link]("Enter your choice:");
ch = [Link]();
[Link]();
[Link]();
switch (ch) {
case 1:
[Link]("Enter name.");
[Link]([Link]());
break;
case 2:
[Link]();
break;
case 3:[Link]("Real order");
Iterator itr = [Link]();
while ([Link]())
{
[Link]([Link]());
}
Iterator it = [Link]();
while ([Link]())
{
[Link]([Link]());
}
break;
default:
[Link]("Invalid choice.");
}
[Link]("-------------------------------
");
} while (ch != 4);
}
}

/*
Slip no 4 Q1 Write a Java program using Runnable interface to
blink Text on the JFrame (Use
Swing)
*/
package [Link].practical_slip;
import [Link];
import [Link];
import [Link].*;
class BlinkText implements Runnable
{
private JFrame frame;
private JLabel blink;

public BlinkText() {
frame = new JFrame("Blink Light");
[Link](200, 200);
blink = new JLabel("Blink");
[Link](blink);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
@Override
public void run() {
Random rand = new Random();
while(true) {
int r = [Link](255);
int g = [Link](255);
int b = [Link](255);
[Link](new Color(r, g, b));
}
}
}
public class slip4_1
{
public static void main(String[] args) {
Thread t = new Thread(new BlinkText());
[Link]();
}
}
/*
Slip no 4 Q2. Write a Java program to store city names and their
STD codes using an appropriate
collection and perform following operations:
i. Add a new city and its code (No duplicates)
ii. Remove a city from the collection
iii. Search for a city name and display the code
*/
package [Link].practical_slip;
import [Link].*;
public class slip4_2
{
public static void main(String[] args) {
Map<String, String> cityMap = new HashMap<>();
Scanner sc = new Scanner([Link]);

int ch;
String code, city;
do {
[Link]("Menu");
[Link]("1. Add City and std code.(no
duplicates)");
[Link]("2. Remove City.");
[Link]("3. Search city name dsiplay std
code");
[Link]("4. Exit");

[Link]("------------------------------");
[Link]("Enter your choice:");
ch = [Link]();
[Link]();
[Link]();

switch(ch) {
case 1: [Link]("Enter std code.");
code = [Link]();
[Link]("Enter City.");
city = [Link]();
[Link](code, city);
break;
case 2: [Link]("Enter std code.");
code = [Link]();
[Link](code);
break;
case 3: [Link]("Enter city:");
city = [Link]();
code = null;
for([Link]<String, String> map :
[Link]()) {
if([Link]().equals(city))
code = [Link]();
}
if(code != null)
[Link]("Code is " + code);
else
[Link]("Not found.");
break;
default: [Link]("Invalid choice.");
}
[Link]("-------------------------------
");
} while(ch != 4);
}
}

/*
Slip no5 Q1. Write a Java Program to create the hash table that
will maintain the mobile number and
student name. Display the details of student using Enumeration
interface
*/
package [Link];
import [Link].*;
public class slip5_1
{
public static void main(String[] args)
{
Hashtable<String, String> studentTable = new
Hashtable<>();
[Link]("1234567890", "john");
[Link]("1239874560", "carry");
Enumeration<String> moblieNumbers = [Link]();
while([Link]())
{
String no = [Link]();
String name = [Link](no);
[Link]("Student name: " + name + ",
Mobile no: " + no);
}
}
}

/*
slip no 6 Q1 Write a Java program to accept ‘n’ integers from
the user and store them in a Collection.
Display them in the sorted order. The collection should not
accept duplicate elements.
(Use a suitable collection). Search for a particular element
using predefined search
method in the Collection framework
*/
package [Link].practical_slip;
import [Link].*;
public class slip6_1
{
public static void main(String[] args) {
TreeSet<Integer> nums = new TreeSet<>();
Scanner sc = new Scanner([Link]);

[Link]("How many number:");


int n = [Link]();
[Link]("Eneter " + n + " values:");
for(int i=0; i<n; i++)
[Link]([Link]());

[Link](nums);

[Link]("Enter key to search:");


int key = [Link]();
if([Link](key))
[Link]("Found.");
else
[Link]("Not found.");
}
}
/*
slip no 6 q2 Write a java program using multithreading to
simulate traffic signal (Use Swing).
*/
package [Link].practical_slip;
import [Link].*;
class TrafficLight implements Runnable {
String[] lights = {"Red", "Green", "Yellow"};

@Override
public void run() {
int idx = 0;
while(true) {
[Link]("Current Signal : " +
lights[idx]);
try {
[Link](getDuration(lights[idx]) * 1000);
} catch (InterruptedException ex) {
[Link]([Link]()).lo
g([Link], null, ex);
}
idx = (idx + 1) % [Link];
}
}
private int getDuration(String light) {
switch(light) {
case "Red": return 4;
case "Green": return 7;
case "Yellow": return 2;
default : return 0;
}
}

}
public class slip6_2
{
public static void main(String[] args) {
Thread t = new Thread(new TrafficLight());
[Link]();
}
}

/*
slip no 7 Q2 Write a java program that implements a multi-thread
application that has three threads.
First thread generates random integer number after every one
second, if the number is
even; second thread computes the square of that number and prints
it. If the number is
odd, the third thread computes the cube of that number and prints
it.
*/
package [Link].practical_slip;
import [Link];
import [Link].*;
class NumGenerator implements Runnable {
Random rand = new Random();
int n;
@Override
public void run() {
while(true) {
n = [Link](100);
[Link]("Generated number: " + n);
try {
[Link](1000);
} catch (InterruptedException ex) {
[Link]([Link]()).lo
g([Link], null, ex);
}
}
}
}
class SqrGenerator implements Runnable {
NumGenerator numGenerator;

SqrGenerator(NumGenerator numGenerator) {
[Link] = numGenerator;
}

@Override
public void run() {
while(true) {
int n = numGenerator.n;
if(n % 2 == 0)
[Link]("Square of " + n + " is " +
n*n);
try {
[Link](1000);
} catch (InterruptedException ex) {
[Link]([Link]()).lo
g([Link], null, ex);
}
}
}
}
class CubeGenerator implements Runnable {
NumGenerator numGenerator;
int n;

CubeGenerator(NumGenerator numGenerator) {
[Link] = numGenerator;
}

@Override
public void run() {
while(true) {
int n = numGenerator.n;
if(n % 2 != 0)
[Link]("Cube of " + n + " is " +
n*n*n);
try {
[Link](1000);
} catch (InterruptedException ex) {
[Link]([Link]()).l
og([Link], null, ex);
}
}
}
}
public class slip7_1
{
public static void main(String[] args) {
NumGenerator numGenerator = new NumGenerator();
Thread t1 = new Thread(numGenerator);
[Link]();

SqrGenerator sqrGenerator = new


SqrGenerator(numGenerator);
Thread t2 = new Thread(sqrGenerator);
[Link]();

CubeGenerator cubeGenerator = new


CubeGenerator(numGenerator);
Thread t3 = new Thread(cubeGenerator);
[Link]();
}
}

/*
slip no 7 q2. Write a java program for the following:
i. To create a Product (Pid, Pname, Price) table.
ii. Insert at least five records into the Product table.
iii. Display all the records from a Product table.
Assume Database is already created
*/
package [Link].practical_slip;
import [Link].*;
import [Link];
public class slip7_2
{
public static void main(String[] args) throws SQLException {
Scanner sc = new Scanner([Link]);
Connection conn =
[Link]("jdbc:postgresql://localhost:5432/pos
tgres", "postgres", "postgres");

int ch;
do {
[Link]("Menu");
[Link]("1. Create table Product.");
[Link]("2. Insert into Product.");
[Link]("3. Display records of product.");
[Link]("4. Exit.");

[Link]("------------------------------");
[Link]("Enter your choice:");
ch = [Link]();

switch(ch) {
case 1: create(conn);
break;
case 2: insert(conn);
break;
case 3 : select(conn);
break;
default : [Link]("Invalid choice.");
break;
}
} while(ch != 4);
}
private static void create(Connection conn) throws
SQLException {
String sql = "create table if not exists product("
+ "pid int primary key,"
+ "pname varchar(30),"
+ "price decimal(10, 2))";
Statement stmt = [Link]();
[Link](sql);
}
private static void insert(Connection conn) throws
SQLException {
String sql = "insert into product values(?, ?, ?)";

PreparedStatement pt = [Link](sql);
Scanner sc = new Scanner([Link]);

[Link]("Enter pid:");
int pid = [Link]();
[Link]();

[Link]("Enter pname:");
String name = [Link]();

[Link]("Enter price");
float price = [Link]();
[Link](1, pid);
[Link](2, name);
[Link](3, price);
[Link]();
}
private static void select(Connection conn) throws
SQLException {
String sql = "select * from product";
Statement stmt = [Link]();
[Link](sql);
ResultSet res = [Link]();

while([Link]()) {
[Link]("Pid = " + [Link]("pid"));
[Link]("PName = " +
[Link]("pname"));
[Link]("Price = " +
[Link]("price"));
[Link]("---------------------------------
-------------");
}
}
}

/*
slip no 9 Q1. Write a java program to define a thread for
printing text on output screen for ‘n’
number of times. Create 3 threads and run them. Pass the text ‘n’
parameters to the
thread constructor.
Example:
i. First thread prints “COVID19” 10 times.
ii. Second thread prints “LOCKDOWN2020” 20 times
iii. Third thread prints “VACCINATED2021” 30 times
*/
package [Link].practical_slip;
class T1 extends Thread {
String msg;

T1(String msg) {
[Link] = msg;
}

public void run() {


for(int i=0; i<10; i++)
[Link](msg);
}
}
class T2 extends Thread {
String msg;
T2(String msg) {
[Link] = msg;
}

public void run() {


for(int i=0; i<20; i++)
[Link](msg);
}
}
class T3 extends Thread {
String msg;

T3(String msg) {
[Link] = msg;
}

public void run() {


for(int i=0; i<30; i++)
[Link](msg);
}
}

public class slip8_1


{
public static void main(String[] args) {
T1 t1 = new T1("COVID19");
T2 t2 = new T2("LOCKDOWN2020");
T3 t3 = new T3("VACCINATED2021");

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

/*slip no 8 Q2*/
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
<style>
.prime { color: red; }
</style>
</head>
<body>
<h1>Is prime?</h1>
<form action="[Link]" method="post">
Enter a number: <input type="text" name="num">
<input type="submit" value="is prime ?">
</form>
<%
String numStr = [Link]("num");
int n = 0;

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


n = [Link](numStr);

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

if(isPrime) {
%>
<h3 class="prime">Prime number</h3>
<%
} else {
%>
<h3 class="prime">Not a prime number</h3>
<%
}
}
}
%>
</body>
</html>

/*
slip no 9 Q1. Write a Java program to create a thread for moving
a ball inside a panel vertically. The
ball should be created when the user clicks on the start button
(Use Swing).
*/
package [Link].practical_slip;
import [Link].*;
import [Link];
import [Link].*;
import [Link].*;
class BallPanel extends JPanel
{
private int yDelta = 0;

@Override
protected void paintComponent(Graphics g)
{
[Link](g);
[Link]([Link]);
[Link](175, yDelta, 50, 50);
repaint();
}
void setBallPos(int y) {
[Link] = y;
}
}
public class slip9_1
{
private Thread ballThread;
private BallPanel ballPanel;
private JFrame frame;
private JButton start;

slip9_1()
{
frame = new JFrame("Ball Movement App");
[Link](400, 400);

ballPanel = new BallPanel();

start = new JButton("Start");


[Link]((ActionEvent e) ->
{
startBallMovement();
});

[Link](new BorderLayout());
[Link](ballPanel, [Link]);
[Link](start, [Link]);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}

private void startBallMovement()


{
if(ballThread == null || ![Link]())
{
ballThread = new Thread(() -> {
moveBallVertically();
});
[Link]();
}
}

private void moveBallVertically()


{
int y = 0;
int dir = 1;
while(true)
{
try
{
[Link](15);
} catch (InterruptedException ex)
{
[Link](slip9_1.[Link]()).log(Lev
[Link], null, ex);
}

y += 5 * dir;

if(y > [Link]() - 50)


dir = -1;

if(y <= 0)
dir = 1;

[Link](y);
}
}

public static void main(String[] args)


{
new slip9_1();
}
}
/*
slip no 10 Q2. 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)
*/
package [Link];
import [Link];
import [Link].*;
import [Link].*;
import [Link].*;
class StudentRec
{
private JFrame frame;
private JTextField tf1, tf2, tf3;
private JButton display;

StudentRec() throws SQLException {


frame = new JFrame("Student First Record.");
[Link](200, 300);

tf1 = new JTextField();


tf2 = new JTextField();
tf3 = new JTextField();

display = new JButton("Show Record");


Connection conn =
[Link]("jdbc:postgresql://localhost:5432/pos
tgres", "postgres", "postgres");

[Link]((ActionEvent) -> {
try {
select(conn);
} catch (SQLException ex) {
[Link]([Link]()).log(
[Link], null, ex);
}
});

[Link](new GridLayout(4,1));

[Link](tf1);
[Link](tf2);
[Link](tf3);
[Link](display);

[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
private void select(Connection conn) throws SQLException {
String sql = "select * from student where rno = 1";

Statement stmt = [Link]();


[Link](sql);
ResultSet rs = [Link]();

while([Link]()) {
[Link](" " + [Link]("rno"));
[Link](" " + [Link]("sname"));
[Link](" " + [Link]("per") + "");
}
}
}
public class slip10_2
{
public static void main(String[] args) throws SQLException {
new StudentRec();
}
}

/*
slip no 11 q2 Write a Java program to display information about
all columns in the DONAR table
using ResultSetMetaData.
*/
package [Link];
import [Link].*;
public class slip11_2
{
public static void main(String[] args) throws SQLException {
Connection conn =
[Link]("jdbc:postgresql://localhost:5432/pos
tgres", "postgres", "postgres");

String sql = "select * from donar";

Statement stmt = [Link]();


[Link](sql);

ResultSet rs = [Link]();
ResultSetMetaData rsmd = [Link]();

int colCnt = [Link]();


[Link]("Donar table Meta Data:");
for(int i=1; i<colCnt; i++) {
String colName = [Link](i);
String colType = [Link](i);
int colSize = [Link](i);

[Link](colName + " " + colType + "(" +


colSize + ")");
}
}
}

/* slip no 12 */
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Is Perfect?</h1>
<form action="slip12_1.jsp" method="post">
Enter a number: <input type="text" name="num">
<input type="submit" value="is perfect?">
</form>
<%
String numStr = [Link]("num");
int n = 0;

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


n = [Link](numStr);
if(n > 1) {
int sum = 0;
for(int i=1; i<=n/2; i++) {
if(n % i == 0) {
sum += i;
}
}

if(sum == n) {
%>
<h3>Perfect number</h3>
<%
} else {
%>
<h3>Not a perfect number</h3>
<%
}
}
}
%>
</body>
</html>

/*
slip no 12 Q2 Write a Java Program to create a PROJECT table
with field’s project_id, Project_name,
Project_description, Project_Status. Insert values in the table.
Display all the details of
the PROJECT table in a tabular format on the screen.(using
swing).
*/
package [Link];
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];
class ProjectTable {
private JFrame frame;
private JTable table;

ProjectTable() throws SQLException {


frame = new JFrame("Project Table");
[Link](new BorderLayout());
[Link](600, 150);
Connection conn =
[Link]("jdbc:postgresql://localhost:5432/pos
tgres", "postgres", "postgres");

createTable(conn);
insert(conn);

String[] colNames = {"pid", "pname", "description",


"status"};
String[][] data = retriveData(conn);

table = new JTable(data, colNames);


JScrollPane scrPane = new JScrollPane(table);

[Link]().add(scrPane,
[Link]);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
private void createTable(Connection conn) throws SQLException
{
String sql = "create table if not exists project("
+ "pid int primary key,"
+ "pname varchar(30),"
+ "description varchar(30),"
+ "status varchar(30))";

Statement stmt = [Link]();


[Link](sql);
}
private void insert(Connection conn) throws SQLException {
String sql = "insert into project values"
+ "(1, 'Game', 'Java Platformer Game',
'complete'),"
+ "(2, 'Website', 'MERN stack', 'complete'),"
+ "(3, 'Portfolio', 'PHP', 'complete')";

Statement stmt = [Link]();


[Link](sql);
}
private String[][] retriveData(Connection conn) throws
SQLException {
String sql = "select * from project";
Statement stmt =
[Link](ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = [Link](sql);
ResultSetMetaData rsmd = [Link]();
int noCol = [Link]();
[Link]();
int noRow = [Link]();
[Link]();
String[][] data = new String[noRow][noCol];
int rowCnt = 0;
while ([Link]()) {
for (int i = 1; i <= noCol; i++)
data[rowCnt][i - 1] = [Link](i);
rowCnt++;
}
return data;
}
}
public class slip12_2
{
public static void main(String[] args) throws SQLException {
new ProjectTable();
}
}

/*
Slip no 13 Q1 Write a Java program to display information about
the database and list all the tables in
the database. (Use DatabaseMetaData).
*/
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class slip13_1
{
public static void main(String[] args) throws SQLException {
Connection conn =
[Link]("jdbc:postgresql://localhost:5432/pos
tgres", "postgres", "postgres");
DatabaseMetaData md = [Link]();

[Link]("" + [Link]());
[Link]("" + [Link]());
[Link]("" + [Link]());
[Link]("" + [Link]());

ResultSet tables = [Link](null, null, "%", new


String[]{"TABLE"});
[Link]("Tables in Database:");
while([Link]()) {
String tableName = [Link]("TABLE_NAME");
[Link](tableName);
}
}
}

/*
Slip no13 Q2 Write a Java program to 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.
*/
package [Link];
import [Link];
import [Link];
import [Link];
class ThreadLifeCycle extends Thread {
private String threadName;

ThreadLifeCycle(String threadName) {
[Link] = threadName;
}

public void run() {


Random rand = new Random();
int sTime = [Link](5000);
[Link](threadName + " is created.");
[Link]("Sleep time of " + threadName + " is:
" + sTime + "ms.");
try {
[Link](sTime);
} catch (InterruptedException ex) {
[Link]([Link]()).log
([Link], null, ex);
}

[Link](threadName + " is dead.");


}
}
public class slip13_2
{
public static void main(String[] args) {
ThreadLifeCycle t1 = new ThreadLifeCycle("First");
ThreadLifeCycle t2 = new ThreadLifeCycle("Second");
ThreadLifeCycle t3 = new ThreadLifeCycle("Third");

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

/*
slip no 14 Q1 Write a Java program using Multithreading for a
simple search engine. Accept a string
to be searched. Search the string in all text files in the
current folder. Use a separate
thread for each file. The result should display the filename and
line number where the
string is found.
*/
package [Link];
import [Link].*;
import [Link];
class SearchThread extends Thread {
private File file;
private String searchStr;
SearchThread(File file, String searchStr) {
[Link] = file;
[Link] = searchStr;
}
public void run() {
searchInFile(file, searchStr);
}
public void searchInFile(File file, String searchStr) {
boolean found = false;
try (BufferedReader br = new BufferedReader(new
FileReader(file))) {
String line;
int lineNo = 0;
while ((line = [Link]()) != null) {
lineNo++;
if ([Link](searchStr)) {
[Link]("Found '" + searchStr + "'
in " + [Link]() + " at line " + lineNo);
found = true;
}
}
} catch (IOException ex) {
[Link]("Error reading file: " +
[Link]());
}
if (!found) {
[Link](searchStr + " not found in " +
[Link]());
}
}
}
public class slip14_1
{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter string to be searched in
files:");
String searchStr = [Link]();
File currDir = new File(".");
File[] files = [Link]();
if (files != null) {
boolean foundInAnyFile = false;
for (File file : files) {
if ([Link]() &&
[Link]().endsWith(".txt")) {
SearchThread t = new SearchThread(file,
searchStr);
[Link]();
foundInAnyFile = true;
}
}
if (!foundInAnyFile) {
[Link]("No text files found in the
current directory.");
}
} else {
[Link]("Error: Unable to access current
directory.");
}
}
}

/* slipno 14 Q2 */
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
<style>
.res { color: red; font-size: 18px; }
</style>
</head>
<body>
<h1>Calculate sum of fist and last digit?</h1>
<form action="slip14_2.jsp" method="post">
Enter a number: <input type="text" name="num">
<input type="submit" value="sum?">
</form>
<%
String numStr = [Link]("num");
int n = 0;

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


n = [Link](numStr);

int fDigit = n;
while(fDigit >= 10) {
fDigit /= 10;
}
int lDigit = n % 10;

int sum = fDigit + lDigit;


%>
<h3 class="res">Sum of first and last digit is
<%= sum %></h3>
<%
}
%>
</body>
</html>

/*
slip no 15 q1 Write a java program to display name and priority
of a Thread.
*/
package [Link];
class MyThread extends Thread {

public void run() {


[Link]("Name of the thread: " +
[Link]().getName());
[Link]("Priority of the thread: " +
[Link]().getPriority());
}
}
public class slip15_1
{
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();

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

/*
slip no 16 Q1. Write a java program to create a TreeSet, add some
colors (String) and print out the
content of TreeSet in ascending order
*/
package [Link];
import [Link].*;
public class slip16_1

{
public static void main(String[] args) {
Set<String> colors = new TreeSet<>();

[Link]("Red");
[Link]("Blue");
[Link]("Green");
[Link]("Yellow");
[Link]("Black");

[Link](colors);
}
}

/*
slip no 16 Q2 Write a Java program to accept the details of
Teacher (TNo, TName, Subject). Insert at
least 5 Records into Teacher Table and display the details of
Teacher who is teaching
“JAVA” Subject. (Use PreparedStatement Interface)
*/
package [Link];
import [Link].*;
import [Link];
class Teacher {
Teacher() throws SQLException, SQLException {
Connection conn =
[Link]("jdbc:postgresql://localhost:5432/pos
tgres", "postgres", "postgres");

for(int i=0; i<5; i++)


insert(conn);

select(conn);
}
private void insert(Connection conn) throws SQLException {
String sql = "insert into teacher values(?, ?, ?)";

PreparedStatement ps = [Link](sql);

Scanner sc = new Scanner([Link]);

[Link]("Enter tno:");
[Link](1, [Link]());
[Link]();

[Link]("Enter tname:");
[Link](2, [Link]());

[Link]("Enter subject:");
[Link](3, [Link]());

[Link]();
}
private void select(Connection conn) throws SQLException {
String sql = "select * from teacher where subject =
'java'";
Statement stmt = [Link]();

ResultSet rs = [Link](sql);
while([Link]()) {
[Link]("teacher tno: " +
[Link]("tno"));
[Link]("teacher tname: " +
[Link]("tname"));
[Link]("teacher subject: " +
[Link]("subject"));
}
}
}
public class slip16_2
{
public static void main(String[] args) throws SQLException {
new Teacher();
}
}

/*
Slip no 17 q1Write a java program to accept ‘N’ integers from a
user. Store and display integers in
sorted order having proper collection class. The collection
should not accept duplicate
elements.
*/
package [Link];
import [Link];
import [Link];
import [Link];
public class slip17_1
{
public static void main(String[] args) {
Set<Integer> set = new TreeSet<>();
Scanner sc = new Scanner([Link]);

[Link]("How many integers:");


int n = [Link]();

[Link]("Enter " + n + " values:");


for(int i=0; i<n; i++)
[Link]([Link]());

[Link](set);
}
}
/*
Slip no 17 Q2 Write a java program using Multithreading to
display the number’s between 1 to 100
continuously in a JTextField by clicking on JButton. (Use
Runnable Interface &
Swing).
*/
package [Link];
import [Link];
import [Link];
import [Link].*;
import [Link].*;
public class slip17_2
{
private JFrame frame;
private JTextField tf;
private JButton print;
private Thread intThread;

slip17_2() {
frame = new JFrame("Integer printing App");
[Link](300, 200);
[Link](new GridLayout(2,1));

tf = new JTextField();
print = new JButton("Print");

[Link](tf);
[Link](print);

[Link]((ActionEvent e) -> {
[Link]("");
if(intThread == null || ![Link]()) {
intThread = new Thread(new Runnable() {
@Override
public void run() {
while(true) {
for(int i=1; i<=100; i++) {
[Link]([Link](i));
try {
[Link](500);
} catch (InterruptedException ex)
{
[Link]([Link].
getName()).log([Link], null, ex);
}
}
[Link]("");
}
}
});
[Link]();
}
});

[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}

public static void main(String[] args) {


new S17Q2();
}
}

/*
Slip n 18 q1 Write a java program using Multithreading to
display all the vowels from a given
String. Each vowel should be displayed after every 3 seconds.
*/
package [Link];
import [Link];
import [Link].*;
public class slip18_1
{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter any string:");


String str = [Link]();

Thread t = new Thread(() -> {


for(int i=0; i<[Link](); i++) {
String str2 = [Link]();
char ch = [Link](i);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch ==
'o' || ch == 'u') {
[Link](ch);
try {
[Link](3000);
} catch (InterruptedException ex) {
[Link](slip18_1.[Link]()
).log([Link], null, ex);
}
[Link]("3 seconds are
passed....");
}
}
});

[Link]();
}
}
/*
slip no 19 Q1 Write a java program to accept ‘N’ Integers from a
user store them into LinkedList
Collection and display only negative integers.
*/
package [Link];
import [Link].*;
public class slip19_1
{
public static void main(String[] args) {
List<Integer> l = new LinkedList<>();
Scanner sc = new Scanner([Link]);

[Link]("How many values:");


int n = [Link]();

[Link]("Enter " + n + " values:");


for(int i=0; i<n; i++)
[Link]([Link]());

[Link]("Negative integers are:");


Iterator itr = [Link]();
while([Link]()) {
int num = (int)[Link]();
if(num < 0)
[Link](num);
}
}
}

/* Slip no 20*/
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="slip20_1.jsp" method="post">
Enter a number :<input type="text" name="num"><br>
<input type="submit" value="show in words">
</form>

<%
String numStr = [Link]("num");
if(numStr != null && ![Link]()) {
int t = [Link](numStr);
int rev = 0, rem;

// reverse the number


while(t > 0) {
rem = t % 10;
rev = (rev * 10) + rem;
t = t / 10;
}

t = rev;
rev = 0;
while(t > 0) {
rem = t % 10;
rev = (rev * 10) + rem;
t = t / 10;

switch(rem) {
case 0: [Link]("zero");
break;
case 1: [Link]("one");
break;
case 2: [Link]("two");
break;
case 3: [Link]("three");
break;
case 4: [Link]("four");
break;
case 5: [Link]("five");
break;
case 6: [Link]("six");
break;
case 7: [Link]("seven");
break;
case 8: [Link]("eight");
break;
case 9: [Link]("nine");
break;
}
}
}
%>
</body>
</html>

/*
slip no 20 q2Write a java program using Multithreading to
demonstrate drawing temple (Use
Swing)
*/
package [Link];
import [Link].*;
import [Link].*;
class TempleDrawing extends JFrame
{
public TempleDrawing()
{
setTitle("Simple Temple Drawing");
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
TemplePanel templePanel = new TemplePanel();
add(templePanel);
setVisible(true);
}
}
class TemplePanel extends JPanel
{
@Override
protected void paintComponent(Graphics g)
{
[Link](g);
drawTemple(g);
}
private void drawTemple(Graphics g)
{
[Link]([Link]);
[Link](100, 100, 100, 100); // Main structure

[Link]([Link]);
[Link](130, 150, 40, 50); // Main Door

[Link]([Link]);
int[] xPoints = {100, 150, 200}; // Triangle for roof
int[] yPoints = {100, 50, 100};
[Link](xPoints, yPoints, 3);
[Link]([Link]);
[Link](150, 40, 20, 10); // Flag
}
}
public class slip20_2
{
public static void main(String[] args)
{
[Link](() ->
{
new TempleDrawing();
});
}
}
/*
slip no 21 Q1. Write a java program to accept ‘N’ Subject Names
from a user store them into
LinkedList Collection and Display them by using Iterator
interface.
*/
package [Link];
import [Link].*;
public class slip21_1
{
public static void main(String[] args) {
List<String> l = new LinkedList<>();
Scanner sc = new Scanner([Link]);

[Link]("How many subjects:");


int n = [Link]();
[Link]();

[Link]("Enter " + n + " subjects:");


for(int i=0; i<n; i++)
[Link]([Link]());

[Link]("Subjects are:");
Iterator itr = [Link]();
while([Link]()) {
[Link]([Link]());
}
}
}

/*
slip no 22 Q2 Write a java program using Multithreading to solve
producer consumer problem in
which a producer produces a value and consumer consume the value
before producer
generate the next value. (Hint: use thread synchronization)
*/
package [Link];
import [Link];
class SharedResource {
private LinkedList<String> buffer = new LinkedList<>();
private int capacity = 1;

public synchronized void produce(String value) {


while([Link]() == capacity) {
try {
wait();
} catch(InterruptedException e) {
[Link]();
}
}

[Link](value);
[Link]("Produced: " + value);
notifyAll();
}

public synchronized String consume() {


while([Link]() == 0) {
try {
wait();
} catch(InterruptedException e) {
[Link]();
}
}

String value = [Link]();


[Link]("Consume: " + value);
notifyAll();

return value;
}
}
class Producer extends Thread {
private SharedResource sharedResource;

public Producer(SharedResource sharedResource) {


[Link] = sharedResource;
}

@Override
public void run() {
for(int i=0; i<5; i++) {
String value = "Value " + i;
[Link](value);
try {
sleep(1000);
} catch (InterruptedException e) {
[Link]();
}
}
}
}
class Consumer extends Thread {
private SharedResource sharedResource;

public Consumer(SharedResource sharedResource) {


[Link] = sharedResource;
}
@Override
public void run() {
for(int i=0; i<5; i++) {
String value = "Value " + i;
[Link]();
try {
sleep(1000);
} catch (InterruptedException e) {
[Link]();
}
}
}
}
public class slip21_2
{
public static void main(String[] args) {
SharedResource sharedResource = new SharedResource();

Producer producer = new Producer(sharedResource);


Consumer consumer = new Consumer(sharedResource);

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

/*
slip no 22 Q1 Write a Menu Driven program in Java for the
following: Assume Employee table with
attributes (ENo, EName, Salary) is already created. 1. Insert 2.
Update 3. Display 4.
Exit
*/
package [Link];
import [Link].*;
import [Link];
public class slip22_1
{
private static void insert(Connection conn) throws
SQLException {
String sql = "insert into emp2 values (?, ?, ?)";
PreparedStatement ps = [Link](sql);

Scanner sc = new Scanner([Link]);


[Link]("Enter eno:");
[Link](1, [Link]());
[Link]();
[Link]("Enter ename:");
[Link](2, [Link]());
[Link]("Enter salary:");
[Link](3, [Link]());

[Link]();
}
private static void update(Connection conn) throws
SQLException {
Scanner sc = new Scanner([Link]);
[Link]("Enter eno:");
int eno = [Link]();
[Link]();

[Link]("Enter new ename:");


String ename = [Link]();

[Link]("Enter new salary:");


float salary = [Link]();

String sql = "update emp2 set ename = '" + ename + "',


salary = " + salary + " where eno = " + eno;
Statement stmt = [Link]();
[Link](sql);
}
private static void display(Connection conn) throws
SQLException {
String sql = "select * from emp2";
Statement stmt = [Link]();
ResultSet rs = [Link](sql);
[Link]("Emp table data:");
while ([Link]()) {
[Link]("eno: " + [Link]("eno"));
[Link]("ename: " +
[Link]("ename"));
[Link]("salary: " +
[Link]("salary"));
}
}
public static void main(String[] args) throws SQLException {
Scanner sc = new Scanner([Link]);
Connection conn =
[Link]("jdbc:postgresql://localhost:5432/pos
tgres", "postgres", "postgres");
int ch;
do {
[Link]("Menu");
[Link]("1. Insert");
[Link]("2. Update");
[Link]("3. Display");
[Link]("4. Exit");
[Link]("-------------------------");
[Link]("Enter your choice:");
ch = [Link]();
switch (ch) {
case 1:
insert(conn);
break;
case 2:
update(conn);
break;
case 3:
display(conn);
break;
}
} while (ch != 4);
}
}

*/ slip no 22 Q2 */
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="[Link]" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="slip22_2.jsp" method="post">
Enter user name :<input type="text" name="user"><br>
<input type="submit" value="greet">
</form>

<%
String user = [Link]("user");

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


LocalTime currTime = [Link]();
int hour = [Link]();

if(hour >= 0 && hour < 12)


[Link]("Good Morning " + user);
else if(hour >= 12 && hour <= 18)
[Link]("Good Afternoon " + user);
else
[Link]("Good Morning " + user);
}
%>
</body>
</html>

/*
slip no 23 Q1 Write a java program using Multithreading to accept
a String from a user and display
each vowel from a String after every 3 seconds
*/
package [Link];
import [Link];
import [Link].*;
public class slip23_1
{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter any string:");


String str = [Link]();

Thread t = new Thread(() -> {


for(int i=0; i<[Link](); i++) {
String str2 = [Link]();
char ch = [Link](i);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch ==
'o' || ch == 'u') {
[Link](ch);
try {
[Link](3000);
} catch (InterruptedException ex) {
[Link](slip23_1.[Link]()
).log([Link], null, ex);
}
[Link]("3 seconds are
passed....");
}
}
});

[Link]();
}
}

/*
Slip no 24 Q1 Write a java program using Multithreading to
scroll the text from left to right
continuously (Use Swing).
*/
package [Link];
import [Link].*;
class TextScrolling extends JFrame implements Runnable {
private JLabel label;
private String text;
private Thread thread;
public TextScrolling(String text) {
[Link] = text;
label = new JLabel(text);
add(label);
setSize(300, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void startScrolling() {
thread = new Thread(this);
[Link]();
}
@Override
public void run() {
try {
while (true) {
String labelText = [Link]();
labelText = [Link](1) +
[Link](0);
[Link](labelText);
[Link](200); // Adjust scrolling speed
}
} catch (InterruptedException e) {
[Link]();
}
}
}
public class slip24_1
{
public static void main(String[] args) {
[Link](() -> {
TextScrolling ts = new TextScrolling("Hello, this
text is scrolling continuously!");
[Link]();
});
}
}

/*
SLip no 25 Q2 Write a Java Program for the following: Assume
database is already created.
*/
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class slip25_2
{
JFrame frame;
JButton b1, b2, b3;
JTextField tf;

slip25_2() throws SQLException {


frame = new JFrame("DB App");
[Link](new BorderLayout());
[Link](600, 100);

JPanel p1 = new JPanel();


JPanel p2 = new JPanel();

tf = new JTextField();
[Link](new GridLayout(1, 2));
[Link](new JLabel("Type your DDL query:"));
[Link](tf);

b1 = new JButton("Create Table");


b2 = new JButton("Alter Table");
b3 = new JButton("Drop Table");
[Link](new GridLayout(1, 3));
[Link](b1);
[Link](b2);
[Link](b3);

Connection conn =
[Link]("jdbc:postgresql://localhost:5432/pos
tgres", "postgres", "postgres");

[Link]((ActionEvent e) -> {
try {
create(conn);
} catch (SQLException ex) {
[Link]([Link]()).log(Level
.SEVERE, null, ex);
}
});
[Link]((ActionEvent e) -> {
try {
alter(conn);
} catch (SQLException ex) {
[Link]([Link]()).log(Level
.SEVERE, null, ex);
}
});
[Link]((ActionEvent e) -> {
try {
drop(conn);
} catch (SQLException ex) {
[Link]([Link]()).log(Level
.SEVERE, null, ex);
}
});

[Link](p1, [Link]);
[Link](p2, [Link]);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}

private void create(Connection conn) throws SQLException {


String sql = [Link]();
Statement stmt = [Link]();
[Link](sql);
}
private void alter(Connection conn) throws SQLException {
String sql = [Link]();
Statement stmt = [Link]();
[Link](sql);
}
private void drop(Connection conn) throws SQLException {
String sql = [Link]();
Statement stmt = [Link]();
[Link](sql);
}

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


new S25Q2();
}
}

/*
Slip no 26 Q1 Write a Java program to delete the details of given
employee (ENo EName Salary).
Accept employee ID through command line. (Use PreparedStatement
Interface)
*/
package [Link];
import [Link].*;
public class slip26_1
{
public static void main(String[] args) throws SQLException {
Connection conn =
[Link]("jdbc:postgresql://localhost:5432/pos
tgres", "postgres", "postgres");

String sql = "delete from emp where id = ?";


PreparedStatement ps = [Link](sql);
[Link](1, [Link](args[0]));
[Link]();
}
}

/*
slip no 27 Q1 Write a Java Program to display the details of
College (CID, CName, address, Year)
database table on JTable.
*/
package [Link];
import [Link];
import [Link].*;
import [Link].*;
class CollegeTable {
private JFrame frame;
private JTable table;

CollegeTable() throws SQLException {


frame = new JFrame("Project Table");
[Link](new BorderLayout());
[Link](600, 150);
Connection conn =
[Link]("jdbc:postgresql://localhost:5432/pos
tgres", "postgres", "postgres");

String[] colNames = {"cid", "cname", "address", "year"};


String[][] data = retriveData(conn);

table = new JTable(data, colNames);


JScrollPane scrPane = new JScrollPane(table);

[Link]().add(scrPane,
[Link]);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
private String[][] retriveData(Connection conn) throws
SQLException {
String sql = "select * from college";
Statement stmt =
[Link](ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = [Link](sql);
ResultSetMetaData rsmd = [Link]();
int noCol = [Link]();
[Link]();
int noRow = [Link]();
[Link]();
String[][] data = new String[noRow][noCol];
int rowCnt = 0;
while ([Link]()) {
for (int i = 1; i <= noCol; i++)
data[rowCnt][i - 1] = [Link](i);
rowCnt++;
}
return data;
}
}
public class slip27_1
{
public static void main(String[] args) throws SQLException {
new CollegeTable();
}
}

/*
Slip no 28 Q2 Write a java program to display name of currently
executing Thread in multithreading
*/
package [Link];
public class slip28_2
{
public static void main(String[] args) {
Thread t = new Thread(() -> {
[Link]("Name of the thread: " +
[Link]().getName());
});
[Link]();
}
}

/*
Slip no 29 Q1. Write a Java program to display information about
all columns in the DONAR table
using ResultSetMetaData.
*/
package [Link];
import [Link].*;
public class slip29_1
{
public static void main(String[] args) throws SQLException {
Connection conn =
[Link]("jdbc:postgresql://localhost:5432/pos
tgres", "postgres", "postgres");

String sql = "select * from donar";

Statement stmt = [Link]();


[Link](sql);

ResultSet rs = [Link]();
ResultSetMetaData rsmd = [Link]();

int colCnt = [Link]();


[Link]("Donar table Meta Data:");
for(int i=1; i<colCnt; i++) {
String colName = [Link](i);
String colType = [Link](i);
int colSize = [Link](i);

[Link](colName + " " + colType + "(" +


colSize + ")");
}
}
}

/*
slip no 29 Q2. Write a Java program to create LinkedList of
integer objects and perform the following:
i. Add element at first position
ii. Delete last element
iii. Display the size of link list
*/
package [Link];
import [Link].*;
public class slip29_2
{
public static void main(String[] args) {
List<Integer> l = new LinkedList<>();
Scanner sc = new Scanner([Link]);

int ch;

do {
[Link]("Menu");
[Link]("1. Insert at head");
[Link]("2. Delete tail.");
[Link]("3. Display size");
[Link]("4. Exit");

[Link]("------------------------------");
[Link]("Enter your choice:");
ch = [Link]();
[Link]();

switch(ch) {
case 1: [Link]("Enter a number:");
[Link]([Link]());
break;
case 2: [Link]();
break;
case 3:
[Link]("Size : " + [Link]() +
"\n" + l);
break;
default: [Link]("Invalid choice.");
}
[Link]("-------------------------------
");
} while(ch != 4);
}
}

/*
Slip no 30 Q1. Write a java program using Multithreading to
demonstrate drawing Indian flag (Use
Swing
*/
package [Link];
import [Link].*;
import [Link].*;
class IndianFlag extends JFrame {
public IndianFlag() {
setTitle("Simple Temple Drawing");
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
FlagPanel flagPanel = new FlagPanel();
add(flagPanel);
setVisible(true);
}
}
class FlagPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
[Link](g);
drawFlag(g);
}
private void drawFlag(Graphics g) {
[Link]([Link]);
[Link](50, 50, 200, 50);

[Link]([Link]);
[Link](50, 100, 200, 50);

[Link]([Link]);
[Link](50, 150, 200, 50);

}
}
public class slip30_1
{
public static void main(String[] args) {
[Link](() -> {
new IndianFlag();
});
}
}

Common questions

Powered by AI

The program manages SQL operations using Java Database Connectivity (JDBC) by establishing a connection to the database with 'DriverManager.getConnection', creating a 'Statement' for executing SQL commands. For updating data, it uses 'executeUpdate' within the 'update' method, which executes an SQL update query based on user input for employee information. The 'display' method retrieves and prints table data using 'executeQuery', iterating over the ResultSet to fetch each row. This approach effectively encapsulates SQL operations by separating concerns between data modification and querying, ensuring both operations use efficient execution paths like prepared statements to potentially enhance performance and security against SQL injection .

The TreeSet collection in Java is used for storing unique elements in a sorted manner, which fits the program's requirement to store 'n' integers input by the user without accepting duplicates and display them in sorted order. TreeSet automatically sorts the elements as they are added, ensuring that no duplicates are allowed and that the elements are kept in natural order. Hence, it simplifies the implementation by maintaining this order without additional logic, and enables efficient searching with methods like 'contains', which checks for the existence of a particular element .

The simulation of a traffic signal using multithreading involves creating a separate thread that cycles through different traffic light states (Red, Green, Yellow) to mimic real-world signal timing. The 'TrafficLight' class implements 'Runnable', allowing it to be executed on a separate thread. It continuously loops over an array of light colors, printing the current signal and pausing for the appropriate duration using 'Thread.sleep()'. Each light color (Red, Green, Yellow) has a specific duration during which it remains active before switching to the next, effectively managing the sequence and timing of traffic lights using a single-threaded process. Multithreading allows this behavior to run separately and concurrently from any other processes, hence not blocking or being blocked by other tasks .

Using the PreparedStatement interface for deleting employee records offers significant advantages in terms of security and performance compared to general Statement objects. PreparedStatements precompile SQL commands, which enhances execution speed for repeated queries. They safely parameterize inputs, mitigating SQL injection risks by treating parameters as non-code data. This is particularly significant in a multi-user application handling direct textual input, ensuring that user-given employee IDs do not affect query syntax inadvertently. By preventing raw SQL execution via external input, PreparedStatements maintain database integrity and elevate overall application security and efficiency .

The Java program uses 'ResultSetMetaData' to extract and display metadata about columns from the 'donar' table in a database. By executing a query to fetch all rows from the table and obtaining a ResultSet object, the program retrieves ResultSetMetaData to access column information such as the count, names, types, and display sizes. This technique benefits database introspection by providing detailed structural information about a table without directly modifying or querying the database schema, enabling developers to dynamically understand and present table structures programmatically in a clean and systematic way .

The Java application demonstrates selective method execution in a multithreaded environment by creating three threads. The first thread generates a random integer every second. Depending on the parity of the generated number (even or odd), the second or third thread executes. If the number is even, the second thread computes and prints its square; if odd, the third thread computes and prints its cube. By continuously checking the parity with a shared variable from the number generator thread, the application ensures that either the even or odd actions are performed correctly in their respective threads, illustrating efficient concurrency and synchronization for specific tasks .

The Enumeration interface provides a way to iterate over elements in a collection, such as a Hashtable, which is used here to store student details keyed by mobile numbers. Using Enumeration to retrieve and display data involves obtaining mobile numbers through the 'keys()' method of the Hashtable and iterating over these keys. It is appropriate for this task because it provides a simple way to traverse the keys and retrieve corresponding student names without needing to track additional state manually, making the operation straightforward and efficient for the intended small-scale dataset .

The multithreaded Java program effectively illustrates thread lifecycle management through the deliberate sequence of creation, execution, starting, sleeping, and termination phases. Each ThreadLifeCycle object is instantiated with a name (creation), indicating setup readiness. Calling 'start()' on each, the threads enter a runnable state, commencing execution of the 'run()' method. Within 'run()', a sleep period, determined randomly up to 4999 milliseconds, is displayed creating a simulated delay highlighting the thread's operational state transition from running to waiting. After sleep, the thread prints its demise, marking its transition to a terminated state, thereby showcasing the full thread lifecycle seamlessly and clearly .

The Swing-based program effectively displays project data from a database by using a JTable within a JFrame, facilitating an organized and visible presentation. The JFrame creates a window while the JTable populates the table data by executing a SQL query through JDBC. The ResultSetMetaData is used to determine the number of columns, enabling dynamic creation of table headers. By wrapping the JTable in a JScrollPane, the program ensures the table is scrollable and readable even with limited screen space. This arrangement efficiently utilizes Swing's versatility for GUI creation combined with JDBC's power for database operations, providing users a seamless and coherent data viewing experience .

The program employs Swing components to build a GUI for interacting with a database by using JFrames, JButtons, JTextFields, and JTables. The JFrame acts as the main window, while JTextFields are used to input or display data entries. Buttons (Create Table, Alter Table, Drop Table) handle user actions, triggering database queries when clicked. JTable displays data from a database in a tabular form, providing a visual representation of database contents. Swing components facilitate user interaction by offering direct, intuitive ways to manipulate data visually, allowing for real-time feedback and changes in the interface based on user commands, leveraging an event-driven programming model .

You might also like