Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Practical Assignment Java-II (1, 2 & 3)

The document contains multiple Java programming assignments that cover various topics including data structures like HashSet, LinkedList, and TreeSet, as well as multithreading and database operations using JDBC. Each assignment includes a specific task, such as reading names into a HashSet, simulating a traffic signal with threads, and managing employee and product records in a database. The document provides complete code examples for each task, demonstrating the implementation of Java concepts.

Uploaded by

Shruti Kondekar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Practical Assignment Java-II (1, 2 & 3)

The document contains multiple Java programming assignments that cover various topics including data structures like HashSet, LinkedList, and TreeSet, as well as multithreading and database operations using JDBC. Each assignment includes a specific task, such as reading names into a HashSet, simulating a traffic signal with threads, and managing employee and product records in a database. The document provides complete code examples for each task, demonstrating the implementation of Java concepts.

Uploaded by

Shruti Kondekar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

PRACTICAL ASSIGNMENT-1 JAVA-II

Q.1.Write a java program to read ‘N’ names of your friends, store it into
HashSet And display them in ascending order.

ANS.

import java.util.*;

public class FriendNamesHashSet

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

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

int n = sc.nextInt();

sc.nextLine();

HashSet<String> friendsSet = new HashSet<>();

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

friendsSet.add(sc.nextLine());

List<String> sortedFriends = new ArrayList<>(friendsSet);

Collections.sort(sortedFriends);

for (String friend : sortedFriends)

System.out.println(friend);

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

ANS.

import java.util.*;

public class LinkedListExample

public static void main(String[] args)

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

list.add("Apple");

list.add("Banana");

list.add("Orange");

list.removeFirst();

System.out.println("Contents of the list in reverse order:");

Iterator<String> iterator = list.descendingIterator();

while (iterator.hasNext())

System.out.println(iterator.next());

Q3. 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

ANS.
import java.util.*;

public class CitySTDCode

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

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

citySTDMap.put("New Delhi", "212");

citySTDMap.put("Mumbai", "213");

citySTDMap.put("Pune", "312");

while (true)

System.out.println("\n1. Add City\n2. Remove City\n3. Search City\n4.


Exit");

int choice = sc.nextInt();

sc.nextLine();

if (choice == 1)

System.out.print("Enter city name: ");

String city = sc.nextLine();

System.out.print("Enter STD code: ");

String code = sc.nextLine();

if (!citySTDMap.containsKey(city))

citySTDMap.put(city, code);

System.out.println("City added.");

else

{
System.out.println("City exists!");

else if (choice == 2)

System.out.print("Enter city to remove: ");

String city = sc.nextLine();

if (citySTDMap.remove(city) != null)

System.out.println("City removed.");

else

System.out.println("City not found.");

else if (choice == 3)

System.out.print("Enter city to search: ");

String city = sc.nextLine();

String code = citySTDMap.get(city);

if (code != null)

System.out.println("STD code for " + city + ": " + code);

else

System.out.println("City not found.");

}
}

else if (choice == 4)

break;

else

System.out.println("Invalid choice.");

sc.close();

Q4. Write a Java Program to create the hash table that will maintain
the mobile number and student name. Display the details of student
using Enumeration interface

ANS.

import java.util.*;

public class StudentMobileHashtable

public static void main(String[] args)

Hashtable<String, String> studentTable = new Hashtable<>();

studentTable.put("9876543210", "Yash");

studentTable.put("9123456789", "Raj");

studentTable.put("9988776655", "Abhi");

studentTable.put("9345678901", "Gaurav");

Enumeration<String> mobileNumbers = studentTable.keys();

Enumeration<String> students = studentTable.elements();


while (mobileNumbers.hasMoreElements())

System.out.println("Mobile Number: " + mobileNumbers.nextElement() + " |


Student Name: " + students.nextElement());

Q5. Write a java program to create a TreeSet, add some colors (String)
and print out the content of TreeSet in ascending order

ANS.

import java.util.*;

public class TreeSetExample

public static void main(String[] args)

TreeSet<String> colors = new TreeSet<>();

colors.add("Blue");

colors.add("Red");

colors.add("Green");

colors.add("Yellow");

colors.add("Purple");

colors.add("Orange");

System.out.println("Colors in ascending order:");

for (String color : colors)

System.out.println(color);

}
PRACTICAL ASSIGNMENT-2 JAVA-II

Q.1. Write a Java program to display all the alphabets between ‘A’ to ‘Z’
after Every 2 seconds.

ANS.

import java.lang.*;

class Alphabet

public static void main(String[] args)

for (char letter = 'A'; letter <= 'Z'; letter++)

System.out.println(letter);

try

Thread.sleep(200);

catch (InterruptedException e)

