Program
function[]=gf(a,b,n,f)
for i=1:n
c=(a*f(b)-b*f(a))/(f(b)-f(a))
if(f(a)*f(c)<0) then b=c
elseif(f(c)*f(b)<0)then a=c
if((a-b)^2<0.0000001) then break
end
end
end
printf('root by regula falsi method=%f',c)
endfunction
Output:
-->deff('y=f(x)','y=x^3-2*3-5')
-->gf(2,3,45,f)
root by regula falsi method=2.223980
16 Comments
slip1
ReplyDeleteq1
public class Q1 extends Thread
{
char c;
public void run()
{
for(c = 'A'; c<='Z';c++)
{
System.out.println(""+c);
try
{
Thread.sleep(3000);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public static void main(String args[])
{
Q1 t = new Q1();
t.start();
}
}
//2. Write a Java program to accept the details of Employee (Eno, EName, Designation,Salary) from a user and store it into the database.
import java.sql.*;
import java.util.*;
public class Q2
{
public static void main(String args[])
{
Connection con = null;
Statement st = null;
ResultSet rs = null;
PreparedStatement ps = null;
Scanner sc = new Scanner(System.in);
try
{
// Load PostgreSQL driver
Class.forName("org.postgresql.Driver");
System.out.println("Driver Loaded Successfully");
// Connect to the database
con = DriverManager.getConnection("jdbc:postgresql:amresh", "postgres", "8624807723");
if (con == null)
System.out.println("Connection failed");
else
System.out.println("Connection Established successfully");
// Create table if it doesn't exist
st = con.createStatement();
st.executeUpdate("CREATE TABLE IF NOT EXISTS employee (Eno INT PRIMARY KEY, EName TEXT, Designation TEXT, Salary DOUBLE PRECISION)");
System.out.println("Created table 'employee' (if not exists)");
// Accept employee details from user
System.out.print("Enter Employee Number (Eno): ");
int eno = sc.nextInt();
sc.nextLine(); // Consume leftover newline
System.out.print("Enter Employee Name (EName): ");
String ename = sc.nextLine();
System.out.print("Enter Employee Designation: ");
String designation = sc.nextLine();
System.out.print("Enter Employee Salary: ");
double salary = sc.nextDouble();
// Insert data into employee table
ps = con.prepareStatement("INSERT INTO employee VALUES(?, ?, ?, ?)");
ps.setInt(1, eno);
ps.setString(2, ename);
ps.setString(3, designation);
ps.setDouble(4, salary);
ps.executeUpdate();
System.out.println("Employee details inserted successfully!");
// Display all employee records
rs = st.executeQuery("SELECT * FROM employee");
System.out.println("\nEno\tEName\t\tDesignation\tSalary");
System.out.println("--------------------------------------------------");
while (rs.next())
{
System.out.println(
rs.getInt("Eno") + "\t" +
rs.getString("EName") + "\t\t" +
rs.getString("Designation") + "\t" +
rs.getDouble("Salary"));
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
// Close all resources
try
{
if (rs != null) rs.close();
if (st != null) st.close();
if (ps != null) ps.close();
if (con != null) con.close();
sc.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
SLIP 2
ReplyDeleteimport java.util.*;
public class Q1
{
public static void main(String args[])
{
HashSet set = new HashSet();
set.add("geeks");
set.add("practice");
set.add("contribute");
set.add("ide");
System.out.println("Original HashSet:"+set);
List list = new ArrayList(set);
Collections.sort(list);
System.out.println("HashSet elements "+"in sorted order"+"using List:"+list);
}
}
-****************Slip 3**************
ReplyDelete/*2. Write a Java program to create LinkedList of String objects and perform the following:
i. Add element at the end of the list
ii. Delete first element of the list
iii. Display the contents of list in reverse order */
import java.util.*;
public class Q2
{
public static void main(String[] args)
{
LinkedList list = new LinkedList<>();
// i. Add elements at the end of the list
list.add("Apple");
list.add("Banana");
list.add("Cherry");
list.add("Date");
System.out.println("Original LinkedList: " + list);
// ii. Delete the first element of the list
if (!list.isEmpty())
{
list.removeFirst();
System.out.println("After deleting first element: " + list);
}
else
{
System.out.println("The list is empty.");
}
// iii. Display the contents of the list in reverse order
System.out.print("List in reverse order: ");
ListIterator iterator = list.listIterator(list.size());
while (iterator.hasPrevious())
{
System.out.print(iterator.previous() + " ");
}
}
}
//******************Slip 4******************* */
ReplyDelete// 1. Java program using Runnable interface to blink Text on the frame
import java.awt.*;
class Q1 extends Frame implements Runnable {
Thread t;
Label l1;
boolean visible;
Q1() {
t = new Thread(this);
t.start();
setLayout(null);
l1 = new Label("Hello JAVA");
l1.setBounds(100, 100, 100, 40);
add(l1);
setSize(300, 300);
setVisible(true);
visible = true;
}
public void run() {
try {
while (true) {
if (visible) {
l1.setText("");
} else {
l1.setText("Hello Amresh");
}
visible = !visible;
Thread.sleep(500);
}
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
public static void main(String[] args) {
new Q1();
}
}
/ 2. Java program to store city names and their STD codes
ReplyDeleteimport java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
class Q2 extends JFrame implements ActionListener {
JTextField t1, t2, t3;
JButton b1, b2, b3;
JTextArea t;
JPanel p1, p2;
HashMap cityCodes;
Q2() {
cityCodes = new HashMap<>();
t1 = new JTextField(10);
t2 = new JTextField(10);
t3 = new JTextField(10);
b1 = new JButton("Add");
b2 = new JButton("Search");
b3 = new JButton("Remove");
t = new JTextArea(20, 20);
p1 = new JPanel();
p1.add(t);
p2 = new JPanel();
p2.setLayout(new GridLayout(2, 3));
p2.add(new JLabel("City Name:"));
p2.add(t1);
p2.add(new JLabel("STD Code:"));
p2.add(t2);
p2.add(b1);
p2.add(new JLabel("City (Search/Remove):"));
p2.add(t3);
p2.add(b2);
p2.add(b3);
add(p1, BorderLayout.NORTH);
add(p2, BorderLayout.SOUTH);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
setLayout(new FlowLayout());
setSize(500, 500);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
String city = t1.getText();
try {
int code = Integer.parseInt(t2.getText());
if (!cityCodes.containsKey(city)) {
cityCodes.put(city, code);
displayCities();
t1.setText("");
t2.setText("");
} else {
JOptionPane.showMessageDialog(null, "City already exists!");
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Please enter a valid number for STD code!");
}
} else if (e.getSource() == b2) {
String city = t3.getText();
if (cityCodes.containsKey(city)) {
t.setText("City: " + city + "\nSTD Code: " + cityCodes.get(city));
} else {
JOptionPane.showMessageDialog(null, "City not found...");
}
} else if (e.getSource() == b3) {
String city = t3.getText();
if (cityCodes.containsKey(city)) {
cityCodes.remove(city);
JOptionPane.showMessageDialog(null, "City Deleted...");
displayCities();
} else {
JOptionPane.showMessageDialog(null, "City not found...");
}
}
}
private void displayCities() {
StringBuilder msg = new StringBuilder("City Name = STD Code\n");
for (Map.Entry entry : cityCodes.entrySet()) {
msg.append(entry.getKey()).append(" = ").append(entry.getValue()).append("\n");
}
t.setText(msg.toString());
}
public static void main(String[] args) {
new Q2();
}
}
// ************ Slip 5 *******
ReplyDelete/* 1. 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. */
import java.util.*;
public class Q1
{
public static void main(String[] args)
{
// Create a Hashtable to store student names and mobile numbers
Hashtable studentData = new Hashtable<>();
// Adding student data
studentData.put("Amresh", "9876543210");
studentData.put("Mitesh", "9823456789");
studentData.put("Shubham", "9765432101");
// Displaying student details using Enumeration
System.out.println("Student Details (Name : Mobile Number):");
Enumeration studentNames = studentData.keys();
while (studentNames.hasMoreElements())
{
String name = studentNames.nextElement();
System.out.println(name + " : " + studentData.get(name));
}
// Searching for a student
Scanner sc = new Scanner(System.in);
System.out.print("\nEnter student name to search: ");
String searchName = sc.nextLine();
if (studentData.containsKey(searchName))
{
System.out.println("Mobile number of " + searchName + " : " + studentData.get(searchName));
}
else
{
System.out.println("Student not found.");
}
// Closing scanner
sc.close();
}
}
/* *********** Slip 6 ********** */
ReplyDelete/*1. Write a Java program to accept ‘n’ integers from the user and store them in a collection.
Display them in the sorted order. The collection should not accept duplicate elements.
(Use a suitable collection). Search for a particular element using predefined search
method in the Collection framework. */
import java.io.*;
import java.util.*;
class Q1 {
public static void main(String[] args) throws IOException {
int no, element;
// Setup BufferedReader for input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Use TreeSet to store elements in sorted order without duplicates
TreeSet ts = new TreeSet<>();
// Accept number of elements
System.out.print("Enter the number of elements: ");
no = Integer.parseInt(br.readLine());
// Input 'n' elements
for (int i = 0; i < no; i++) {
System.out.print("Enter element " + (i + 1) + ": ");
element = Integer.parseInt(br.readLine());
if (ts.add(element)) {
System.out.println("Element added.");
} else {
System.out.println("Duplicate element! Skipping...");
}
}
// Display elements in sorted order
System.out.println("\nThe elements in sorted order: " + ts);
// Accept an element to search
System.out.print("\nEnter element to search: ");
element = Integer.parseInt(br.readLine());
// Search the element in the TreeSet
if (ts.contains(element))
System.out.println("Element found!");
else
System.out.println("Element NOT found!");
}
}
/* 2. Write a java program to simulate traffic signal using threads */
import java.applet.*;
import java.awt.*;
// Extend Applet and implement Runnable for threading
public class Q2 extends Applet implements Runnable {
Thread t;
int red, yellow, green;
// Initialize the applet and thread
public void init() {
t = new Thread(this);
t.start();
red = 1; yellow = 0; green = 0;
}
// Thread's run method to control signal changes
public void run() {
try {
while (true) {
// Red light for 5 seconds
red = 1; yellow = 0; green = 0;
repaint();
Thread.sleep(5000);
// Green light for 5 seconds
red = 0; yellow = 0; green = 1;
repaint();
Thread.sleep(5000);
// Yellow light for 2 seconds (transition)
red = 0; yellow = 1; green = 0;
repaint();
Thread.sleep(2000);
}
} catch (Exception e) {
System.out.println(e);
}
}
// Paint method to draw the signal
public void paint(Graphics g) {
g.drawRect(100, 100, 100, 300);
// Red light
if (red == 1) {
g.setColor(Color.red);
g.fillOval(100, 100, 100, 100);
} else {
g.setColor(Color.black);
g.drawOval(100, 100, 100, 100);
}
// Yellow light
if (yellow == 1) {
g.setColor(Color.yellow);
g.fillOval(100, 200, 100, 100);
} else {
g.setColor(Color.black);
g.drawOval(100, 200, 100, 100);
}
// Green light
if (green == 1) {
g.setColor(Color.green);
g.fillOval(100, 300, 100, 100);
} else {
g.setColor(Color.black);
g.drawOval(100, 300, 100, 100);
}
}
}
/* ********* Slip 7 ******** */
ReplyDelete// 1. Java program to implement a multi-thread application with three threads
import java.util.Random;
class Square extends Thread {
int x;
Square(int n) { x = n; }
public void run() {
int sqr = x * x;
System.out.println("Square of " + x + " = " + sqr);
}
}
class Cube extends Thread {
int x;
Cube(int n) { x = n; }
public void run() {
int cub = x * x * x;
System.out.println("Cube of " + x + " = " + cub);
}
}
class Number extends Thread {
public void run() {
Random random = new Random();
for (int i = 0; i < 5; i++) {
int randomInteger = random.nextInt(100);
System.out.println("\nRandom Integer generated: " + randomInteger);
if (randomInteger % 2 == 0) {
Square s = new Square(randomInteger);
s.start();
} else {
Cube c = new Cube(randomInteger);
c.start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}
public class Q1 {
public static void main(String args[]) {
Number n = new Number();
n.start();
}
}
/* 2. Java program to create a Product table, insert records, and display them */
import java.sql.*;
public class Q2 {
public static void main(String[] args) {
String url = "jdbc:oracle:thin:@localhost:1521:amresh";
String user = "oracle";
String password = "8624807723";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(url, user, password);
Statement stmt = con.createStatement();
String createTableQuery = "CREATE TABLE Product (Pid INT PRIMARY KEY, Pname VARCHAR(50), Price DECIMAL(10, 2))";
try {
stmt.executeUpdate(createTableQuery);
System.out.println("Table 'Product' created successfully.");
} catch (SQLException e) {
System.out.println("Table already exists.");
}
String[] products = {
"INSERT INTO Product VALUES (1, 'Laptop', 50000.00)",
"INSERT INTO Product VALUES (2, 'Smartphone', 25000.00)",
"INSERT INTO Product VALUES (3, 'Tablet', 15000.00)",
"INSERT INTO Product VALUES (4, 'Smartwatch', 7000.00)",
"INSERT INTO Product VALUES (5, 'Headphones', 2000.00)"
};
for (String query : products) {
stmt.executeUpdate(query);
}
System.out.println("5 records inserted successfully.");
ResultSet rs = stmt.executeQuery("SELECT * FROM Product");
System.out.println("\nProduct Records:");
System.out.printf("%-5s %-15s %-10s%n", "ID", "Name", "Price");
System.out.println("----------------------------------");
while (rs.next()) {
int id = rs.getInt("Pid");
String name = rs.getString("Pname");
double price = rs.getDouble("Price");
System.out.printf("%-5d %-15s %-10.2f%n", id, name, price);
}
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
/* ******* Slip 8 ******* */
ReplyDelete/* 1. 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 */
import java.io.*;
import java.util.*;
public class Q1 extends Thread
{
int n;
String msg;
tdemo2(int n,String msg)
{
this.n=n;
this.msg=msg;
}public void run()
{
try
{
for (int i=1;i<=n;i++)
{
System.out.println(msg);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String Args[])
{
Thread t1=new Thread(new tdemo2(10,"COVID19"));
t1.start();
Thread t2=new Thread(new tdemo2(20,"LOCKDOWN2020"));
t2.start();
Thread t3=new Thread(new tdemo2(30,"VACCINATED2021"));
t3.start();
}
}
/* ****************** Slip 9 ****************** */
ReplyDelete/* 1. Write a Java program to create a thread for moving a ball inside a panel vertically. The
ball should be created when the user clicks on the start button */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Q1 extends JFrame {
private BallPanel ballPanel;
private JButton startButton;
private BallThread ballThread;
public BallMovement() {
setTitle("Ball Movement");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// Create custom panel that supports ball drawing
ballPanel = new BallPanel();
startButton = new JButton("Start");
// Add action listener to start the ball on button click
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
startBall();
}
});
// Set layout and add components
ballPanel.setLayout(null);
ballPanel.add(startButton);
startButton.setBounds(150, 10, 100, 30);
getContentPane().add(ballPanel);
}
private void startBall() {
// Start the ball animation if not already running
if (ballThread == null || !ballThread.isAlive()) {
ballThread = new BallThread(ballPanel);
ballThread.start();
}
}
public static void main(String[] args) {
// Launch the application on the event dispatch thread
SwingUtilities.invokeLater(() -> new BallMovement().setVisible(true));
}
}
// Custom JPanel that handles ball movement and repainting
class BallPanel extends JPanel {
private static final int DIAMETER = 20;
private int y = 50;
private int ySpeed = 2;
public void moveBall() {
// Bounce logic
if (y + DIAMETER >= getHeight() || y <= 0) {
ySpeed = -ySpeed;
}
y += ySpeed;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw the ball
g.setColor(Color.BLUE);
g.fillOval(150, y, DIAMETER, DIAMETER);
}
}
// Thread that keeps the ball moving
class BallThread extends Thread {
private BallPanel ballPanel;
public BallThread(BallPanel ballPanel) {
this.ballPanel = ballPanel;
}
public void run() {
while (true) {
ballPanel.moveBall();
try {
Thread.sleep(10); // Control the speed of movement
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
SLIP 10
ReplyDelete/* 2. Write a Java program to display first record from student table (RNo, SName, Per) onto
the TextFields by clicking on button. (Assume Student table is already created). */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class Q2 extends JFrame implements ActionListener {
JTextField t1, t2, t3;
JLabel l1, l2, l3;
JButton b1, b2;
// Constructor
StudDb() {
setLayout(new FlowLayout());
setSize(400, 300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Labels and text fields
l1 = new JLabel("RollNo");
add(l1);
t1 = new JTextField(10);
add(t1);
l2 = new JLabel("Name");
add(l2);
t2 = new JTextField(10);
add(t2);
l3 = new JLabel("Percentage");
add(l3);
t3 = new JTextField(10);
add(t3);
// Buttons
b1 = new JButton("Insert");
add(b1);
b1.addActionListener(this);
b2 = new JButton("Display First Record");
add(b2);
b2.addActionListener(this);
// Load PostgreSQL Driver
try {
Class.forName("org.postgresql.Driver");
} catch (Exception e) {
System.out.println("Error loading driver: " + e.getMessage());
}
}
// Handle button events
public void actionPerformed(ActionEvent e2) {
if (e2.getSource() == b1) {
// Insert new student record
try (Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost/amresh", "postgres", "8624807723")) {
int rno = Integer.parseInt(t1.getText());
String sname = t2.getText();
float percentage = Float.parseFloat(t3.getText());
String query = "INSERT INTO student VALUES(?,?,?)";
PreparedStatement st = conn.prepareStatement(query);
st.setInt(1, rno);
st.setString(2, sname);
st.setFloat(3, percentage);
int rows = st.executeUpdate();
if (rows > 0) JOptionPane.showMessageDialog(this, "Record Inserted Successfully!");
st.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());
}
}
if (e2.getSource() == b2) {
// Fetch and display the first student record
try (Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost/amresh", "postgres", "8624807723")) {
String query = "SELECT * FROM student LIMIT 1";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
if (rs.next()) {
t1.setText(String.valueOf(rs.getInt("RNo")));
t2.setText(rs.getString("SName"));
t3.setText(String.valueOf(rs.getFloat("Per")));
JOptionPane.showMessageDialog(this, "First Record Loaded!");
} else {
JOptionPane.showMessageDialog(this, "No records found.");
}
rs.close();
st.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage());
}
}
}
// Main method
public static void main(String[] args) {
new Q2();
}
}
SLIP 11
ReplyDelete/* 2. Write a Java program to display information about all columns in the DONAR table
using ResultSetMetaData. */
import java.sql.*;
public class Q2{
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Load PostgreSQL driver
Class.forName("org.postgresql.Driver");
// Connect to the database
con = DriverManager.getConnection("jdbc:postgresql:amresh", "postgres", "8624807723");
// Create statement and execute query
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM DONAR");
// Get metadata from the result set
ResultSetMetaData rsmd = rs.getMetaData();
int noOfColumns = rsmd.getColumnCount();
// Display column count
System.out.println("Number of columns = " + noOfColumns);
// Display details for each column
for (int i = 1; i <= noOfColumns; i++) {
System.out.println("Column No : " + i);
System.out.println("Column Name : " + rsmd.getColumnName(i));
System.out.println("Column Type : " + rsmd.getColumnTypeName(i));
System.out.println("Column Display Size : " + rsmd.getColumnDisplaySize(i));
System.out.println("-----------------------------------------");
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
} finally {
// Close resources
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (con != null) con.close();
} catch (SQLException e) {
System.out.println("Error closing connection: " + e.getMessage());
}
}
}
}
SLIP 12
ReplyDelete/* 2. Write a Java Program to create a PROJECT table with field’s project_id, Project_name,
Project_description, Project_Status. Insert values in the table. Display all the details of
the PROJECT table in a tabular format on the screen.(using swing). */
import java.sql.*;
import java.util.*;
public class Q2
{
public static void main(String args[])
{
Connection con = null;
Statement st = null;
ResultSet rs = null;
PreparedStatement ps = null;
Scanner sc = new Scanner(System.in);
try {
Class.forName("org.postgresql.Driver");
System.out.println("Driver Loaded Successfully");
con = DriverManager.getConnection("jdbc:postgresql:amresh", "postgres", "8624807723");
if (con == null)
System.out.println("Connection failed");
else
System.out.println("Connection Established successfully");
st = con.createStatement();
st.executeUpdate("create table if not exists project_5(pid int primary key, pname text, pdesc text, pstatus text);");
System.out.println("Created table project_5 (if not exists)");
System.out.print("Enter Project ID: ");
int pid = sc.nextInt();
sc.nextLine(); // Consume newline
System.out.print("Enter Project Name: ");
String pname = sc.nextLine();
System.out.print("Enter Project Description: ");
String pdesc = sc.nextLine();
System.out.print("Enter Project Status: ");
String pstatus = sc.nextLine();
ps = con.prepareStatement("insert into project_5 values(?,?,?,?)");
ps.setInt(1, pid);
ps.setString(2, pname);
ps.setString(3, pdesc);
ps.setString(4, pstatus);
ps.executeUpdate();
System.out.println("Inserted successfully");
rs = st.executeQuery("select * from project_5");
System.out.println("pid \t pname \t pdesc \t pstatus ");
while (rs.next()) {
System.out.println(" " + rs.getInt(1) + "\t" + rs.getString(2) + "\t" + rs.getString(3) + "\t" + rs.getString(4));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (st != null) st.close();
if (ps != null) ps.close();
if (con != null) con.close();
sc.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
/* *********** Slip 13 ********* */
ReplyDelete/* 1. Write a Java program to display information about the database and list all the tables in
the database. (Use DatabaseMetaData). */
import java.sql.*;
public class Q1 {
public static void main(String[] args) {
Connection con = null;
try {
Class.forName("org.postgresql.Driver");
con=DriverManager.getConnection("jdbc:postgresql:amresh","postgres","8624807723");
DatabaseMetaData metaData = con.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("\nTables in the database:");
ResultSet tables = metaData.getTables(null, null, "%", new String[]{"TABLE"});
while (tables.next()) {
System.out.println(tables.getString("TABLE_NAME"));
}
tables.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/* 2. Write a Java program to show lifecycle (creation, sleep, and dead) of a thread. Program
should print randomly the name of thread and value of sleep time. The name of the
thread should be hard coded through constructor. The sleep time of a thread will be a
random integer in the range 0 to 4999 */
class MyThread extends Thread {
// Constructor to name the thread
public MyThread(String name) {
super(name);
}
// Define thread behavior in run()
public void run() {
System.out.println(getName() + " thread created.");
// Simulate thread lifecycle
while (true) {
try {
// Random sleep time between 0 to 4999 milliseconds
int sleepTime = (int) (Math.random() * 5000);
System.out.println(getName() + " is sleeping for: " + sleepTime + " msec");
// Put the thread to sleep
Thread.sleep(sleepTime);
// Simulate thread completion
System.out.println(getName() + " thread completed work.");
break;
} catch (InterruptedException e) {
System.out.println(getName() + " was interrupted.");
}
}
}
}
// Main class to test thread lifecycle
public class Q2 {
public static void main(String args[]) {
// Create two threads with hardcoded names
MyThread t1 = new MyThread("Shradha");
MyThread t2 = new MyThread("Pooja");
// Start both threads
t1.start();
t2.start();
try {
// Wait for both threads to complete
t1.join();
t2.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
// Threads have finished, print final message
System.out.println(t1.getName() + " thread dead.");
System.out.println(t2.getName() + " thread dead.");
}
}
/* ************** Slip 14 *************** */
ReplyDelete/* 1. Write a Java program for a simple search engine. Accept a string to be searched. Search
the string in all text files in the current folder. Use a separate thread for each file. The
result should display the filename and line number where the string is found. */
import java.io.*;
public class Q1 extends Thread {
private File file;
private String searchString;
// Constructor to initialize the file and search string
public SearchThread(File file, String searchString) {
this.file = file;
this.searchString = searchString;
}
// Thread's run() method — searches line by line
public void run() {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
int lineNumber = 0;
// Read each line and check for the search string
while ((line = reader.readLine()) != null) {
lineNumber++;
if (line.contains(searchString)) {
System.out.println("String found in " + file.getName() + " at line " + lineNumber);
}
}
} catch (IOException e) {
System.out.println("Error reading file: " + file.getName());
}
}
// Main method to start the search engine
public static void main(String[] args) {
try {
// Get user input for the search string
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string to search: ");
String searchString = br.readLine();
// Filter .txt files in the current directory
File dir = new File(".");
File[] files = dir.listFiles((dir1, name) -> name.endsWith(".txt"));
if (files == null || files.length == 0) {
System.out.println("No .txt files found in the current directory.");
return;
}
// Create and start a thread for each file
for (File file : files) {
SearchThread searchThread = new SearchThread(file, searchString);
searchThread.start();
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
/* *********** Slip 15 ************ */
ReplyDelete/* 1. Write a java program to display name and priority of a Thread. */
public class Q1
{
public static void main(String[] args) {
// Get the current thread
Thread t = Thread.currentThread();
// Display current thread info
System.out.println("Current Thread: " + t);
// Change the thread's name
t.setName("My Custom Thread");
// Set a higher priority
t.setPriority(Thread.MAX_PRIORITY);
// Display updated thread info
System.out.println("After name and priority change: " + t);
// Demonstrate the thread running with a countdown
try {
for (int i = 5; i > 0; i--) {
System.out.println("Countdown: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Thread interrupted: " + e.getMessage());
}
System.out.println("Thread execution complete.");
}
}