0% found this document useful (0 votes)
13 views34 pages

Java Collection Programs Overview

The document contains multiple Java programming tasks, each demonstrating the use of different collection classes such as ArrayList, LinkedList, TreeSet, and Hashtable. Tasks include accepting user input for cities, friends, colors, and student contact information, as well as sorting integers and HashMaps. Additionally, it covers threading concepts, including creating threads for printing text and solving the producer-consumer problem with synchronization.

Uploaded by

kvh18137
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)
13 views34 pages

Java Collection Programs Overview

The document contains multiple Java programming tasks, each demonstrating the use of different collection classes such as ArrayList, LinkedList, TreeSet, and Hashtable. Tasks include accepting user input for cities, friends, colors, and student contact information, as well as sorting integers and HashMaps. Additionally, it covers threading concepts, including creating threads for printing text and solving the producer-consumer problem with synchronization.

Uploaded by

kvh18137
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

#A1 a) Write a java program to accept names of 'n' cities, insert same into array list collection and

display the
contents of same array list, also remove all these elements

1. import [Link];
2. import [Link];
3. public class a1
4. {
5. public static void main(String args[])
6. {
7. Scanner sc = new Scanner([Link]);
8. [Link]("Enter number of cities:");
9. int n = [Link]();
10. ArrayList<String> a1 = new ArrayList<String>();
11. [Link]();
12. for(int i = 0;i<n;i++)
13. {
a. [Link]("Enter city "+(i+1)+":");
b. String city = [Link]();
c. [Link](city);
14. }
15. [Link]("The cities are:");
16. [Link](a1);
17. [Link]();
18. [Link]("After Clearing");
19. [Link](a1);
20. }
21. }

#A2 b) Write a java program to read 'n' names of your friends, store it into linked list, also display contents of
the same.

1. import [Link];
2. import [Link].*;
3. public class a2
4. {
5. public static void main(String args[])
6. {
7. Scanner sc = new Scanner([Link]);
8. LinkedList<String> friends = new LinkedList<String>();
9. [Link]("Enter number of friends: ");
10. int n = [Link]();
11. [Link]();
12. for(int i = 0;i<n;i++)
13. {
a. [Link]("Enter Friend "+(i+1)+":");
b. String friend = [Link]();
c. [Link](friend);
14. }
15. [Link]("Friends:");
16. Iterator<String>itr = [Link]();
17. while([Link]())
18. {
a. [Link]([Link]());
19. }
20. }
21. }

#A3 c) Write a program to create a new tree set, add some colors (string) and print out the tree set

1. import [Link];
2. import [Link];
3. import [Link];
4. public class a3
5. {
6. public static void main(String args[])
7. {
8. Scanner sc = new Scanner([Link]);
9. Set<String> ts = new TreeSet<String>();
10. [Link]("Enter number of colors: ");
11. int n = [Link]();
12. [Link]();
13. for(int i = 0;i<n;i++)
14. {
a. [Link]("Enter color "+(i+1)+":");
b. String color = [Link]();
c. [Link](color);
15. }
16. [Link]("Colors:");
17. [Link](ts);
18. }
19. }

#A4 d) Create the hash table that will maintain the mobile number and student name. Display the contact list.

1. import [Link];
2. import [Link].*;
3. public class a4
4. {
5. public static void main(String args[])
6. {
7. Scanner sc = new Scanner([Link]);
8. Hashtable<String,String> ht = new Hashtable<String,String>();
9. [Link]("Enter number of students: ");
10. int n = [Link]();
11. [Link]();
12. for(int i = 0;i<n;i++)
13. {

a. [Link]("Enter Name of "+(i+1)+":");


b. String name = [Link]();
c. [Link]("Enter Mobile no: ");
d. String mob = [Link]();
e. [Link](name, mob);
14. }
15. [Link]("Hash Table:");
16. [Link](ht);
17. }
18. }

#B1 a) Accept 'n' integers from the user. Store and display integers in sorted order having proper collection class.
The collection should not accept duplicate elements.

1. import [Link];
2. import [Link];
3. import [Link];
4. public class b1
5. {
6. public static void main(String args[])
7. {
8. Scanner sc = new Scanner([Link]);
9. Set<Integer> ts = new TreeSet<Integer>();
10. [Link]("Enter how many numbers: ");
11. int n = [Link]();
12. [Link]();
13. for(int i = 0;i<n;i++)
14. {
a. [Link]("Enter number "+(i+1)+":");
b. int num = [Link]();
c. [Link](num);
15. }
16. [Link]("Sorted Numbers:");
17. [Link](ts)
18. }
19. }

#B2 Write a program to sort HashMap by keys and display the details before sorting and after sorting

