Java Cia 3

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

Name : Saanika Chaudhari

Roll.No : 40
Class : TY BSC(CS)

JAVA CIA 3(slips)


Slip 1
Q1. Write a java program to display all the alphabets between ‘A’ to
‘Z’ after every 2 seconds. Using threads

public class Main {


public static void main(String[] args) {
AlphabetThread alphabetThread = new AlphabetThread();
alphabetThread.start();
}
}

class AlphabetThread extends Thread {


@Override
public void run() {
char start = 'A';
char end = 'Z';

for (char c = start; c <= end; c++) {


System.out.print(c + " ");
try {
Thread.sleep(2000); // Sleep for 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

Output: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Q2. Write a program to accept the details of Employee (ENo, EName,
Designation, Salary) from the user and store it into a database. (using
Swing)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class Main extends JFrame {


private JTextField tfEno, tfEName, tfDesignation, tfSalary;
private JButton btnSave;

public Main() {
setTitle("Employee Details Form");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new GridLayout(5, 2));

JLabel lblEno = new JLabel("Employee Number:");


tfEno = new JTextField();
add(lblEno);
add(tfEno);

JLabel lblEName = new JLabel("Employee Name:");


tfEName = new JTextField();
add(lblEName);
add(tfEName);

JLabel lblDesignation = new JLabel("Designation:");


tfDesignation = new JTextField();
add(lblDesignation);
add(tfDesignation);

JLabel lblSalary = new JLabel("Salary:");


tfSalary = new JTextField();
add(lblSalary);
add(tfSalary);

btnSave = new JButton("Save");


btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveEmployeeDetails();
}
});
add(btnSave);

setVisible(true);
}

private void saveEmployeeDetails() {


String eno = tfEno.getText();
String eName = tfEName.getText();
String designation = tfDesignation.getText();
String salary = tfSalary.getText();

try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/java",
"root", "student");
PreparedStatement ps = con.prepareStatement("insert into
employee(Eno, Ename, Designation, Salary) values(?,?,?,?)");
ps.setString(1, eno);
ps.setString(2, eName);
ps.setString(3, designation);
ps.setString(4, salary);
int i = ps.executeUpdate();
if (i > 0) {
JOptionPane.showMessageDialog(this, "Employee details
saved successfully!");
tfEno.setText("");
tfEName.setText("");
tfDesignation.setText("");
tfSalary.setText("");
}
con.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error: " +
ex.getMessage());
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Main();
}
});
}
}
create database java;
use java;
create table Employee(Eno int,Ename text,Designation text, Salary
int);
select * from Employee;

Output:
1 aaa abc 10000
2 bbb xyz 20000

Slip 3
Q1. Write a JSP program to display the details of a patient (PNo,
PName, Address, age, disease) in tabular form on a web browser
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Patient Details</title>
</head>
<body>
<h2>Patient Details</h2>
<table border="1">
<tr>
<th>Patient Number</th>
<th>Patient Name</th>
<th>Address</th>
<th>Age</th>
<th>Disease</th>
</tr>
<%
// Sample patient details (replace with your data)
String[][] patients = {
{"1", "John Doe", "123 Main St", "30", "Fever"},
{"2", "Jane Smith", "456 Elm St", "25", "Headache"},
{"3", "Alice Johnson", "789 Oak St", "40", "Flu"}
};

// Loop through the patients array and display details in the


table
for (String[] patient : patients) {
out.println("<tr>");
for (String detail : patient) {
out.println("<td>" + detail + "</td>");
}
out.println("</tr>");
}
%>
</table>
</body>
</html>
Output: Patient Details
Patient Number Patient Name Address Age Disease
1 John Doe 123 Main St 30 Fever
2 Jane Smith 456 Elm St 25 Headache
3 Alice Johnson 789 Oak St 40 Flu

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

import java.util.LinkedList;
import java.util.Collections;

public class Main {


public static void main(String[] args) {
LinkedList<String> linkedList = new LinkedList<>();

// i. Add element at the end of the list


linkedList.add("Apple");
linkedList.add("Banana");
linkedList.add("Orange");
linkedList.add("Grapes");
System.out.println("LinkedList after adding elements: " +
linkedList);

// ii. Delete first element of the list


if (!linkedList.isEmpty()) {
linkedList.removeFirst();
System.out.println("LinkedList after deleting first
element: " + linkedList);
} else {
System.out.println("LinkedList is empty.");
}

// iii. Display the contents of list in reverse order


Collections.reverse(linkedList);
System.out.println("LinkedList in reverse order: " +
linkedList);
}
}

Output:
LinkedList after adding elements: [Apple, Banana, Orange, Grapes]
LinkedList after deleting first element: [Banana, Orange, Grapes]
LinkedList in reverse order: [Grapes, Orange, Banana]

Slip 4
Q1. Write a java program using Runnable interface to blink Text on
the frame
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Main extends JFrame implements Runnable {


private JLabel label;
private boolean isVisible = true;

public Main() {
setTitle("Blinking Text");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

label = new JLabel("Blinking Text");


label.setFont(new Font("Arial", Font.BOLD, 24));
add(label, BorderLayout.CENTER);

Thread thread = new Thread(this);


thread.start();

setVisible(true);
}

public void run() {


try {
while (true) {
Thread.sleep(500); // Wait for 500 milliseconds
isVisible = !isVisible;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
label.setVisible(isVisible);
}
});
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Main();
}
});
}
}

