OneCompiler

ns13

116

Q1]

import java.sql.*;

public class DatabaseInfo {

static final String JDBC_URL = "jdbc:mysql://localhost:3306/your_database_name";
static final String USER = "your_username";
static final String PASSWORD = "your_password";

public static void main(String[] args) {
    try (Connection conn = DriverManager.getConnection(JDBC_URL, USER, 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());

  
        ResultSet rs = metaData.getTables(null, null, "%", new String[] { "TABLE" });
        System.out.println("\nTables in the database:");
        while (rs.next()) {
            String tableName = rs.getString("TABLE_NAME");
            System.out.println(tableName);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

}

Q2]

import java.util.Random;

public class ThreadLifecycleDemo extends Thread {
private String threadName;

public ThreadLifecycleDemo(String name) {
    this.threadName = name;
}

public void run() {
    System.out.println("Thread " + threadName + " is created.");
    Random random = new Random();

    try {
        int sleepTime = random.nextInt(5000); // Random sleep time between 0 to 4999 milliseconds
        System.out.println("Thread " + threadName + " will sleep for " + sleepTime + " milliseconds.");
        Thread.sleep(sleepTime);
    } catch (InterruptedException e) {
        System.out.println("Thread " + threadName + " is interrupted.");
    }

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

public static void main(String[] args) {
    ThreadLifecycleDemo thread1 = new ThreadLifecycleDemo("Thread1");
    ThreadLifecycleDemo thread2 = new ThreadLifecycleDemo("Thread2");

    thread1.start();
    thread2.start(); 
}

}