1. import [Link].*;
2. public class b2
3. {
4. public static void main(String args[])
5. {
6. if([Link] == 0)
7. {
a. [Link]("khudse likh loollolllololol");
b. return;
8. }
9. Scanner sc = new Scanner([Link]);
10. HashMap<String, Integer> hashmap = new HashMap<>();

11. [Link]("Tanmay", 200);


12. [Link]("Pradip", 400);
13. [Link]("Raj", 800);
14. [Link]("Om", 100);
15. [Link]("Hashmap Before Sorting:");
16. for([Link]<String, Integer> entry: [Link]())
17. {
18. [Link]([Link]() + " : " + [Link]());
19. }

20. TreeMap<String, Integer> sortedMap = new TreeMap<>(hashmap);

21. [Link]("\nHashmap After Sorting by keys: ");


22. for([Link]<String, Integer> entry : [Link]())
23. {
a. [Link]([Link]() + " : " + [Link]());
24. }
25. }
26. }

#B3 Write a program that loads names and phone numbers from a text file where the data is organized as one
line per record and each field in a record are separated by a tab (\t). it takes a name or phone number as input
and prints the corresponding other value from the hash table (hint: use hash tables)

1. import [Link].*;
2. import [Link];
3. import [Link];
4. import [Link].*;
5. import [Link];
6. import [Link];

7. public class b3
8. {
9. public static void main(String args[]){
10. try{
11. File f = new File("[Link]");
12. BufferedReader br = null;
13. br = new BufferedReader(new FileReader(f));
14. Hashtable<String, String>table = new Hashtable<>();
15. Scanner sc = new Scanner([Link]);
16. String line = "";

17. while((line = [Link]())!=null)


18. {
a. String[] parts = [Link]("\t");
b. String name = parts[0].trim();
c. String number = parts[1].trim();

d. if(![Link]("") && ![Link](""))


e. {
f. [Link](name, number);
g. }
19. }
20. [Link]("Enter Name: ");
21. String key = [Link]();
22. if([Link](key))
23. {
a. [Link]([Link](key));
b. [Link]();
c. [Link]();
24. }
25. }
26. catch(Exception e)
27. {
28. [Link](e);
29. }
30. }
31. }

#C2 b) Write a program to create link list of integer objects. Do the following:

i. Add element at first position


ii. delete last element
iii. display the size of link list

1. import [Link].*;
2. import [Link];
3. import [Link];
4. public class c2
5. {
6. public static void displayList(LinkedList a1)
7. {
8. Iterator<Integer>itr = [Link]();
9. while([Link]())
10. {
a. [Link]([Link]());
11. }
12. }
13. public static void main(String[] args)
14. {
15. LinkedList<Integer> a1 = new LinkedList<Integer>();
16. Scanner sc = new Scanner([Link]);
17. [Link](1);
18. int choice = 0;

19. do
20. {
21. [Link]("[Link] Element at first position:");
22. [Link]("[Link] Last Element:");
23. [Link]("[Link] the size of LinkedList:");
24. [Link]("Enter your choice:");
25. choice = [Link]();

26. switch(choice)
27. {
a. case 1: [Link]("Enter Element:");
b. int el = [Link]();
c. [Link](el);
d. [Link]("Element "+el+" Entered in the LinkedList");
e. displayList(a1);
f. break;

g. case 2: int size = [Link]();


h. el = [Link](size-1);
i. [Link]("Last Element Removed");
j. displayList(a1);
k. break;

l. case 3: size = [Link]();


m. [Link]("Size of linkedList is: "+size);
n. break;
28. }
29. }while(choice!=4);
30. }
31. }

ASIIGNMENT 2
#A1 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 PrintThread extends Thread


{
private String text;
private int count;

public PrintThread(String text, int count)


{
[Link] = text;
[Link] = count;
}
@Override
public void run()
{
for(int i = 0;i<count;i++)
{
[Link](text);
try
{
[Link](100);
}
catch(InterruptedException e)
{
[Link]("Thread Interrupted:"+[Link]());
}
}
}
}