System.out.println("Thread interrupted");

Q.2. Write a java program to simulate traffic signal using threads.

ANS.

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TrafficLight extends JPanel implements ActionListener

private Color[] colors = {Color.RED, Color.YELLOW, Color.GREEN};

private int currentLight = 0;

private Timer timer;

public TrafficLight()

timer = new Timer(1000, this);

timer.start();

protected void paintComponent(Graphics g)

super.paintComponent(g);

g.setColor(Color.BLACK);

g.fillRect(50, 30, 100, 250);

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

g.setColor(i == currentLight ? colors[i] : Color.GRAY);

g.fillOval(75, 50 + (i * 70), 50, 50);

public void actionPerformed(ActionEvent e)

currentLight = (currentLight + 1) % 3;

repaint();

public static void main(String[] args)

{
JFrame frame = new JFrame("Traffic Light");

frame.add(new TrafficLight());

frame.setSize(200, 350);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

Q.3. 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, the third
thread computes the of cube of that Number and print it.

ANS.

import java.util.Random;

import java.lang.*;

public class MultiThreadApp

public static void main(String[] args)

Random rand = new Random();

Thread t1 = new Thread(() ->

while (true)

int num = rand.nextInt(100) + 1;

System.out.println("Generated Number: " + num);

if (num % 2 == 0)

new Thread(() -> computeSquare(num)).start();


}

else

new Thread(() -> computeCube(num)).start();

try

Thread.sleep(1000);

catch (InterruptedException e)

Thread.currentThread().interrupt();

});

t1.start();

private static void computeSquare(int num)

int square = num * num;

System.out.println("Square: " + square);

private static void computeCube(int num)

int cube = num * num * num;

System.out.println("Cube: " + cube);

}
Q.4. 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.

ANS.

class MyThread extends Thread

private String text;

private int times;

public MyThread(String text, int times)

this.text = text;

this.times = times;

@Override

public void run()

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

System.out.println(text);

public class ThreadExample

public static void main(String[] args)

{
MyThread thread1 = new MyThread("COVID19", 10);

MyThread thread2 = new MyThread("LOCKDOWN2020", 20);

MyThread thread3 = new MyThread("VACCINATED2021", 30);

thread1.start();

thread2.start();

thread3.start();

5. Write a java program to display name and priority of a Thread.

ANS.

import java.lang.*;

class ThreadInfo

public static void main(String[] args)

Thread t = new Thread()

public void run()

System.out.println("Thread Name: " + Thread.currentThread().getName());

System.out.println("Thread Priority: " + Thread.currentThread().getPriority());

};

t.setName("yash");

t.setPriority(7);

t.start();

}
Q.6. 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).

ANS.

import java.lang.*;

class Mythread

public static void main(String args[])

Thread t=Thread.currentThread();

System.out.println("Current thread is "+t);

t.setName("Demo Thread");

System.out.println("After changing name thread is"+t);

try

for(int n=100; n>0;n--)

System.out.println(n);

Thread.sleep(500);

catch(InterruptedException e)

System.out.println("Thread interrupted");

}
PRACTICAL ASSIGNMENT-3 JAVA-II

Q.1.Write a Java program to accept the details of Employee (Eno,


EName, Designation, Salary) from a user and store it into the database.
(Use Swing).

ANS.

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.sql.*;

public class EmployeeForm extends JFrame

JTextField eidField = new JTextField(), enameField = new JTextField(),


designationField = new JTextField(), salaryField = new JTextField();

JButton saveButton = new JButton("Save");

public EmployeeForm()

setTitle("Employee Form");

setSize(300, 200);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new GridLayout(5, 2));

add(new JLabel("Emp ID:"));

add(eidField);

add(new JLabel("Name:"));

add(enameField);

add(new JLabel("Designation:"));

add(designationField);

add(new JLabel("Salary:"));

add(salaryField);

add(saveButton);

saveButton.addActionListener(e -> saveEmployee());


}

private void saveEmployee()

try (Connection conn =


DriverManager.getConnection("jdbc:postgresql:empdb","postgres","password"
);

PreparedStatement stmt = conn.prepareStatement("INSERT INTO employee


(eid, ename, designation, salary) VALUES (?, ?, ?, ?)"))

stmt.setInt(1, Integer.parseInt(eidField.getText()));

stmt.setString(2, enameField.getText());

stmt.setString(3, designationField.getText());

stmt.setDouble(4, Double.parseDouble(salaryField.getText()));

stmt.executeUpdate();

JOptionPane.showMessageDialog(this, "Employee saved!");

catch (Exception ex)

JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());

public static void main(String[] args)

SwingUtilities.invokeLater(() -> new EmployeeForm().setVisible(true));

Q.2.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.


ANS.

import java.sql.*;

import java.util.Scanner;

public class ProductDatabase

public static void main(String[] args)

String createTableQuery = "CREATE TABLE IF NOT EXISTS Product (" + "Pid


INT PRIMARY KEY, " + "Pname VARCHAR(100), " + "Price DECIMAL(10, 2))";

