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

java-assignments

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
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

java-assignments

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
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

#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 java.util.Scanner;
2. import java.util.ArrayList;
3. public class a1
4. {
5. public static void main(String args[])
6. {
7. Scanner sc = new Scanner(System.in);
8. System.out.println("Enter number of cities:");
9. int n = sc.nextInt();
10. ArrayList<String> a1 = new ArrayList<String>();
11. sc.nextLine();
12. for(int i = 0;i<n;i++)
13. {
a. System.out.print("Enter city "+(i+1)+":");
b. String city = sc.nextLine();
c. a1.add(city);
14. }
15. System.out.println("The cities are:");
16. System.out.println(a1);
17. a1.clear();
18. System.out.println("After Clearing");
19. System.out.println(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 java.util.Scanner;
2. import java.util.*;
3. public class a2
4. {
5. public static void main(String args[])
6. {
7. Scanner sc = new Scanner(System.in);
8. LinkedList<String> friends = new LinkedList<String>();
9. System.out.print("Enter number of friends: ");
10. int n = sc.nextInt();
11. sc.nextLine();
12. for(int i = 0;i<n;i++)
13. {
a. System.out.print("Enter Friend "+(i+1)+":");
b. String friend = sc.nextLine();
c. friends.add(friend);
14. }
15. System.out.println("Friends:");
16. Iterator<String>itr = friends.iterator();
17. while(itr.hasNext())
18. {
a. System.out.println(itr.next());
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 java.util.Scanner;
2. import java.util.Set;
3. import java.util.TreeSet;
4. public class a3
5. {
6. public static void main(String args[])
7. {
8. Scanner sc = new Scanner(System.in);
9. Set<String> ts = new TreeSet<String>();
10. System.out.print("Enter number of colors: ");
11. int n = sc.nextInt();
12. sc.nextLine();
13. for(int i = 0;i<n;i++)
14. {
a. System.out.print("Enter color "+(i+1)+":");
b. String color = sc.nextLine();
c. ts.add(color);
15. }
16. System.out.println("Colors:");
17. System.out.println(ts);
18. }
19. }

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

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

a. System.out.print("Enter Name of "+(i+1)+":");


b. String name = sc.nextLine();
c. System.out.print("Enter Mobile no: ");
d. String mob = sc.nextLine();
e. ht.put(name, mob);
14. }
15. System.out.println("Hash Table:");
16. System.out.println(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 java.util.Scanner;
2. import java.util.Set;
3. import java.util.TreeSet;
4. public class b1
5. {
6. public static void main(String args[])
7. {
8. Scanner sc = new Scanner(System.in);
9. Set<Integer> ts = new TreeSet<Integer>();
10. System.out.print("Enter how many numbers: ");
11. int n = sc.nextInt();
12. sc.nextLine();
13. for(int i = 0;i<n;i++)
14. {
a. System.out.print("Enter number "+(i+1)+":");
b. int num = sc.nextInt();
c. ts.add(num);
15. }
16. System.out.println("Sorted Numbers:");
17. System.out.println(ts)
18. }
19. }

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

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

11. hashmap.put("Tanmay", 200);


12. hashmap.put("Pradip", 400);
13. hashmap.put("Raj", 800);
14. hashmap.put("Om", 100);
15. System.out.println("Hashmap Before Sorting:");
16. for(Map.Entry<String, Integer> entry: hashmap.entrySet())
17. {
18. System.out.println(entry.getKey() + " : " + entry.getValue());
19. }

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

21. System.out.println("\nHashmap After Sorting by keys: ");


22. for(Map.Entry<String, Integer> entry : sortedMap.entrySet())
23. {
a. System.out.println(entry.getKey() + " : " + entry.getValue());
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 java.util.*;
2. import java.io.BufferedReader;
3. import java.io.File;
4. import java.io.*;
5. import java.util.Scanner;
6. import java.util.Scanner;

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

17. while((line = br.readLine())!=null)


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

d. if(!name.equals("") && !number.equals(""))


e. {
f. table.put(name, number);
g. }
19. }
20. System.out.println("Enter Name: ");
21. String key = sc.nextLine();
22. if(table.containsKey(key))
23. {
a. System.out.println(table.get(key));
b. br.close();
c. sc.close();
24. }
25. }
26. catch(Exception e)
27. {
28. System.out.println(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 java.util.*;
2. import java.util.Scanner;
3. import java.util.Iterator;
4. public class c2
5. {
6. public static void displayList(LinkedList a1)
7. {
8. Iterator<Integer>itr = a1.iterator();
9. while(itr.hasNext())
10. {
a. System.out.println(itr.next());
11. }
12. }
13. public static void main(String[] args)
14. {
15. LinkedList<Integer> a1 = new LinkedList<Integer>();
16. Scanner sc = new Scanner(System.in);
17. a1.add(1);
18. int choice = 0;

19. do
20. {
21. System.out.println("1.Enter Element at first position:");
22. System.out.println("2.Delete Last Element:");
23. System.out.println("3.Display the size of LinkedList:");
24. System.out.print("Enter your choice:");
25. choice = sc.nextInt();

26. switch(choice)
27. {
a. case 1: System.out.print("Enter Element:");
b. int el = sc.nextInt();
c. a1.addFirst(el);
d. System.out.println("Element "+el+" Entered in the LinkedList");
e. displayList(a1);
f. break;

g. case 2: int size = a1.size();


h. el = a1.remove(size-1);
i. System.out.println("Last Element Removed");
j. displayList(a1);
k. break;

l. case 3: size = a1.size();


m. System.out.println("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)


{
this.text = text;
this.count = count;
}
@Override
public void run()
{
for(int i = 0;i<count;i++)
{
System.out.println(text);
try
{
Thread.sleep(100);
}
catch(InterruptedException e)
{
System.out.println("Thread Interrupted:"+e.getMessage());
}
}
}
}

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

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

#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. System.out.println(Thread.currentThread().getName() + ":"+ i);
b. try
c. {
d. Thread.sleep(6000);
e. }
f. catch(InterruptedException e)
g. {
h. System.out.print("Thread Interrupted:" + e.getMessage());
i. }
j. ThreadName = Thread.currentThread().getName();
k. if(ThreadName == "Thread-A")
l. {
m. Thread.currentThread().setName("Thread-B");
n. }
o. else if(ThreadName == "Thread-B")
p. {
q. Thread.currentThread().setName("Thread-C");
r. }
s. else if(ThreadName == "Thread-C")
t. {
u. Thread.currentThread().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. t1.start();
24. t2.start();
25. t3.start();
26. if(!t1.isAlive() && !t2.isAlive() && !t3.isAlive())
27. {
a. System.out.print("|-----------------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. System.out.println("Producer interrupted:" + e.getMessage());
h. }
9. }
10. value = newValue;
11. available = true;

12. System.out.println("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. System.out.println("Consumer Interrupted: "+ e.getMessage());
h. }
19. }
20. System.out.println("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. this.resource = resource;
31. }
32. @Override
33. public void run()
34. {
35. for(int i = 1;i<=10;i++)
36. {
a. resource.produce(i);
b. try
c. {
d. Thread.sleep(1000);
e. }
f. catch(InterruptedException e)
g. {
h. System.out.println("Producer Thread interrupted: "+
e.getMessage());
i. }
37. }
38. }
39. }

40. class Consumer extends Thread


41. {
42. private SharedResources resource;
43. public Consumer(SharedResources resource)
44. {
45. this.resource = resource;
46. }
47. @Override
48. public void run()
49. {
50. for(int i = 1;i<10;i++)
51. {
a. resource.consume();
b. try
c. {
d. Thread.sleep(1000);
e. }
f. catch(InterruptedException e)
g. {
h. System.out.println("Consumer thread interrupted: "+
e.getMessage());
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. producer.start();
63. consumer.start();
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 java.util.Random;
import java.util.*;
class SumThread extends Thread
{
private int[] array;
private int startIndex;
private int sum=0;

public SumThread(int[] array,int startIndex)


{
this.array=array;
this.startIndex=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;
System.out.println("Total sum: "+total);
System.out.println("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 java.util.*;
import java.io.*;
class FileSearch extends Thread
{
private File File;
private String search;

public FileSearch(File File, String search)


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

for(File File : f.listFiles())


{
if(File.isFile())
{
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 java.util.Random;
class SharedData
{
private int number;
private boolean isNewNumber = false;
public synchronized void setNumber(int number)
{
while(isNewNumber)
{
try{
wait();
}catch(InterruptedException e)
{
Thread.currentThread().interrupt();
System.out.println("Thread Interrupted!");
}
}
this.number = number;
isNewNumber = true;
notifyAll();
}

public synchronized int getNumber()


{
//wait until new number is available
while(!isNewNumber)
{
try{
wait();
}catch(InterruptedException e)
{
Thread.currentThread().interrupt();
System.out.println("Thread interrupted!");
}
}

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

class NumberGeneration extends Thread


{
private SharedData sharedData;
private Random random;

public NumberGeneration(SharedData sharedData)


{
this.sharedData = sharedData;
this.random = new Random();
}

public void run()


{
try{
while(true)
{
int number = random.nextInt(100);
System.out.println("Generated no: "+number);
sharedData.setNumber(number);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Number Generator interrupted.");
}
}
}
class EvenSquaredThread extends Thread
{
private SharedData sharedData;
public EvenSquaredThread(SharedData sharedData)
{
this.sharedData = sharedData;
}

public void run()


{
while(true)
{
int num = sharedData.getNumber();
if(num % 2 == 0)
{
int square = num*num;
System.out.println("Even number: "+num+"\nSquare: "+square);
}
}

}
}

class OddCubeThread extends Thread


{
private SharedData sharedData;
public OddCubeThread(SharedData sharedData)
{
this.sharedData = sharedData;
}

public void run()


{
while(true)
{
int num = sharedData.getNumber();
if(num % 2 != 0)
{
int cube = num*num*num;
System.out.println("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);

generator.start();
even.start();
odd.start();
}
}

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 javax.swing.*;
2. import javax.swing.table.DefaultTableModel;
3. import java.awt.*;
4. import java.sql.*;

5. public class a1 {

6. private static final String URL = "jdbc:postgresql://192.168.0.10/tydb180";


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

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


10. SwingUtilities.invokeLater(a1::new);
11. }

12. public a1() {


13. JFrame frame = new JFrame("Project Details");
14. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15. frame.setSize(600, 400);
16. frame.setLayout(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 = DriverManager.getConnection(URL, USER,
PASSWORD);
a. Statement stmt = conn.createStatement()) {
22. String delete = "drop table PROJECT";
23. stmt.executeUpdate(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. stmt.executeUpdate(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. stmt.executeUpdate(insertQuery);
g. // Fetch and display data
h. ResultSet rs = stmt.executeQuery("SELECT * FROM PROJECT");
i. while (rs.next()) {
j. int id = rs.getInt("Project_id");
k. String name = rs.getString("Project_name");
l. String desc = rs.getString("Project_Description");
m. String status = rs.getString("Project_status");
n. model.addRow(new Object[]{id, name, desc, status});
o. }
24. } catch (SQLException e) {
a. e.printStackTrace();
25. }

26. // Add components


27. JScrollPane scrollPane = new JScrollPane(table);
28. frame.add(scrollPane, BorderLayout.CENTER);
29. frame.setVisible(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 java.sql.*;

2. public class a2 {
3. private static final String URL = "jdbc:postgresql://192.168.0.10/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 = DriverManager.getConnection(URL, USER,
PASSWORD)) {
a. DatabaseMetaData metaData = conn.getMetaData();

b. // Display Database Information


c. System.out.println("Database Product Name: " +
metaData.getDatabaseProductName());
d. System.out.println("Database Version: " +
metaData.getDatabaseProductVersion());
e. System.out.println("Driver Name: " + metaData.getDriverName());
f. System.out.println("Driver Version: " +
metaData.getDriverVersion());
g. System.out.println("User Name: " + metaData.getUserName());
h. System.out.println("\nTables in the Database:");

i. // Fetch and List Tables


j. ResultSet tables = metaData.getTables(null, null, "%", new
String[]{"TABLE"});
k. while (tables.next()) {
l. System.out.println("- " + tables.getString("TABLE_NAME"));
m. }
8. } catch (SQLException e) {
a. e.printStackTrace();
9. }
10. }
11. }

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

import java.sql.*;

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

public static void main(String[] args) {


try (Connection conn = DriverManager.getConnection(URL, USER,
PASSWORD);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM DONAR LIMIT 1")) {
// Fetching only one row for metadata

ResultSetMetaData metaData = rs.getMetaData();


int columnCount = metaData.getColumnCount();

System.out.println("Columns in the DONAR Table:");


System.out.println("--------------------------------------");

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


System.out.println("Column Name: " + metaData.getColumnName(i));
System.out.println("Data Type: " + metaData.getColumnTypeName(i));
System.out.println("Column Size: " +
metaData.getColumnDisplaySize(i));
System.out.println("Nullable: " + (metaData.isNullable(i) ==
ResultSetMetaData.columnNullable ? "Yes" : "No"));
System.out.println("Auto Increment: " + (metaData.isAutoIncrement(i)
? "Yes" : "No"));
System.out.println("--------------------------------------");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

#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 java.sql.*;

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

public static void main(String[] args) {


if (args.length == 0) {
System.out.println("Usage: java MobileDatabaseManager <operation>
[parameters]");
return;
}

String operation = args[0];

try (Connection conn = DriverManager.getConnection(URL, USER,


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

case "Modify":
if (args.length < 3) {
System.out.println("Usage: Modify <Model_Number>
<Column_Name> <New_Value>");
return;
}
modifyMobile(conn, args);
break;

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

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

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

case "Exit":
System.out.println("Exiting program...");
break;

default:
System.out.println("Invalid operation. Use Insert, Modify, Delete,
Search, ViewAll, or Exit.");
}
} catch (SQLException e) {
e.printStackTrace();
}
}

// Insert a new mobile record


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

int rows = stmt.executeUpdate();


System.out.println(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 = conn.prepareStatement(sql)) {
stmt.setString(1, args[3]);
stmt.setString(2, args[1]);

int rows = stmt.executeUpdate();


System.out.println(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 = conn.prepareStatement(sql)) {
stmt.setString(1, modelNumber);

int rows = stmt.executeUpdate();


System.out.println(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 = conn.prepareStatement(sql)) {
stmt.setString(1, modelNumber);
ResultSet rs = stmt.executeQuery();

if (rs.next()) {
System.out.println("Model Number: " +
rs.getString("Model_Number"));
System.out.println("Model Name: " + rs.getString("Model_Name"));
System.out.println("Color: " + rs.getString("Model_Color"));
System.out.println("Sim Type: " + rs.getString("Sim_Type"));
System.out.println("Network Type: " + rs.getString("NetworkType"));
System.out.println("Battery: " + rs.getInt("BatteryCapacity") + "mAh");
System.out.println("Storage: " + rs.getInt("InternalStorage") + "GB");
System.out.println("RAM: " + rs.getInt("RAM") + "GB");
System.out.println("Processor: " + rs.getString("ProcessorType"));
} else {
System.out.println("No record found.");
}
}
}

// View all mobile records


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

while (rs.next()) {
System.out.println("Model Number: " + rs.getString("Model_Number")
+
", Name: " + rs.getString("Model_Name") +
", Color: " + rs.getString("Model_Color") +
", Sim: " + rs.getString("Sim_Type") +
", Network: " + rs.getString("NetworkType") +
", Battery: " + rs.getInt("BatteryCapacity") + "mAh" +
", Storage: " + rs.getInt("InternalStorage") + "GB" +
", RAM: " + rs.getInt("RAM") + "GB" +
", Processor: " + rs.getString("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 javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class InfoServlet extends HttpServlet {

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

// Set response content type


response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Get client information


String clientIP = request.getRemoteAddr();
String userAgent = request.getHeader("User-Agent");

// Get server information


String osName = System.getProperty("os.name");

// Get all servlet names from ServletContext


ServletContext context = getServletContext();
Enumeration<String> servletNames = context.getServletNames(); // Only
works in Servlet 4.0+

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

out.println("<h2>Server Information</h2>");
out.println("<p><strong>Operating System:</strong> " + osName +
"</p>");

out.println("<h2>Loaded Servlets</h2>");
if (servletNames != null) {
out.println("<ul>");
while (servletNames.hasMoreElements()) {
out.println("<li>" + servletNames.nextElement() + "</li>");
}
out.println("</ul>");
} else {
out.println("<p>Servlet names not available (Check Servlet API
version)</p>");
}

out.println("</body></html>");
}
}

#DATABASEINFO.JAVA
import java.sql.*;

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 = DriverManager.getConnection(URL, USER,
PASSWORD)) {
DatabaseMetaData metaData = conn.getMetaData();
// Display Database Information
System.out.println("Database Product Name: " +
metaData.getDatabaseProductName());
System.out.println("Database Version: " +
metaData.getDatabaseProductVersion());
System.out.println("Driver Name: " + metaData.getDriverName());
System.out.println("Driver Version: " + metaData.getDriverVersion());
System.out.println("User Name: " + metaData.getUserName());
System.out.println("\nTables in the Database:");

// Fetch and List Tables


ResultSet tables = metaData.getTables(null, null, "%", new
String[]{"TABLE"});
while (tables.next()) {
System.out.println("- " + tables.getString("TABLE_NAME"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

#DONORTABLEINFO.java
import java.sql.*;

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 = DriverManager.getConnection(URL, USER,
PASSWORD);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM DONAR LIMIT 1")) {
// Fetching only one row for metadata

ResultSetMetaData metaData = rs.getMetaData();


int columnCount = metaData.getColumnCount();

System.out.println("Columns in the DONAR Table:");


System.out.println("--------------------------------------");

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


System.out.println("Column Name: " + metaData.getColumnName(i));
System.out.println("Data Type: " + metaData.getColumnTypeName(i));
System.out.println("Column Size: " +
metaData.getColumnDisplaySize(i));
System.out.println("Nullable: " + (metaData.isNullable(i) ==
ResultSetMetaData.columnNullable ? "Yes" : "No"));
System.out.println("Auto Increment: " + (metaData.isAutoIncrement(i)
? "Yes" : "No"));
System.out.println("--------------------------------------");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

#projecttabledisplay.java
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;

public class ProjectTableDisplay {

private static final String URL = "jdbc:postgresql: 192.168.0.10:tydb180";


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

public static void main(String[] args) {


SwingUtilities.invokeLater(ProjectTableDisplay::new);
}

public ProjectTableDisplay() {
JFrame frame = new JFrame("Project Details");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
frame.setLayout(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 = DriverManager.getConnection(URL, USER,
PASSWORD);
Statement stmt = conn.createStatement()) {

// 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))";
stmt.executeUpdate(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')";
stmt.executeUpdate(insertQuery);

// Fetch and display data


ResultSet rs = stmt.executeQuery("SELECT * FROM PROJECT");
while (rs.next()) {
int id = rs.getInt("Project_id");
String name = rs.getString("Project_name");
String desc = rs.getString("Project_Description");
String status = rs.getString("Project_status");
model.addRow(new Object[]{id, name, desc, status});
}
} catch (SQLException e) {
e.printStackTrace();
}

// Add components
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setVisible(true);
}
}

You might also like