public class a1
{
public static void main(String args[])
{
Thread t1 = new PrintThread("Covid-19", 10);
Thread t2 = new PrintThread("LOCKDOWN2020", 20);
Thread t3 = new PrintThread("VACCINATED2021", 30);

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

#A2 b) Write a program in which thread sleep for 6 sec in the loop in reverse order from 100 to 1 and change the
name of thread.

1. class ReverseThread extends Thread


2. {
3. public ReverseThread(String name)
4. {
5. super(name);
6. }
7. @Override
8. public void run()
9. {
10. String ThreadName = "Thread-A";

11. for(int i = 100;i>=1;i--)


12. {
a. [Link]([Link]().getName() + ":"+ i);
b. try
c. {
d. [Link](6000);
e. }
f. catch(InterruptedException e)
g. {
h. [Link]("Thread Interrupted:" + [Link]());
i. }
j. ThreadName = [Link]().getName();
k. if(ThreadName == "Thread-A")
l. {
m. [Link]().setName("Thread-B");
n. }
o. else if(ThreadName == "Thread-B")
p. {
q. [Link]().setName("Thread-C");
r. }
s. else if(ThreadName == "Thread-C")
t. {
u. [Link]().setName("Thread-A");
v. }

13. }
14. }
15. }

16. public class a2


17. {
18. public static void main(String args[])
19. {
20. Thread t1 = new ReverseThread("Thread-A");
21. Thread t2 = new ReverseThread("Thread-B");
22. Thread t3 = new ReverseThread("Thread-C");

23. [Link]();
24. [Link]();
25. [Link]();
26. if(![Link]() && ![Link]() && ![Link]())
27. {
a. [Link]("|-----------------By Tanmay Waghmare-----------------
----|");
28. }
29. }
30. }

#A3 c) Write a program 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)

1. class SharedResources
2. {
3. private int value;
4. private boolean available = false;
5. public synchronized void produce(int newValue)
6. {
7. while(available)
8. {
a. try
b. {
c. wait();
d. }
e. catch(InterruptedException e)
f. {
g. [Link]("Producer interrupted:" + [Link]());
h. }
9. }
10. value = newValue;
11. available = true;

12. [Link]("Produced:"+ value);


13. notify();
14. }

15. public synchronized void consume()


16. {
17. while(!available)
18. {
a. try
b. {
c. wait();
d. }
e. catch(InterruptedException e)
f. {
g. [Link]("Consumer Interrupted: "+ [Link]());
h. }
19. }
20. [Link]("Consumed: " +value);
21. available = false;
22. notify();

23. }

24. }

25. class Producer extends Thread


26. {
27. private SharedResources resource;
28. public Producer (SharedResources resource)
29. {
30. [Link] = resource;
31. }
32. @Override
33. public void run()
34. {
35. for(int i = 1;i<=10;i++)
36. {
a. [Link](i);
b. try
c. {
d. [Link](1000);
e. }
f. catch(InterruptedException e)
g. {
h. [Link]("Producer Thread interrupted: "+
[Link]());
i. }
37. }
38. }
39. }

40. class Consumer extends Thread


41. {
42. private SharedResources resource;
43. public Consumer(SharedResources resource)
44. {
45. [Link] = resource;
46. }
47. @Override
48. public void run()
49. {
50. for(int i = 1;i<10;i++)
51. {
a. [Link]();
b. try
c. {
d. [Link](1000);
e. }
f. catch(InterruptedException e)
g. {
h. [Link]("Consumer thread interrupted: "+
[Link]());
i. }
52. }
53. }
54. }

55. public class a3


56. {
57. public static void main(String args[])
58. {
59. SharedResources resource = new SharedResources();
60. Producer producer = new Producer(resource);
61. Consumer consumer = new Consumer(resource);
62. [Link]();
63. [Link]();
64. }
65. }

//Set B 1 a) Write a program to calculate the sum and average of an array of 1000 integers (generated
randomly) using 10 threads. Each thread calculates the sum of 100 integers. Use these values to calculate average
[Use join method ].

import [Link];
import [Link].*;
class SumThread extends Thread
{
private int[] array;
private int startIndex;
private int sum=0;

public SumThread(int[] array,int startIndex)


{
[Link]=array;
[Link]=startIndex;
}
public void run()
{
for(int i=startIndex;i<startIndex+100;i++)
{
sum+=array[i];
}
}
public int getSum()
{
return sum;
}
}
public class b1
{
public static void main(String args[])throws InterruptedException
{
int[] array=new Random().ints(1000,1,100).toArray();
SumThread[] thread=new SumThread[10];

for(int i=0;i<10;i++)
{
thread[i]=new SumThread(array,i*100);
thread[i].start();
}
int total=0;
for(int i=0;i<10;i++)
{
thread[i].join();
total+=thread[i].getSum();
}
double avg=total/1000.0;
[Link]("Total sum: "+total);
[Link]("Average: "+avg);
}
}

//Set B 2) Write a program for a simple search engine. Accept a string to be


searched. Search for the string in all text files in the current folder. Use a
separate thread for each file The result should display the filename, line
number where the string is found.

import [Link].*;
import [Link].*;
class FileSearch extends Thread
{
private File File;
private String search;

public FileSearch(File File, String search)


{
[Link]=File;
[Link]=search;
}
public void run()
{
try(BufferedReader br=new BufferedReader(new FileReader(File)))
{
String line;
int lno=0;
while((line=[Link]())!=null)
{
lno++;
if([Link](search))
{
[Link]("Found "+search+" in "+[Link]()+" at
"+lno);
}
}
}
catch(Exception e)
{
[Link]("Error reading File "+[Link]());
}
}
}
public class b2
{
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
[Link]("Enter string to search: ");
String search=[Link]();
File f=new File(".");

for(File File : [Link]())


{
if([Link]())
{
new FileSearch(File,search).start();
}
}
}
}
#B3 c) Write a program that implements a multi-thread application that has three
threads. First thread generates random integer every 1 second and if the value is
even, second thread computes the square of the number and prints. If the value is
odd, the third thread will print the value of cube of the number.

import [Link];
class SharedData
{
private int number;
private boolean isNewNumber = false;
public synchronized void setNumber(int number)
{
while(isNewNumber)
{
try{
wait();
}catch(InterruptedException e)
{
[Link]().interrupt();
[Link]("Thread Interrupted!");
}
}
[Link] = number;
isNewNumber = true;
notifyAll();
}

public synchronized int getNumber()


{
//wait until new number is available
while(!isNewNumber)
{
try{
wait();
}catch(InterruptedException e)
{
[Link]().interrupt();
[Link]("Thread interrupted!");
}
}

isNewNumber = false;
notifyAll();
return number;
}
}

class NumberGeneration extends Thread


{
private SharedData sharedData;
private Random random;

public NumberGeneration(SharedData sharedData)


{
[Link] = sharedData;
[Link] = new Random();
}

public void run()


{
try{
while(true)
{
int number = [Link](100);
[Link]("Generated no: "+number);
[Link](number);
[Link](1000);
}
}
catch(InterruptedException e)
{
[Link]("Number Generator interrupted.");
}
}
}
class EvenSquaredThread extends Thread
{
private SharedData sharedData;
public EvenSquaredThread(SharedData sharedData)
{
[Link] = sharedData;
}

public void run()


{
while(true)
{
int num = [Link]();
if(num % 2 == 0)
{
int square = num*num;
[Link]("Even number: "+num+"\nSquare: "+square);
}
}

}
}

class OddCubeThread extends Thread


{
private SharedData sharedData;
public OddCubeThread(SharedData sharedData)
{
[Link] = sharedData;
}

public void run()


{
while(true)
{
int num = [Link]();
if(num % 2 != 0)
{
int cube = num*num*num;
[Link]("Odd no: "+num+"\nCube: "+cube);
}
}

}
}
public class b3
{
public static void main(String[] args)
{
SharedData sharedData = new SharedData();

NumberGeneration generator = new NumberGeneration(sharedData);


EvenSquaredThread even = new EvenSquaredThread(sharedData);
OddCubeThread odd = new OddCubeThread(sharedData);

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

ASSIGNMENT 3
#A1 a) Create a PROJECT table with fields project_id, Project_name,
Project_description, Project Status, etc. Insert values in the table. Display all the
details of the PROJECT table in a tabular format on the screen (using swing).

1. import [Link].*;
2. import [Link];
3. import [Link].*;
4. import [Link].*;

5. public class a1 {

6. private static final String URL = "jdbc:postgresql://[Link]/tydb180";


7. private static final String USER = "ty180";
8. private static final String PASSWORD = "";

9. public static void main(String[] args) {


10. [Link](a1::new);
11. }

12. public a1() {


13. JFrame frame = new JFrame("Project Details");
14. [Link](JFrame.EXIT_ON_CLOSE);
15. [Link](600, 400);
16. [Link](new BorderLayout());

17. String[] columnNames = {"Project ID", "Project Name",


"Description", "Status"};
18. DefaultTableModel model = new
DefaultTableModel(columnNames, 0);
19. JTable table = new JTable(model);

20. // Database Operations


21. try (Connection conn = [Link](URL, USER,
PASSWORD);
a. Statement stmt = [Link]()) {
22. String delete = "drop table PROJECT";
23. [Link](delete);
a. // Create table if not exists
b. String createTableQuery = "CREATE TABLE IF NOT EXISTS PROJECT ("
+
a. "Project_id INT PRIMARY KEY, " +
b. "Project_name VARCHAR(255), " +
c. "Project_Description TEXT, " +
d. "Project_status VARCHAR(50))";
c. [Link](createTableQuery);

d. // Insert sample data


e. String insertQuery = "INSERT INTO PROJECT (Project_id,
Project_name, Project_Description, Project_status) VALUES " +
1. "(1,'Recommendation System', 'Developing
Recommendation System using AI', 'In Progress'), " +
2. "(2,'Amazon Clone', 'Building an online shopping
platform', 'Completed')";
f. [Link](insertQuery);
g. // Fetch and display data
h. ResultSet rs = [Link]("SELECT * FROM PROJECT");
i. while ([Link]()) {
j. int id = [Link]("Project_id");
k. String name = [Link]("Project_name");
l. String desc = [Link]("Project_Description");
m. String status = [Link]("Project_status");
n. [Link](new Object[]{id, name, desc, status});
o. }
24. } catch (SQLException e) {
a. [Link]();
25. }

26. // Add components


27. JScrollPane scrollPane = new JScrollPane(table);
28. [Link](scrollPane, [Link]);
29. [Link](true);
30. }
31. }

#A2 b) Write a program to display information about the database and list all the
tables in the database. (Use DatabaseMetaData).

1. import [Link].*;

2. public class a2 {
3. private static final String URL = "jdbc:postgresql://[Link]/tydb180";
4. private static final String USER = "ty180";
5. private static final String PASSWORD = "";

6. public static void main(String[] args) {


7. try (Connection conn = [Link](URL, USER,
PASSWORD)) {
a. DatabaseMetaData metaData = [Link]();

b. // Display Database Information


c. [Link]("Database Product Name: " +
[Link]());
d. [Link]("Database Version: " +
[Link]());
e. [Link]("Driver Name: " + [Link]());
f. [Link]("Driver Version: " +
[Link]());
g. [Link]("User Name: " + [Link]());
h. [Link]("\nTables in the Database:");

i. // Fetch and List Tables


j. ResultSet tables = [Link](null, null, "%", new
String[]{"TABLE"});
k. while ([Link]()) {
l. [Link]("- " + [Link]("TABLE_NAME"));
m. }
8. } catch (SQLException e) {
a. [Link]();
9. }
10. }
11. }

#A3 c) Write a program to display information about all columns in the DONAR
table using ResultSetMetaData

import [Link].*;

public class a3 {
private static final String URL = "jdbc:postgresql://[Link]/tydb180";
private static final String USER = "ty180";
private static final String PASSWORD = "";

public static void main(String[] args) {


try (Connection conn = [Link](URL, USER,
PASSWORD);
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM DONAR LIMIT 1")) {
// Fetching only one row for metadata

ResultSetMetaData metaData = [Link]();


int columnCount = [Link]();

[Link]("Columns in the DONAR Table:");


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

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


[Link]("Column Name: " + [Link](i));
[Link]("Data Type: " + [Link](i));
[Link]("Column Size: " +
[Link](i));
[Link]("Nullable: " + ([Link](i) ==
[Link] ? "Yes" : "No"));
[Link]("Auto Increment: " + ([Link](i)
? "Yes" : "No"));
[Link]("--------------------------------------");
}
} catch (SQLException e) {
[Link]();
}
}
}

#B1 a) Create a MOBILE table with fields Model Number, Model Name,
Model_Color, Sim Type, Network Type, BatteryCapacity, Internal Storage, RAM and
Processor Type. Insert values in the table. Write a menu driven program to pass the
input using Command line argument to perform the following operations on
MOBILE table.
1. Insert 2. Modify 3. Delete 4. Search 5. View All 6. Exit

import [Link].*;

public class b1 {
static final String URL = "jdbc:postgresql://[Link]/tydb180";
static final String USER = "ty180";
static final String PASSWORD = "your_password";

public static void main(String[] args) {


if ([Link] == 0) {
[Link]("Usage: java MobileDatabaseManager <operation>
[parameters]");
return;
}

String operation = args[0];

try (Connection conn = [Link](URL, USER,


PASSWORD)) {
switch (operation) {
case "Insert":
if ([Link] < 10) {
[Link]("Usage: Insert <Model_Number>
<Model_Name> <Model_Color> <Sim_Type> <NetworkType>
<BatteryCapacity> <InternalStorage> <RAM> <ProcessorType>");
return;
}
insertMobile(conn, args);
break;

case "Modify":
if ([Link] < 3) {
[Link]("Usage: Modify <Model_Number>
<Column_Name> <New_Value>");
return;
}
modifyMobile(conn, args);
break;

case "Delete":
if ([Link] < 2) {
[Link]("Usage: Delete <Model_Number>");
return;
}
deleteMobile(conn, args[1]);
break;

case "Search":
if ([Link] < 2) {
[Link]("Usage: Search <Model_Number>");
return;
}
searchMobile(conn, args[1]);
break;

case "ViewAll":
viewAllMobiles(conn);
break;

case "Exit":
[Link]("Exiting program...");
break;

default:
[Link]("Invalid operation. Use Insert, Modify, Delete,
Search, ViewAll, or Exit.");
}
} catch (SQLException e) {
[Link]();
}
}

// Insert a new mobile record


private static void insertMobile(Connection conn, String[] args) throws
SQLException {
String sql = "INSERT INTO MOBILE VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement stmt = [Link](sql)) {
[Link](1, args[1]);
[Link](2, args[2]);
[Link](3, args[3]);
[Link](4, args[4]);
[Link](5, args[5]);
[Link](6, [Link](args[6]));
[Link](7, [Link](args[7]));
[Link](8, [Link](args[8]));
[Link](9, args[9]);

int rows = [Link]();


[Link](rows > 0 ? "Mobile inserted successfully!" : "Insertion
failed.");
}
}

// Modify an existing mobile record


private static void modifyMobile(Connection conn, String[] args) throws
SQLException {
String sql = "UPDATE MOBILE SET " + args[2] + " = ? WHERE Model_Number
= ?";
try (PreparedStatement stmt = [Link](sql)) {
[Link](1, args[3]);
[Link](2, args[1]);

int rows = [Link]();


[Link](rows > 0 ? "Mobile updated successfully!" : "Update
failed.");
}
}

// Delete a mobile record


private static void deleteMobile(Connection conn, String modelNumber)
throws SQLException {
String sql = "DELETE FROM MOBILE WHERE Model_Number = ?";
try (PreparedStatement stmt = [Link](sql)) {
[Link](1, modelNumber);

int rows = [Link]();


[Link](rows > 0 ? "Mobile deleted successfully!" : "No such
record found.");
}
}

// Search for a mobile record


private static void searchMobile(Connection conn, String modelNumber)
throws SQLException {
String sql = "SELECT * FROM MOBILE WHERE Model_Number = ?";
try (PreparedStatement stmt = [Link](sql)) {
[Link](1, modelNumber);
ResultSet rs = [Link]();

if ([Link]()) {
[Link]("Model Number: " +
[Link]("Model_Number"));
[Link]("Model Name: " + [Link]("Model_Name"));
[Link]("Color: " + [Link]("Model_Color"));
[Link]("Sim Type: " + [Link]("Sim_Type"));
[Link]("Network Type: " + [Link]("NetworkType"));
[Link]("Battery: " + [Link]("BatteryCapacity") + "mAh");
[Link]("Storage: " + [Link]("InternalStorage") + "GB");
[Link]("RAM: " + [Link]("RAM") + "GB");
[Link]("Processor: " + [Link]("ProcessorType"));
} else {
[Link]("No record found.");
}
}
}

// View all mobile records


private static void viewAllMobiles(Connection conn) throws SQLException {
String sql = "SELECT * FROM MOBILE";
try (PreparedStatement stmt = [Link](sql);
ResultSet rs = [Link]()) {

while ([Link]()) {
[Link]("Model Number: " + [Link]("Model_Number")
+
", Name: " + [Link]("Model_Name") +
", Color: " + [Link]("Model_Color") +
", Sim: " + [Link]("Sim_Type") +
", Network: " + [Link]("NetworkType") +
", Battery: " + [Link]("BatteryCapacity") + "mAh" +
", Storage: " + [Link]("InternalStorage") + "GB" +
", RAM: " + [Link]("RAM") + "GB" +
", Processor: " + [Link]("ProcessorType"));
}
}
}
}

ASSIGNMENT 4
a) Design a servlet that provides information about a HTTP request from a client,
such as IP address and browser type. The servlet also provides information about
the server on which the servlet is running, such as the operating system type, and
the names of currently loaded servlets.

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

public class InfoServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

// Set response content type


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

// Get client information


String clientIP = [Link]();
String userAgent = [Link]("User-Agent");

// Get server information


String osName = [Link]("[Link]");

// Get all servlet names from ServletContext


ServletContext context = getServletContext();
Enumeration<String> servletNames = [Link](); // Only
works in Servlet 4.0+

[Link]("<html><body>");
[Link]("<h2>Client Information</h2>");
[Link]("<p><strong>IP Address:</strong> " + clientIP + "</p>");
[Link]("<p><strong>Browser (User-Agent):</strong> " + userAgent +
"</p>");

[Link]("<h2>Server Information</h2>");
[Link]("<p><strong>Operating System:</strong> " + osName +
"</p>");

[Link]("<h2>Loaded Servlets</h2>");
if (servletNames != null) {
[Link]("<ul>");
while ([Link]()) {
[Link]("<li>" + [Link]() + "</li>");
}
[Link]("</ul>");
} else {
[Link]("<p>Servlet names not available (Check Servlet API
version)</p>");
}

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

#[Link]
import [Link].*;

public class DatabaseInfo {


private static final String URL = "jdbc:mysql://localhost:3306/your_database";
// Replace with your database
private static final String USER = "your_username"; // Replace with your DB
username
private static final String PASSWORD = "your_password"; // Replace with
your DB password

public static void main(String[] args) {


try (Connection conn = [Link](URL, USER,
PASSWORD)) {
DatabaseMetaData metaData = [Link]();
// Display Database Information
[Link]("Database Product Name: " +
[Link]());
[Link]("Database Version: " +
[Link]());
[Link]("Driver Name: " + [Link]());
[Link]("Driver Version: " + [Link]());
[Link]("User Name: " + [Link]());
[Link]("\nTables in the Database:");

// Fetch and List Tables


ResultSet tables = [Link](null, null, "%", new
String[]{"TABLE"});
while ([Link]()) {
[Link]("- " + [Link]("TABLE_NAME"));
}
} catch (SQLException e) {
[Link]();
}
}
}

#[Link]
import [Link].*;

public class DonarTableInfo {


private static final String URL = "jdbc:mysql://localhost:3306/your_database";
// Replace with your database name
private static final String USER = "your_username"; // Replace with your DB
username
private static final String PASSWORD = "your_password"; // Replace with
your DB password

public static void main(String[] args) {


try (Connection conn = [Link](URL, USER,
PASSWORD);
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM DONAR LIMIT 1")) {
// Fetching only one row for metadata

ResultSetMetaData metaData = [Link]();


int columnCount = [Link]();

[Link]("Columns in the DONAR Table:");


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

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


[Link]("Column Name: " + [Link](i));
[Link]("Data Type: " + [Link](i));
[Link]("Column Size: " +
[Link](i));
[Link]("Nullable: " + ([Link](i) ==
[Link] ? "Yes" : "No"));
[Link]("Auto Increment: " + ([Link](i)
? "Yes" : "No"));
[Link]("--------------------------------------");
}
} catch (SQLException e) {
[Link]();
}
}
}

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

public class ProjectTableDisplay {

private static final String URL = "jdbc:postgresql: [Link]:tydb180";


private static final String USER = "ty180";
private static final String PASSWORD = "";

public static void main(String[] args) {


[Link](ProjectTableDisplay::new);
}

public ProjectTableDisplay() {
JFrame frame = new JFrame("Project Details");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](600, 400);
[Link](new BorderLayout());

String[] columnNames = {"Project ID", "Project Name", "Description",


"Status"};
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
JTable table = new JTable(model);

// Database Operations
try (Connection conn = [Link](URL, USER,
PASSWORD);
Statement stmt = [Link]()) {

// Create table if not exists


String createTableQuery = "CREATE TABLE IF NOT EXISTS PROJECT (" +
"Project_id INT PRIMARY KEY AUTO_INCREMENT, " +
"Project_name VARCHAR(255), " +
"Project_Description TEXT, " +
"Project_status VARCHAR(50))";
[Link](createTableQuery);

// Insert sample data


String insertQuery = "INSERT INTO PROJECT (Project_name,
Project_Description, Project_status) VALUES " +
"('AI Chatbot', 'Developing an AI-powered chatbot', 'In
Progress'), " +
"('E-commerce App', 'Building an online shopping platform',
'Completed')";
[Link](insertQuery);

// Fetch and display data


ResultSet rs = [Link]("SELECT * FROM PROJECT");
while ([Link]()) {
int id = [Link]("Project_id");
String name = [Link]("Project_name");
String desc = [Link]("Project_Description");
String status = [Link]("Project_status");
[Link](new Object[]{id, name, desc, status});
}
} catch (SQLException e) {
[Link]();
}

// Add components
JScrollPane scrollPane = new JScrollPane(table);
[Link](scrollPane, [Link]);
[Link](true);
}
}

Common questions

Powered by AI

Hashtables in Java can suffer from performance pitfalls primarily due to their inherent design limitations. Despite providing average O(1) time for get and put operations, performance can degrade to O(n) in the worst case when hash collisions occur frequently. This occurs if many keys map to the same hash code bucket, which requires the use of a linked list traversal . A Hashtable is also not synchronized with the collections framework, meaning explicit synchronization is needed when access is shared across threads. For applications requiring concurrent operations, a ConcurrentHashMap would be more appropriate as it handles synchronization efficiently while maintaining performance . Additionally, Hashtables do not maintain any order—scenarios needing ordered keys or sorted access might benefit more from using TreeMap or LinkedHashMap .

Using a HashMap in Java has the advantage of providing average O(1) time complexity for retrieval operations due to direct hashing. However, HashMap does not maintain any order of the elements, meaning inserted order is not preserved, and elements do not follow any sortable order . This can be a significant limitation when the order of elements is crucial for application logic or output. In such cases, LinkedHashMap provides an alternative as it maintains a doubly-linked list structure along with hashing to preserve insertion order. When natural sorting or custom orders are necessary, TreeMap would be a better choice as it orders keys based on natural ordering or a custom Comparator . Each choice involves a trade-off between higher memory usage and additional overhead for order maintenance instead of purely optimized retrieval times .

In Java, each thread has a priority that affects its scheduling; threads with higher priority are generally executed in preference to threads with lower priority. However, thread priorities are not a guarantee for execution order, especially with scheduling behavior varying across platforms and JVM implementations. Java uses a fixed-priority scheduling algorithm, with priorities ranging from MIN_PRIORITY (1) to MAX_PRIORITY (10), defaulting at NORM_PRIORITY (5). While higher priority threads typically receive more CPU time, excessive reliance on priority can lead to thread starvation where lower priority threads are never executed. Therefore, while priorities can guide thread execution, they should be used carefully in conjunction with proper thread handling techniques like using thread joins and cooperation policies such as wait/notify to manage task execution efficiently .

Database metadata and result set metadata serve different yet complementary roles in a Java JDBC application. DatabaseMetaData provides comprehensive details about the database itself, such as product name, version, the capabilities of the database, and structural information about tables and schemas . This is particularly useful for schema exploration and assessing database capabilities. On the other hand, ResultSetMetaData offers information related to the specific ResultSet object columns, such as their data types, sizes, and immediate properties like nullability and auto-increment status . While DatabaseMetaData is crucial for dynamically adapting to different databases and understanding their broader structures, ResultSetMetaData is essential for dealing with and dynamically processing the results of SQL queries. Together, they facilitate both high-level database management and precise data retrieval operations, empowering flexible application design adaptable to varying data environments .

ResultSetMetaData is highly effective in Java for dynamically retrieving information about database columns. It allows for an in-depth understanding of the column properties of a ResultSet, such as column name, type, size, and nullability, which is beneficial in dynamic SQL queries or when dealing with unknown database schemas . This capability is particularly useful in creating generic data processing or reporting tools where the structure of the data source might not be known at compile time. Developers can use this metadata to build adaptable applications that can automatically adjust to varying database schemas without hardcoding column details, which enhances flexibility and reduces maintenance overhead . Nevertheless, when using ResultSetMetaData, one should be cautious about potential performance implications, especially in large datasets, as metadata retrieval can be relatively resource-intensive .

Java's Swing framework supports the display of database results through GUI components such as JTable, which can be used alongside a table model like DefaultTableModel to render database records visually . This capability allows developers to present data fetched from databases (e.g., via JDBC) in an organized, tabular format, minimizing the need for manual rendering of records on a UI. Swing's integration with database handling using table models facilitates dynamic data manipulation, allowing for real-time updates from backend changes . The benefits include an interactive and user-friendly interface for users, enabling operations like sorting, filtering, and pagination directly within the UI layer without delving into complex GUI management. This enhances both developer productivity and user experience by separating presentation logic from data retreival processes .

Running multiple threads in Java with sleep intervals introduces challenges such as potential resource contention, unresponsive applications, and complex debugging scenarios due to timing issues. Thread.sleep can cause unexpected delays and may lead to inefficient CPU usage as all threads waiting on a resource will remain blocked during the sleep period . It can also cause thread synchronization issues if threads wake up at unpredictable times, disrupting process flow. These challenges can be mitigated by using higher-level concurrency utilities provided by the java.util.concurrent package, such as Executors for managing thread pools, and ScheduledExecutorService for scheduling tasks with fixed delay or period. These utilities handle timing more gracefully and avoid manual sleep management, while synchronized blocks or locks can prevent race conditions among threads accessing shared resources . Proper thread management and synchronization ensure that resource usage is optimized and application responsiveness is maintained .

A TreeSet in Java uses a Red-Black tree structure, which ensures that elements are stored in a naturally sorted order. The ordering is determined by the natural ordering of the elements (i.e., elements that implement Comparable) or by a comparator provided at set creation time . This automatic sorting means that you cannot add duplicate elements, as the tree structure only allows unique values. These features make TreeSet suitable for scenarios where quick lookup and storage without duplicates are needed, but less so for unsorted data or when insertion order needs to be preserved, as seen in other collections like LinkedList .

The Producer-Consumer problem in Java can be effectively solved using thread synchronization mechanisms by ensuring that shared resources (like a buffer or queue) are properly synchronized to prevent concurrent access issues. The solution typically involves using a synchronized block or locks to control access to shared data. Java's concurrency utilities, such as the BlockingQueue, can offer a robust solution without manual synchronization, as they handle the necessary waiting and notify logic for producers and consumers automatically. BlockingQueues are thread-safe and designed to efficiently manage concurrent producers and consumers, with built-in handling of the blocking and signaling required when the queue is full or empty, respectively . Such mechanisms ensure data consistency and prevent race conditions without the complexity of managing low-level synchronization manually .

A LinkedList in Java is advantageous for scenarios involving frequent insertions and deletions because it is a doubly-linked list structure. This allows for efficient operations like adding or removing elements from both ends or even the middle of the list, as these operations do not require shifting elements, unlike an ArrayList. Consequently, LinkedLists provide better performance than ArrayLists when insertions and deletions are frequent, particularly in large datasets . However, it is less efficient than ArrayList for random access, as elements must be accessed sequentially .

You might also like