Output:

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

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {


private static Map<String, String> citySTDMap = new
HashMap<>();

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
int choice;

do {
System.out.println("\n1. Add a new city and its code");
System.out.println("2. Remove a city");
System.out.println("3. Search for a city name and display the
code");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();

switch (choice) {
case 1:
addCity(scanner);
break;
case 2:
removeCity(scanner);
break;
case 3:
searchCity(scanner);
break;
case 4:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 4);

scanner.close();
}
private static void addCity(Scanner scanner) {
System.out.print("Enter city name: ");
String city = scanner.next();
System.out.print("Enter STD code: ");
String stdCode = scanner.next();

if (!citySTDMap.containsKey(city)) {
citySTDMap.put(city, stdCode);
System.out.println("City added successfully.");
} else {
System.out.println("City already exists.");
}
}

private static void removeCity(Scanner scanner) {


System.out.print("Enter city name to remove: ");
String city = scanner.next();

if (citySTDMap.containsKey(city)) {
citySTDMap.remove(city);
System.out.println("City removed successfully.");
} else {
System.out.println("City not found.");
}
}

private static void searchCity(Scanner scanner) {


System.out.print("Enter city name to search: ");
String city = scanner.next();

if (citySTDMap.containsKey(city)) {
System.out.println("STD code for " + city + ": " +
citySTDMap.get(city));
} else {
System.out.println("City not found.");
}
}
}

Output:
1. Add a new city and its code
2. Remove a city
3. Search for a city name and display the code
4. Exit
Enter your choice: 1
Enter city name: pune
Enter STD code: 001
City added successfully.

1. Add a new city and its code


2. Remove a city
3. Search for a city name and display the code
4. Exit
Enter your choice: 1
Enter city name: mumbai
Enter STD code: 002
City added successfully.

1. Add a new city and its code


2. Remove a city
3. Search for a city name and display the code
4. Exit
Enter your choice: 2
Enter city name to remove: pune
City removed successfully.

1. Add a new city and its code


2. Remove a city
3. Search for a city name and display the code
4. Exit
Enter your choice: 3
Enter city name to search: mumbai
STD code for mumbai: 002
Slip 7
Q1. 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 print it. If the number is odd, third
thread computes the cube of that number and print it.
import java.util.Random;

class NumberGenerator implements Runnable{


private Random random=new Random();
@Override
public void run() {
while(true){
int number=random.nextInt(100)+1;
System.out.println("Generated number: "+number);
if(number%2==0) {
new Thread(new
SquareCalculator(number)).start();
}
else {
new Thread(new CubePrinter(number)).start();
}
try {
Thread.sleep(1000);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}

class SquareCalculator implements Runnable{


private int number;
public SquareCalculator(int number) {
this.number=number;
}
@Override
public void run() {
int square=number*number;
System.out.println("Square: "+square);
}
}

class CubePrinter implements Runnable{


private int number;
public CubePrinter(int number) {
this.number=number;
}
@Override
public void run() {
int cube=number*number*number;
System.out.println("Cube: "+cube);
}
}

public class Main {


public static void main(String[] args) {
Thread numberGeneratorThread=new Thread(new
NumberGenerator());
numberGeneratorThread.start();
}
}

Output: Generated number: 55


Cube: 166375
Generated number: 55
Cube: 166375
Generated number: 15
Cube: 3375
Generated number: 17
Cube: 4913
Generated number: 8
Square: 64
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 table.
iii. Display all the records from a table.

import java.sql.*;

public class Main {


static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/java";
static final String USER = "root";
static final String PASS = "student";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER,
PASS);

System.out.println("Creating table in given database...");


stmt = conn.createStatement();
String sql = "CREATE TABLE Product " +
"(Pid INT NOT NULL AUTO_INCREMENT, " +
" Pname VARCHAR(255), " +
" Price DOUBLE, " +
" PRIMARY KEY ( Pid ))";
stmt.executeUpdate(sql);
System.out.println("Table created successfully...");

System.out.println("Inserting records into the table...");


sql = "INSERT INTO Product (Pname, Price) VALUES
('Product1', 10.0), ('Product2', 20.0), ('Product3', 30.0), ('Product4',
40.0), ('Product5', 50.0)";
stmt.executeUpdate(sql);
System.out.println("Records inserted successfully...");

System.out.println("Displaying all records from the table...");


sql = "SELECT * FROM Product";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("Pid");
String name = rs.getString("Pname");
double price = rs.getDouble("Price");
System.out.println("ID: " + id + ", Name: " + name + ",
Price: " + price);
}
rs.close();

} catch (SQLException se) {


se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}

Output: Connecting to database...


Creating table in given database...
Table created successfully...
Inserting records into the table...
Records inserted successfully...
Displaying all records from the table...
ID: 1, Name: Product1, Price: 10.0
ID: 2, Name: Product2, Price: 20.0
ID: 3, Name: Product3, Price: 30.0
ID: 4, Name: Product4, Price: 40.0
ID: 5, Name: Product5, Price: 50.0
Goodbye!

1 Product1 10
2 Product2 20
3 Product3 30
4 Product4 40
5 Product5 50

Slip 8
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

class mythread extends Thread{


String str;
int n,i;
mythread(String str, int n){
this.str=str;
this.n=n;
}
public void run() {
try {
for(i=0;i<n;i++) {
System.out.println(i+1+" : "+str);
}
System.out.println("\n");
}
catch(Exception e) {

}
}
}

public class Main {


public static void main(String[] args) {
mythread t1 = new mythread ("COVID19", 10);
mythread t2 = new mythread ("LOCKDOWN2020", 20);
mythread t3 = new mythread ("VACCINATED2021", 30);

t1.start();
t2.start();
t3.start();
}
}

Output:
1 : COVID19
2 : COVID19
1 : LOCKDOWN2020
2 : LOCKDOWN2020
3 : LOCKDOWN2020
4 : LOCKDOWN2020
5 : LOCKDOWN2020
6 : LOCKDOWN2020
7 : LOCKDOWN2020
8 : LOCKDOWN2020
9 : LOCKDOWN2020
10 : LOCKDOWN2020
11 : LOCKDOWN2020
12 : LOCKDOWN2020
13 : LOCKDOWN2020
1 : VACCINATED2021
3 : COVID19
14 : LOCKDOWN2020
2 : VACCINATED2021
4 : COVID19
15 : LOCKDOWN2020
3 : VACCINATED2021
5 : COVID19
6 : COVID19
7 : COVID19
8 : COVID19
9 : COVID19
10 : COVID19
16 : LOCKDOWN2020
17 : LOCKDOWN2020
18 : LOCKDOWN2020
19 : LOCKDOWN2020
20 : LOCKDOWN2020
4 : VACCINATED2021
5 : VACCINATED2021
6 : VACCINATED2021
7 : VACCINATED2021
8 : VACCINATED2021
9 : VACCINATED2021
10 : VACCINATED2021
11 : VACCINATED2021
12 : VACCINATED2021
13 : VACCINATED2021
14 : VACCINATED2021
15 : VACCINATED2021
16 : VACCINATED2021
17 : VACCINATED2021
18 : VACCINATED2021
19 : VACCINATED2021
20 : VACCINATED2021
21 : VACCINATED2021
22 : VACCINATED2021
23 : VACCINATED2021
24 : VACCINATED2021
25 : VACCINATED2021
26 : VACCINATED2021
27 : VACCINATED2021
28 : VACCINATED2021
29 : VACCINATED2021
30 : VACCINATED2021

Q2. Write a JSP program to check whether a given number is prime or


not. Display the result in red color.
<%@ page language="java" contentType="text/html; charset=UTF-
8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Prime Number Checker</title>
</head>
<body>
<h2>Prime Number Checker</h2>
<form method="post" action="">
Enter a number: <input type="number" name="number"
required><br><br>
<input type="submit" value="Check Prime">
</form>
<%
if (request.getMethod().equals("POST")) {
int number =
Integer.parseInt(request.getParameter("number"));
boolean isPrime = true;

if (number <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
}

if (isPrime) {
out.println("<p style='color: red; font-weight:
bold;'>Number " + number + " is PRIME.</p>");
} else {
out.println("<p style='color: red; font-weight:
bold;'>Number " + number + " is NOT PRIME.</p>");
}
}
%>
</body>
</html>

Output: Prime Number Checker


Enter a number:

Number 8656 is NOT PRIME.

Slip 10
Q1. Write a java program to display the current date using spring.
<!-- applicationContext.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dateBean" class="java.util.Date" factory-
method="new" />

<bean id="dateFormat" class="java.text.SimpleDateFormat">


<constructor-arg value="yyyy-MM-dd HH:mm:ss" />
</bean>

<bean id="currentDate" class="java.util.Date">


<property name="time" value="#{dateBean.time}" />
</bean>

<bean id="formattedCurrentDate" class="java.lang.String">


<constructor-arg ref="dateFormat" />
<constructor-arg ref="currentDate" />
</bean>

</beans>

import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationConte
xt;

public class Main {


public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("applicationContext.xml");
String formattedCurrentDate = (String)
context.getBean("formattedCurrentDate");
System.out.println("Current Date: " + formattedCurrentDate);
}
}

Output:
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).
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

public class Main extends JFrame {


private JTextField tfRNo, tfSName, tfPer;
private JButton btnDisplay;

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";


static final String DB_URL = "jdbc:mysql://localhost:3306/java";
static final String USER = "root";
static final String PASS = "student";

public Main() {
setTitle("Display First Record");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

setLayout(new GridLayout(4, 2));

JLabel lblRNo = new JLabel("Roll Number:");


tfRNo = new JTextField();
tfRNo.setEditable(false);
add(lblRNo);
add(tfRNo);

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


tfSName = new JTextField();
tfSName.setEditable(false);
add(lblSName);
add(tfSName);
JLabel lblPer = new JLabel("Percentage:");
tfPer = new JTextField();
tfPer.setEditable(false);
add(lblPer);
add(tfPer);

btnDisplay = new JButton("Display First Record");


btnDisplay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
displayFirstRecord();
}
});
add(btnDisplay);

setVisible(true);
}

private void displayFirstRecord() {


Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER,
PASS);
stmt = conn.createStatement();
String sql = "SELECT * FROM student LIMIT 1";
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
int rno = rs.getInt("Rno");
String sname = rs.getString("Sname");
double per = rs.getDouble("Per");
tfRNo.setText(String.valueOf(rno));
tfSName.setText(sname);
tfPer.setText(String.valueOf(per));
} else {
JOptionPane.showMessageDialog(this, "No records found
in the student table.");
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Main();
}
});
}
}