String insertQuery = "INSERT INTO Product (Pid, Pname, Price) VALUES (?,
?, ?)";

String selectQuery = "SELECT * FROM Product";

try (Connection conn =


DriverManager.getConnection("jdbc:postgresql:empdb","postgres","password"
);

Statement stmt = conn.createStatement();

Scanner scanner = new Scanner(System.in))

stmt.executeUpdate(createTableQuery);

System.out.println("Product table created successfully.");

PreparedStatement pstmt = conn.prepareStatement(insertQuery);

while (true)

System.out.print("Enter Product ID (or 0 to stop): ");

int pid = scanner.nextInt();

if (pid == 0) break;

scanner.nextLine();

System.out.print("Enter Product Name: ");

String pname = scanner.nextLine();

System.out.print("Enter Product Price: ");


double price = scanner.nextDouble();

pstmt.setInt(1, pid);

pstmt.setString(2, pname);

pstmt.setBigDecimal(3, new java.math.BigDecimal(price));

pstmt.executeUpdate();

System.out.println("Product inserted successfully.");

ResultSet rs = stmt.executeQuery(selectQuery);

System.out.println("Displaying all products:");

while (rs.next()) {

System.out.println("Pid: " + rs.getInt("Pid") + ", Pname: " +


rs.getString("Pname") + ", Price: " + rs.getDouble("Price"));

catch (SQLException e)

e.printStackTrace();

OR

import java.sql.*;

public class ProductDatabase

public static void main(String[] args)

String createTableQuery = "CREATE TABLE IF NOT EXISTS Product (" + "Pid


INT PRIMARY KEY, " + "Pname VARCHAR(100), " + "Price DECIMAL(10, 2))";

String insertQuery = "INSERT INTO Product (Pid, Pname, Price) VALUES (?,
?, ?)";
String selectQuery = "SELECT * FROM Product";

try (Connection conn =


DriverManager.getConnection("jdbc:postgresql:empdb","postgres","password"
);

Statement stmt = conn.createStatement())

stmt.executeUpdate(createTableQuery);

System.out.println("Product table created successfully.");

try (PreparedStatement pstmt = conn.prepareStatement(insertQuery))

pstmt.setInt(1, 1);

pstmt.setString(2, "Laptop");

pstmt.setBigDecimal(3, new java.math.BigDecimal(65000));

pstmt.executeUpdate();

pstmt.setInt(1, 2);

pstmt.setString(2, "Smartphone");

pstmt.setBigDecimal(3, new java.math.BigDecimal(50000));

pstmt.executeUpdate();

pstmt.setInt(1, 3);

pstmt.setString(2, "Tablet");

pstmt.setBigDecimal(3, new java.math.BigDecimal(95000));

pstmt.executeUpdate();

pstmt.setInt(1, 4);

pstmt.setString(2, "Headphones");

pstmt.setBigDecimal(3, new java.math.BigDecimal(5000));

pstmt.executeUpdate();

pstmt.setInt(1, 5);

pstmt.setString(2, "Monitor");

pstmt.setBigDecimal(3, new java.math.BigDecimal(20000));


pstmt.executeUpdate();

System.out.println("Records inserted successfully.");

try (ResultSet rs = stmt.executeQuery(selectQuery))

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

while (rs.next()) {

int pid = rs.getInt("Pid");

String pname = rs.getString("Pname");

double price = rs.getDouble("Price");

System.out.println("Pid: " + pid + ", Pname: " + pname + ", Price: " + price);

catch (SQLException e)

e.printStackTrace();

Q.3. write a java program to display information about all columns in


the DONAR table usng ResultSetMetaData.

ANS.

import java.sql.*;

public class DonarTableMetadata

public static void main(String[] args)

String selectQuery = "SELECT * FROM DONAR";


try (Connection conn =
DriverManager.getConnection("jdbc:postgresql:empdb","postgres","password"
);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(selectQuery))

ResultSetMetaData metaData = rs.getMetaData();

int columnCount = metaData.getColumnCount();

System.out.println("Information about columns in the DONAR table:");

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

String columnName = metaData.getColumnName(i);

String columnType = metaData.getColumnTypeName(i);

int columnSize = metaData.getColumnDisplaySize(i);

System.out.println("Column " + i + ":");

System.out.println(" Name: " + columnName);

System.out.println(" Type: " + columnType);

System.out.println(" Size: " + columnSize);

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

catch (SQLException e)

e.printStackTrace();

Q.4. Write a java program to display information about the database


and list all the tables in the database. (use DatabaseMetaData).

ANS.
import java.sql.*;

public class DatabaseInfo

public static void main(String[] args)

try (Connection conn =


DriverManager.getConnection("jdbc:postgresql:empdb","postgres","password"
);

DatabaseMetaData metaData = conn.getMetaData();

System.out.println("Database Product Name: " +


metaData.getDatabaseProductName());

System.out.println("Database Product Version: " +


metaData.getDatabaseProductVersion());

System.out.println("Driver Name: " + metaData.getDriverName());

System.out.println("Driver Version: " + metaData.getDriverVersion());

System.out.println("URL: " + metaData.getURL());

System.out.println("User: " + metaData.getUserName());

System.out.println("\nList of Tables in the Database:");

ResultSet tables = metaData.getTables(null, null, "%", new


String[]{"TABLE"});

while (tables.next())

System.out.println(tables.getString("TABLE_NAME"));

catch (SQLException e)

e.printStackTrace();

}
}