create table Student(Rno int,Sname text,Per int);


insert into Student values(1,"aaa",75)
insert into Student values(2,"bbb",85)
insert into Student values(3,"ccc",96)
select * from Student;
1 aaa 75
2 bbb 85
3 ccc 96

Slip 13
Q1. Write a java program to display information about the database
and list all the tables in the database. (Use DatabaseMetaData).
import java.sql.*;

public class Main {


static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/java";
static final String USER = "root";
static final String PASS = "student";

public static void main(String[] args) {


Connection conn = null;
DatabaseMetaData meta = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER,
PASS);
meta = conn.getMetaData();

System.out.println("Database information:");
System.out.println("Database name: " +
meta.getDatabaseProductName());
System.out.println("Database version: " +
meta.getDatabaseProductVersion());
System.out.println("Driver name: " + meta.getDriverName());
System.out.println("Driver version: " +
meta.getDriverVersion());
System.out.println();

System.out.println("List of tables in the database:");


ResultSet rs = meta.getTables(null, null, "%", new String[] {
"TABLE" });
while (rs.next()) {
System.out.println(rs.getString("TABLE_NAME"));
}
rs.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}

Output: Database information:


Database name: MySQL
Database version: 8.0.35
Driver name: MySQL Connector/J
Driver version: mysql-connector-j-8.3.0 (Revision:
805f872a57875f311cb82487efcfb070411a3fa0)