Q.5. Write a java program to accept the details of Teacher(TNo, TName,


Subject), Insert at least 5 Records into Teacher Table and display the
details of Teacher who is teaching "JAVA" Subject. (Use
PreparedStatement Interface)

ANS,

import java.sql.*;

public class TeacherDetails

public static void main(String[] args)

String insertQuery = "INSERT INTO Teacher (TNo, TName, Subject) VALUES


(?, ?, ?)";

String selectQuery = "SELECT * FROM Teacher WHERE Subject = ?";

try (Connection connection =


DriverManager.getConnection("jdbc:postgresql:empdb","postgres","password"
);

try (PreparedStatement insertStmt =


connection.prepareStatement(insertQuery))

insertStmt.setInt(1, 1);

insertStmt.setString(2, "Mahadik Madam");

insertStmt.setString(3, "JAVA");

insertStmt.executeUpdate();

insertStmt.setInt(1, 2);

insertStmt.setString(2, "Wanave Madam");

insertStmt.setString(3, "Python");

insertStmt.executeUpdate();

insertStmt.setInt(1, 3);

insertStmt.setString(2, "Bhong Madam");


insertStmt.setString(3, "OS");

insertStmt.executeUpdate();

insertStmt.setInt(1, 4);

insertStmt.setString(2, "Shaikh Sir");

insertStmt.setString(3, "DA");

insertStmt.executeUpdate();

insertStmt.setInt(1, 5);

insertStmt.setString(2, "Tamboli Sir");

insertStmt.setString(3, "STT");

insertStmt.executeUpdate();

try (PreparedStatement selectStmt =


connection.prepareStatement(selectQuery))

selectStmt.setString(1, "JAVA");

ResultSet resultSet = selectStmt.executeQuery();

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

while (resultSet.next()) {

int tNo = resultSet.getInt("TNo");

String tName = resultSet.getString("TName");

String subject = resultSet.getString("Subject");

System.out.println("TNo: " + tNo + ", TName: " + tName + ", Subject: " +
subject);

}catch (SQLException e)

e.printStackTrace();

}
}

OR

import java.sql.*;

import java.util.Scanner;

public class TeacherDetails

public static void main(String[] args){

String insertQuery = "INSERT INTO Teacher (TNo, TName, Subject) VALUES


(?, ?, ?)";

String selectQuery = "SELECT * FROM Teacher WHERE Subject = ?";

Scanner scanner = new Scanner(System.in);

try (Connection connection =


DriverManager.getConnection("jdbc:postgresql:empdb","postgres","password"
);

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

System.out.println("Enter details for Teacher " + (i + 1) + ":");

System.out.print("Enter Teacher No (TNo): ");

String tNo = scanner.nextLine

System.out.print("Enter Teacher Name (TName): ");

String tName = scanner.nextLine();

System.out.print("Enter Subject: ");

String subject = scanner.nextLine();

try (PreparedStatement insertStmt =


connection.prepareStatement(insertQuery))

insertStmt.setString(1, tNo);

insertStmt.setString(2, tName);
insertStmt.setString(3, subject);

insertStmt.executeUpdate();

System.out.println("Teacher details inserted successfully!\n");

try (PreparedStatement selectStmt =


connection.prepareStatement(selectQuery))

selectStmt.setString(1, "JAVA");

ResultSet resultSet = selectStmt.executeQuery();

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

while (resultSet.next())

String tNo = resultSet.getString("TNo");

String tName = resultSet.getString("TName");

String subject = resultSet.getString("Subject");

System.out.println("TNo: " + tNo + ", TName: " + tName + ", Subject: " +
subject);

catch (SQLException e)

{e.printStackTrace();

finally

{scanner.close();

You might also like