List of tables in the database:


employee
product
student
leo
actor
address
category
city
country
customer
film
film_actor
film_category
film_text
inventory
language
payment
rental
staff
store
sys_config
city
country
countrylanguage

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 will be a random integer in the
range 0 to 4999.
import java.util.Random;

public class Main {


public static void main(String[] args) {
MyThread thread = new MyThread("Thread-1");
thread.start();
}
}

class MyThread extends Thread {


public MyThread(String name) {
super(name);
}

public void run() {


System.out.println("Thread " + getName() + " created.");

Random random = new Random();


int sleepTime = random.nextInt(5000); // Random sleep time
between 0 and 4999 milliseconds
try {
System.out.println("Thread " + getName() + " will sleep for "
+ sleepTime + " milliseconds.");
Thread.sleep(sleepTime);
System.out.println("Thread " + getName() + " woke up after
sleeping.");
} catch (InterruptedException e) {
System.out.println("Thread " + getName() + " interrupted
while sleeping.");
}

System.out.println("Thread " + getName() + " is dead.");


}
}

Output:
Thread Thread-1 created.
Thread Thread-1 will sleep for 3298 milliseconds.
Thread Thread-1 woke up after sleeping.
Thread Thread-1 is dead.

Slip 14
Q1. Write a java program 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
import java.io.*;
import java.util.concurrent.*;

public class Main {


public static void main(String[] args) {
// Accept the string to be searched
String searchString = "is";

// Get all text files in the current folder


File currentFolder = new File("C:\\Users\\Ruhana\\eclipse-
workspace\\Demo_New\\src\\CIA");
File[] files = currentFolder.listFiles((dir, name) ->
name.endsWith("java.txt"));

// Create thread pool


ExecutorService executor =
Executors.newFixedThreadPool(files.length);

// Submit tasks for each file


for (File file : files) {
Runnable task = new SearchTask(file, searchString);
executor.submit(task);
}

// Shutdown executor
executor.shutdown();
}
}

class SearchTask implements Runnable {


private File file;
private String searchString;

public SearchTask(File file, String searchString) {


this.file = file;
this.searchString = searchString;
}

@Override
public void run() {
try (BufferedReader reader = new BufferedReader(new
FileReader(file))) {
String line;
int lineNumber = 1;
while ((line = reader.readLine()) != null) {
if (line.contains(searchString)) {
System.out.println("Found '" + searchString + "' in " +
file.getName() + " at line " + lineNumber);
}
lineNumber++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Output: Found 'is' in java.txt at line 1

Q2. Write a JSP program to calculate sum of first and last digit of a
given number. Display sum in Red color with font size 18.
<%@ page language="java" contentType="text/html; charset=UTF-
8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sum of First and Last Digit</title>
</head>
<body>
<h2>Sum of First and Last Digit</h2>
<form method="post" action="">
Enter a number: <input type="number" name="number"
required><br><br>
<input type="submit" value="Calculate Sum">
</form>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.text.*" %>
<%
if (request.getMethod().equals("POST")) {
int number =
Integer.parseInt(request.getParameter("number"));
int firstDigit = String.valueOf(number).charAt(0) - '0';
int lastDigit = number % 10;
int sum = firstDigit + lastDigit;
%>
<p style="color: red; font-size: 18px;">Sum of first and last digit of
<%= number %>: <%= sum %></p>
<%
}
%>
</body>
</html>

Output: Sum of First and Last Digit


Enter a number:

Sum of first and last digit of 32: 5

Slip 16
Q1. Write a java program to create a TreeSet, add some colors
(String) and print out the content of TreeSet in ascending order.
import java.util.TreeSet;

public class Main {


public static void main(String[] args) {
// Create a TreeSet to store colors
TreeSet<String> colors = new TreeSet<>();

// Add colors to the TreeSet


colors.add("Red");
colors.add("Blue");
colors.add("Green");
colors.add("Yellow");
colors.add("Orange");

// Print out the content of TreeSet in ascending order


System.out.println("Colors in ascending order:");
for (String color : colors) {
System.out.println(color);
}
}
}

Output: Colors in ascending order:


Blue
Green
Orange
Red
Yellow

Q2. Write a java program to accept the details of Teacher (Tno,


TName, Subject). Insert atleast 5 Records into Teacher Table and
display the details of Teacher who is teaching “JAVA” subject. (use
PreparedStatement Interface).
package CIA;

import java.sql.*;

public class Main {


static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/java";
static final String USER = "root";
static final String PASS = "student";

public static void main(String[] args) {


Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER,
PASS);

// Insert records into Teacher table


String insertSql = "INSERT INTO Teacher (Tno, Tname,
Subject) VALUES (?, ?, ?)";
pstmt = conn.prepareStatement(insertSql);
pstmt.setInt(1, 1);
pstmt.setString(2, "John");
pstmt.setString(3, "JAVA");
pstmt.executeUpdate();

pstmt.setInt(1, 2);
pstmt.setString(2, "Alice");
pstmt.setString(3, "C++");
pstmt.executeUpdate();

pstmt.setInt(1, 3);
pstmt.setString(2, "Bob");
pstmt.setString(3, "JAVA");
pstmt.executeUpdate();

pstmt.setInt(1, 4);
pstmt.setString(2, "Emily");
pstmt.setString(3, "Python");
pstmt.executeUpdate();

pstmt.setInt(1, 5);
pstmt.setString(2, "David");
pstmt.setString(3, "JAVA");
pstmt.executeUpdate();

// Display details of teachers teaching "JAVA" subject


String selectSql = "SELECT * FROM Teacher WHERE
Subject = ?";
pstmt = conn.prepareStatement(selectSql);
pstmt.setString(1, "JAVA");
ResultSet rs = pstmt.executeQuery();

System.out.println("Teachers teaching JAVA subject:");


while (rs.next()) {
int tno = rs.getInt("TNo");
String tname = rs.getString("TName");
String subject = rs.getString("Subject");
System.out.println("TNo: " + tno + ", TName: " + tname +
", Subject: " + subject);
}
rs.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null) pstmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}

Output: Teachers teaching JAVA subject:


TNo: 1, TName: John, Subject: JAVA
TNo: 3, TName: Bob, Subject: JAVA
TNo: 5, TName: David, Subject: JAVA

create table Teacher(Tno int,Tname text,Subject text);


select * from Teacher;
1 John JAVA
2 Alice C++
3 Bob JAVA
4 Emily Python
5 David JAVA

Slip 17
Q1. Write 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.
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

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


int N = scanner.nextInt();

Set<Integer> integers = new TreeSet<>(); // TreeSet to store


integers in sorted order

System.out.println("Enter " + N + " integers:");


for (int i = 0; i < N; i++) {
int num = scanner.nextInt();
integers.add(num); // Adding integers to the TreeSet
}

System.out.println("Integers in sorted order (without


duplicates):");
for (int num : integers) {
System.out.println(num);
}
scanner.close();
}
}

Output: Enter the number of integers (N): 3


Enter 3 integers:
545
87
3
Integers in sorted order (without duplicates):
3
87
545

Q2. Write a Multithreading program in java to display the number’s


between 1 to 100 continuously in a TextField by clicking on button
.(use Runnable Interface)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Main extends JFrame {


private JTextField textField;
private JButton startButton;
private JButton stopButton;
private Thread numberThread;

public Main() {
setTitle("Number Display");
setSize(300, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

textField = new JTextField(10);


textField.setEditable(false);
textField.setHorizontalAlignment(JTextField.CENTER);
startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
startNumberDisplay();
}
});

stopButton = new JButton("Stop");


stopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
stopNumberDisplay();
}
});

JPanel panel = new JPanel();


panel.add(startButton);
panel.add(stopButton);

add(textField, BorderLayout.CENTER);
add(panel, BorderLayout.SOUTH);

setVisible(true);
}

private void startNumberDisplay() {


if (numberThread == null || !numberThread.isAlive()) {
numberThread = new Thread(new NumberRunnable());
numberThread.start();
}
}

private void stopNumberDisplay() {


if (numberThread != null && numberThread.isAlive()) {
numberThread.interrupt();
}
}
class NumberRunnable implements Runnable {
public void run() {
try {
for (int i = 1; i <= 100; i++) {
textField.setText(Integer.toString(i));
Thread.sleep(1000); // Display each number for 1 second
}
} catch (InterruptedException e) {
// Thread interrupted, stop displaying numbers
}
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Main();
}
});
}
}

Output:

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

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

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


int N = scanner.nextInt();

LinkedList<String> subjects = new LinkedList<>();

System.out.println("Enter " + N + " subject names:");


for (int i = 0; i < N; i++) {
String subject = scanner.next();
subjects.add(subject); // Add subject name to the LinkedList
}

System.out.println("Subject names entered by the user:");


Iterator<String> iterator = subjects.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

scanner.close();
}
}

Output: Enter the number of subjects (N): 3


Enter 3 subject names:
java
DA
OS
Subject names entered by the user:
java
DA
OS

Q2. Write a java program to solve producer consumer problem in


which a producer produces a value and consumer consume the value
before producer generates the next value.(Hint; use thread
synchronization)
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
// Creating shared object
LinkedList<Integer> buffer = new LinkedList<>();
int capacity = 5;

// Creating Producer and Consumer threads


Producer producer = new Producer(buffer, capacity);
Consumer consumer = new Consumer(buffer);

// Starting producer and consumer threads


producer.start();
consumer.start();
}
}

class Producer extends Thread {


private LinkedList<Integer> buffer;
private int capacity;
private int value = 1;

public Producer(LinkedList<Integer> buffer, int capacity) {


this.buffer = buffer;
this.capacity = capacity;
}

public void run() {


while (true) {
try {
produce(value++);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

private void produce(int value) throws InterruptedException {


synchronized (buffer) {
while (buffer.size() == capacity) {
System.out.println("Buffer is full. Producer is waiting...");
buffer.wait();
}

System.out.println("Producer produced: " + value);


buffer.add(value);
Thread.sleep(1000); // Simulate some processing time

buffer.notifyAll();
}
}
}

class Consumer extends Thread {


private LinkedList<Integer> buffer;

public Consumer(LinkedList<Integer> buffer) {


this.buffer = buffer;
}

public void run() {


while (true) {
try {
consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

private void consume() throws InterruptedException {


synchronized (buffer) {
while (buffer.isEmpty()) {
System.out.println("Buffer is empty. Consumer is
waiting...");
buffer.wait();
}

int value = buffer.removeFirst();


System.out.println("Consumer consumed: " + value);
Thread.sleep(1000); // Simulate some processing time

buffer.notifyAll();
}
}
}

Output: Buffer is empty. Consumer is waiting...


Producer produced: 1
Producer produced: 2
Consumer consumed: 1
Consumer consumed: 2
Producer produced: 3
Producer produced: 4
Consumer consumed: 3
Consumer consumed: 4
Producer produced: 5

Slip 23
Q1. Write a java program to accept a string from a user and display
each vowel from a string after every 3 seconds
import java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");


String input = scanner.nextLine();

// Create a thread to display vowels


Thread vowelThread = new Thread(new VowelPrinter(input));
vowelThread.start();

scanner.close();
}
}

class VowelPrinter implements Runnable {


private String input;

public VowelPrinter(String input) {


this.input = input;
}

public void run() {


for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (isVowel(ch)) {
System.out.println(ch);

try {
Thread.sleep(3000); // Display each vowel after every 3
seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

private boolean isVowel(char ch) {


ch = Character.toLowerCase(ch);
return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';
}
}

Output: Enter a string: java programming language


a
a
o
a
i
a
u
a
e

Q2. Write a java program to accept ‘N’ student names through


command line, store them into the appropriate collection and display
them by using iterator and ListIterator interface.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;

public class Main {


public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Usage: java StudentNames <student1>
<student2> ... <studentN>");
return;
}

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

// Adding student names to the ArrayList


for (String arg : args) {
studentList.add(arg);
}

System.out.println("Student names entered by the user:");


displayUsingIterator(studentList);
System.out.println();
displayUsingListIterator(studentList);
}

private static void displayUsingIterator(ArrayList<String>


studentList) {
Iterator<String> iterator = studentList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}

private static void displayUsingListIterator(ArrayList<String>


studentList) {
ListIterator<String> listIterator = studentList.listIterator();
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}
}
}

Output: Student names entered by the user:


aaa
ccc
abc
zzz
xyz
pqr
using listiterator interface
aaa
ccc
abc
zzz
xyz
pqr
Slip 26
Q1. Write a java program to delete the details of given employee(Eno,
EName, Salary). Accept employee ID through commond line .(use
PreparedStatement Interface)
import java.sql.*;

public class Main {


static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/java";
static final String USER = "root";
static final String PASS = "student";

public static void main(String[] args) {


if (args.length != 1) {
System.out.println("Usage: java DeleteEmployee
<employeeID>");
return;
}

int employeeID = Integer.parseInt(args[0]);

Connection conn = null;


PreparedStatement pstmt = null;

try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER,
PASS);

String deleteSql = "DELETE FROM Employee WHERE ENo


= ?";
pstmt = conn.prepareStatement(deleteSql);
pstmt.setInt(1, employeeID);

int rowsAffected = pstmt.executeUpdate();


if (rowsAffected > 0) {
System.out.println("Employee with ID " + employeeID + "
deleted successfully.");
} else {
System.out.println("No employee found with ID " +
employeeID);
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null) pstmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}

Output: Usage: java DeleteEmployee <employeeID>


2
Employee with ID 2 deleted successfully.

1 aaa abc 10000


2 Bbb xyz 20000
After deleting
1 aaa abc 10000

Q2. Write a JSP program to calculate sum of first and last digit of a
givemn number. Display sum in Red color with font size 18.
<%@ page language="java" contentType="text/html; charset=UTF-
8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sum of First and Last Digit</title>
</head>
<body>
<h2>Sum of First and Last Digit</h2>
<form method="post" action="">
Enter a number: <input type="number" name="number"
required><br><br>
<input type="submit" value="Calculate Sum">
</form>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.text.*" %>
<%
if (request.getMethod().equals("POST")) {
int number =
Integer.parseInt(request.getParameter("number"));
int firstDigit = String.valueOf(number).charAt(0) - '0';
int lastDigit = number % 10;
int sum = firstDigit + lastDigit;
%>
<p style="color: red; font-size: 18px;">Sum of first and last digit of
<%= number %>: <%= sum %></p>
<%
}
%>
</body>
</html>

Output: Sum of First and Last Digit


Enter a number:

Sum of first and last digit of 32: 5

Slip 28
Q1. Write a JSP script to accept a string from a user and display it in
reverse order
<%@ page language="java" contentType="text/html; charset=UTF-
8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Reverse String</title>
</head>
<body>
<h2>Reverse String</h2>
<form method="post" action="">
Enter a string: <input type="text" name="inputString"
required><br><br>
<input type="submit" value="Reverse">
</form>
<%
if (request.getMethod().equals("POST")) {
String inputString = request.getParameter("inputString");
StringBuilder reversedString = new
StringBuilder(inputString).reverse();
%>
<p>Original String: <%= inputString %></p>
<p>Reversed String: <%= reversedString %></p>
<%
}
%>
</body>
</html>

Output:
Reverse String
Enter a string:

Original String: ruhana


Reversed String: anahur

Q2. Write a java program to display name of currently executing


thread in multithreading.
public class Main {
public static void main(String[] args) {
// Create and start a new thread
Thread thread = new Thread(new MyRunnable());
thread.start();

// Get and display the name of the currently executing thread


String currentThreadName = Thread.currentThread().getName();
System.out.println("Name of the currently executing thread: " +
currentThreadName);
}
}

class MyRunnable implements Runnable {


public void run() {
// Get and display the name of the currently executing thread
String currentThreadName = Thread.currentThread().getName();
System.out.println("Name of the currently executing thread in
MyRunnable: " + currentThreadName);
}
}

Output: Name of the currently executing thread: main


Name of the currently executing thread in MyRunnable: Thread-0
Slip 29
Q1. Write a java program to display information about all columns in
the DONAR table using ResultSetMetaData.
import java.sql.*;

public class Main {


static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/java";
static final String USER = "root";
static final String PASS = "student";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;

try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER,
PASS);
stmt = conn.createStatement();
String sql = "SELECT * FROM Donar";
ResultSet rs = stmt.executeQuery(sql);

ResultSetMetaData rsmd = rs.getMetaData();


int columnCount = rsmd.getColumnCount();

System.out.println("Information about columns in the


DONAR table:");
for (int i = 1; i <= columnCount; i++) {
String columnName = rsmd.getColumnName(i);
String columnType = rsmd.getColumnTypeName(i);
int columnSize = rsmd.getColumnDisplaySize(i);
boolean isNullable = rsmd.isNullable(i) ==
ResultSetMetaData.columnNullable;
System.out.println("Column Name: " + columnName);
System.out.println("Column Type: " + columnType);
System.out.println("Column Size: " + columnSize);
System.out.println("Is Nullable: " + (isNullable ? "Yes" :
"No"));
System.out.println();
}

rs.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}

Output: Information about columns in the DONAR table:


Column Name: id
Column Type: INT
Column Size: 10
Is Nullable: Yes

Column Name: Name


Column Type: TEXT
Column Size: 16383
Is Nullable: Yes

create table Donar(id int, Name text);


insert into Donar values(1,"aaa");
insert into Donar values(2,"bbb");
insert into Donar values(3,"ccc");
select * from donar;
1 aaa
2 bbb
3 ccc

Q2. Write a java program to create Linked list of integer objects and
perform the following
i. Add element at first position
ii. Delete the element
iii. Display the size of linked list

import java.util.LinkedList;

public class Main {


public static void main(String[] args) {
LinkedList<Integer> linkedList = new LinkedList<>();

// Add element at first position


linkedList.addFirst(10);
linkedList.addFirst(20);
linkedList.addFirst(30);
System.out.println("LinkedList after adding elements at first
position: " + linkedList);

// Delete last element


if (!linkedList.isEmpty()) {
linkedList.removeLast();
System.out.println("LinkedList after deleting last element: " +
linkedList);
} else {
System.out.println("LinkedList is empty.");
}

// Display the size of link list


int size = linkedList.size();
System.out.println("Size of LinkedList: " + size);
}
}
Output: LinkedList after adding elements at first position: [30, 20, 10]
LinkedList after deleting last element: [30, 20]
Size of LinkedList: 2

Slip 30
Q1. Write a java program for the implementation of synchronization.
public class Main {
public static void main(String[] args) {
// Creating shared object
Counter counter = new Counter();

// Creating and starting threads


Thread thread1 = new Thread(new IncrementTask(counter));
Thread thread2 = new Thread(new DecrementTask(counter));
thread1.start();
thread2.start();
}
}

// Shared counter class


class Counter {
private int count = 0;

// Method to increment count (synchronized)


public synchronized void increment() {
count++;
System.out.println("Incremented count to: " + count);
}

// Method to decrement count (synchronized)


public synchronized void decrement() {
count--;
System.out.println("Decremented count to: " + count);
}
}

// Runnable task to increment count


class IncrementTask implements Runnable {
private Counter counter;

public IncrementTask(Counter counter) {


this.counter = counter;
}

public void run() {


for (int i = 0; i < 5; i++) {
counter.increment();
}
}
}

// Runnable task to decrement count


class DecrementTask implements Runnable {
private Counter counter;

public DecrementTask(Counter counter) {


this.counter = counter;
}

public void run() {


for (int i = 0; i < 5; i++) {
counter.decrement();
}
}
}

Output: Incremented count to: 1


Incremented count to: 2
Incremented count to: 3
Incremented count to: 4
Incremented count to: 5
Decremented count to: 4
Decremented count to: 3
Decremented count to: 2
Decremented count to: 1
Decremented count to: 0

Q2. Write a java program for the implementation of scrollable


ResultSet. Assume teacher table with attributes (TID, TName, Salary)
is already created.
package CIA;

import java.sql.*;

public class Main {


static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/java";
static final String USER = "root";
static final String PASS = "student";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;

try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER,
PASS);
// Creating a scrollable ResultSet
stmt =
conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
String sql = "SELECT * FROM Teacher";
ResultSet rs = stmt.executeQuery(sql);

// Move cursor to the last row


rs.last();

// Display data in reverse order


System.out.println("Displaying data in reverse order:");
while (rs.previous()) {
int tid = rs.getInt("Tid");
String tname = rs.getString("Tname");
double salary = rs.getDouble("Salary");
System.out.println("TID: " + tid + ", TName: " + tname + ",
Salary: " + salary);
}

rs.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}

Output: Displaying data in reverse order:


TID: 2, TName: xyz, Salary: 30000.0
TID: 1, TName: abc, Salary: 10000.0

create table Teacher(Tid int, Tname text, Salary int);


insert into Teacher values(1,"abc",10000);
insert into teacher values(2,"xyz",30000);
insert into Teacher values(3,"pqr",25000);
select * from Teacher;

1 abc 10000
2 xyz 30000
3 pqr 25000

You might also like