0% found this document useful (0 votes)
17 views2 pages

Untitled Document - Converted - 2

Uploaded by

sureshroopa2k15
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)
17 views2 pages

Untitled Document - Converted - 2

Uploaded by

sureshroopa2k15
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
You are on page 1/ 2

Write a JAVA program Illustrating Multiple catch clauses } // Main class to run the threads try

class MultipleCatchDemo } class ThreadDemo {


{ catch (InterruptedException e) { String str = null;
public static void main(String args[]) { public static void main(String args[ ]) System.out.println(str.length()); // This will throw a NullPointerException
{ System.out.println("GoodMorningThread interrupted."); { }
try } GoodMorningThread goodMorning = new GoodMorningThread(); catch (NullPointerException e)
{ } HelloThread hello = new HelloThread(); {
String str = null; } WelcomeThread welcome = new WelcomeThread(); System.out.println("Error: Null reference accessed.");
int[] numbers = new int[5]; class HelloThread extends Thread goodMorning.start(); }
System.out.println(str.length()); { hello.start(); try
numbers[10] = 100; public void run() welcome.start(); {
} { } String[] data = {"10", "20", null};
catch (NullPointerException e) try } for (int i = 0; i <= data.length; i++)
{ { Write a JAVA program for creation of Java Built-in Exceptions {
System.out.println("Error: Null reference accessed."); while (true) class BuiltInExceptionsDemo System.out.println(Integer.parseInt(data[i]));
} { { }
catch (ArrayIndexOutOfBoundsException e) System.out.println("Hello"); public static void main(String args[]) }
{ Thread.sleep(2000); // Sleep for 2 seconds { catch (ArrayIndexOutOfBoundsException e)
System.out.println("Error: Array index is out of bounds."); } try {
} } { System.out.println("Error: Array index is out of bounds.");
catch (Exception e) catch (InterruptedException e) int result = 10 / 0; // This will throw an ArithmeticException }
{ { } catch (NumberFormatException e)
System.out.println("Error: An unexpected exception occurred."); System.out.println("HelloThread interrupted."); catch (ArithmeticException e) {
} } { System.out.println("Error: Invalid number format.");
finally } System.out.println("Error: Division by zero is not allowed."); }
{ } } catch (NullPointerException e)
System.out.println("This block executes regardless of an exception"); class WelcomeThread extends Thread try {
} { { System.out.println("Error: Null reference accessed.");
System.out.println("Program continues after handling exceptions."); public void run() int[] numbers = new int[5]; }
} { numbers[10] = 100; // This will throw an ArrayIndexOutOfBoundsException System.out.println("Program continues after handling exceptions.");
} try } }
Write a JAVA program that creates threads by extending Thread class. First thread display { catch (ArrayIndexOutOfBoundsException e) }
“Good Morning “every 1 sec, the second thread displays “Hello “every 2 seconds and the third while (true) { Write a program illustrating is Alive and join ()
display “Welcome” every 3 seconds, (Repeat the same by implementing Runnable) { System.out.println("Error: Array index is out of bounds."); class MyThread extends Thread
class GoodMorningThread extends Thread System.out.println("Welcome"); } {
{ Thread.sleep(3000); // Sleep for 3 seconds try public void run()
public void run() } { {
{ } String str = "abc"; try
try catch (InterruptedException e) int number = Integer.parseInt(str); // This will throw a NumberFormatException {
{ { } System.out.println(Thread.currentThread().getName() + " is running.");
while (true) System.out.println("WelcomeThread interrupted."); catch (NumberFormatException e) Thread.sleep(2000); // Simulate work with sleep
{ } { System.out.println(Thread.currentThread().getName() + " has finished.");
System.out.println("Good Morning"); } System.out.println("Error: Invalid number format."); }
Thread.sleep(1000); // Sleep for 1 second } } catch (InterruptedException e)

{ { { Producer ()
System.out.println(Thread.currentThread().getName() + " interrupted."); if (age < 0 || age > 150) public void run() {
} { { sb = new StringBuffer();
} throw new AgeException("Invalid age: " + age + ". Age must be between 0 and try }
} 150."); { public void run ()
class ThreadManagementDemo } while (true) {
{ else { synchronized (sb)
public static void main(String args[ ]) { System.out.println("Daemon Thread 2 is running..."); {
{ System.out.println("Age is valid: " + age); Thread.sleep(1500); // Sleep for 1.5 seconds for (int i=1;i<=5;i++)
MyThread thread1 = new MyThread(); } } {
MyThread thread2 = new MyThread(); } } try
thread1.setName("Thread-1"); public static void main(String args[]) catch (InterruptedException e) {
thread2.setName("Thread-2"); { { sb.append (i + " : ");
System.out.println("Starting threads..."); try System.out.println("Daemon Thread 2 interrupted."); Thread.sleep (500);
thread1.start(); { } System.out.println (i + " appended");
thread2.start(); checkAge(25); // Valid age } }
// Check if threads are alive and use join checkAge(-5); // Invalid age, will throw AgeException } catch (InterruptedException ie){}
try } // Main class }
{ catch (AgeException e) class DaemonThreadExample sb.notify ();
System.out.println("Thread1 is alive: " + thread1.isAlive()); { { }
System.out.println("Thread2 is alive: " + thread2.isAlive()); System.out.println("Caught exception: " + e.getMessage()); public static void main(String args[ ]) }
thread1.join(); // Wait for thread1 to finish } { }
thread2.join(); // Wait for thread2 to finish } Thread daemonThread1 = new Thread(new DaemonTask1()); class Consumer implements Runnable
System.out.println("Both threads have completed."); } daemonThread1.setDaemon(true); // Set the thread as a daemon {
} Write a Program illustrating Daemon Threads. daemonThread1.start(); Producer prod;
catch (InterruptedException e) class DaemonTask1 implements Runnable Thread daemonThread2 = new Thread(new DaemonTask2()); Consumer (Producer prod)
{ { daemonThread2.setDaemon(true); // Set the thread as a daemon {
System.out.println("Main thread interrupted."); public void run() daemonThread2.start(); this.prod = prod;
} { // Main thread activity }
System.out.println("Main thread exiting."); try try public void run()
} { { {
} while (true) Thread.sleep(5000); // Main thread sleeps for 5 seconds synchronized (prod.sb)
Write a JAVA program for creation of User Defined Exception { } {
class AgeException extends Exception System.out.println("Daemon Thread 1 is running..."); catch (InterruptedException e) try
{ Thread.sleep(1000); // Sleep for 1 second { {
public AgeException(String message) } System.out.println("Main thread interrupted."); prod.sb.wait ();
{ } } }
super(message); catch (InterruptedException e) System.out.println("Main thread is about to finish."); catch (Exception e) { }
} { } System.out.println (prod.sb);
} System.out.println("Daemon Thread 1 interrupted."); } }
// Main class } Write a JAVA program Producer Consumer Problem }
class UserDefinedExceptionDemo } class Producer implements Runnable }
{ } { class Communicate
public static void checkAge(int age) throws AgeException class DaemonTask2 implements Runnable StringBuffer sb; {
public static void main(String args[]) import javafx.scene.control.Label; public static void main(String[] args) { ('Smartphone', 'Samsung Galaxy', 30000.00)";
{ import javafx.stage.Stage; String createTableSQL = "CREATE TABLE products (" + String insertSQL3 = "INSERT INTO products (name, description, price) VALUES
Producer obj1 = new Producer (); import javafx.scene.image.*; "id INT AUTO_INCREMENT PRIMARY KEY, " + ('Tablet', 'Apple iPad', 50000.00)";
Consumer obj2 = new Consumer (obj1); import java.io.*; "name VARCHAR(100), " + // Step 1: Establishing a Connection
Thread t1 = new Thread (obj1); public class JavaFX_LableImage extends Application { "description VARCHAR(255), " + try (Connection connection = DriverManager
Thread t2 = new Thread (obj2); // launch the application "price DECIMAL(10, 2)" + .getConnection(URL,USER,PASSWORD);
t2.start (); public void start(Stage s) throws Exception ")"; // Step 2:Create a statement using connection object
t1.start (); { // Step 1: Establishing a Connection Statement stmt = connection.createStatement();){
} // set title for the stage try (Connection connection = DriverManager // Step 3: Execute the query or update query
} s.setTitle("creating label"); .getConnection(URL,USER,PASSWORD); if (connection != null) {
Write a JAVA program that import and use the user defined packages // create a input stream // Step 2:Create a statement using connection object System.out.println("Connected to the Database!");
//creating a package FileInputStream input = new FileInputStream("E:\\ aits-tpt.jpg"); Statement stmt = connection.createStatement();){ }
package pack; // create a image // Step 3: Execute the query or update query //Step 3: Execute insert SQL statements
public class Addition Image i = new Image(input); if (connection != null) { stmt.executeUpdate(insertSQL1);
{ // create a image View System.out.println("Connected to the database!"); stmt.executeUpdate(insertSQL2);
private double d1,d2; ImageView iw = new ImageView(i); stmt.executeUpdate(createTableSQL); stmt.executeUpdate(insertSQL3);
public Addition(double a,double b) // create a label // Step 4: display the result. System.out.println("Records Inserted Successfully!");
{ Label b = new Label("AITS-TIRUPATI", iw); System.out.println("Table created successfully!"); } catch (SQLException e) {
d1 = a; // create a Stack pane } e.printStackTrace();
d2 = b; StackPane r = new StackPane(); } catch (SQLException e) { }
} // add password field e.printStackTrace(); // Step 4: try-with-resource statement will auto close the connection.
public void sum() r.getChildren().add(b); } }
{ // create a scene // Step 4: try-with-resource statement will auto close the connection. }
System.out.println ("Sum of two given numbers is : " + (d1+d2) ); Scene sc = new Scene(r, 500, 500); } Write a JAVA program for abstract class to find areas of different shapes
} // set the scene } // Abstract class
} s.setScene(sc); Write a java program to connect to a database using JDBC and insert values into it. abstract class Shape
//Using the package pack s.show(); JDBC_InsertMultipleRecords.java {
import pack.Addition; } Create a new class “JDBC_InsertMultipleRecords” and paste the below code. abstract double area();
class Use public static void main(String args[]) import java.sql.Connection; }
{ { import java.sql.DriverManager; // Subclass for Circle
public static void main(String args[]) // launch the application import java.sql.ResultSet; class Circle extends Shape
{ launch(args); import java.sql.SQLException; {
Addition ob1 = new Addition(10,20); } import java.sql.Statement; double radius;
ob1.sum(); } public class JDBC_InsertMultipleRecords { Circle(double radius)
} Write a java program that connects to a database using JDBC private static final String URL = "jdbc:mysql://localhost:3306/mysql_demo"; {
} import java.sql.SQLException; private static final String USER = "root"; this.radius = radius;
Without writing any code, build a GUI that display text in label and image in an ImageView import java.sql.Statement; private static final String PASSWORD = "root"; }
(use JavaFX) ( public class JDBC_ConnectAndCreateTable { public static Connection getConnection() throws SQLException { double area()
import javafx.application.Application; private static final String URL = "jdbc:mysql://localhost:3306/mysql_demo"; return DriverManager.getConnection(URL, USER, PASSWORD); {
import javafx.scene.Scene; private static final String USER = "root"; } return Math.PI * radius * radius; // Area of circle = π * r^2
import javafx.scene.control.*; private static final String PASSWORD = "root"; public static void main(String[] args) { }
import javafx.scene.layout.*; public static Connection getConnection() throws SQLException { String insertSQL1 = "INSERT INTO products (name, description, price) VALUES }
import javafx.event.ActionEvent; return DriverManager.getConnection(URL, USER, PASSWORD); ('Laptop', 'Dell Inspiron', 75000.00)"; // Subclass for Rectangle
import javafx.event.EventHandler; } String insertSQL2 = "INSERT INTO products (name, description, price) VALUES class Rectangle extends Shape

{ Statement stmt = connection.createStatement();){ }


double width, height; // Step 3: Execute the query or update query public void show()
Rectangle(double width, double height) if (connection != null) { {
{ System.out.println("Connected to the Database!"); System.out.println("method of class Base3");
this.width = width; } }
this.height = height; //Step 3: Execute insert SQL statements }
} int rowsDeleted = stmt.executeUpdate(deleteSQL); Derive.java
double area() System.out.println(rowsDeleted + " row(s) deleted!"); public class Derive
{ } catch (SQLException e) { {
return width * height; // Area of rectangle = width * height e.printStackTrace(); public static void main (String args [])
} } {
} // Step 4: try-with-resource statement will auto close the connection. Base1 obj1 = new Base1();
// Main class to run the program } Base1 obj2 = new Base2();
class AbstractClassDemo } Base2 obj3 = new Base3();
{ POLYMORPHISM obj1.show();
public static void main(String args[]) class Base1 obj2.show();
{ { obj3.show();
Shape circle = new Circle(5.0); Base1() }
Shape rectangle = new Rectangle(4.0, 6.0); { }
System.out.println("Area of the circle: " + circle.area()); System.out.println("Constructor of Base1 ");
System.out.println("Area of the rectangle: " + rectangle.area()); }
} public void show()
} {
Write a java program to connect to a database using JDBC and delete values from it. ( System.out.println ("method of class Base1");
DeleteRecords.java }
Create a new class “JDBC_DeleteRecords” and paste the below code. }
import java.sql.Connection; Base2.java
import java.sql.DriverManager; class Base2 extends Base1
import java.sql.ResultSet; {
import java.sql.SQLException; Base2()
import java.sql.Statement; {
public class JDBC_DeleteRecords { System.out.println("Constructor of Base2");
private static final String URL = "jdbc:mysql://localhost:3306/mysql_demo"; }
private static final String USER = "root"; public void show()
private static final String PASSWORD = "root"; {
public static Connection getConnection() throws SQLException { System.out.println ("method of class Base2");
return DriverManager.getConnection(URL, USER, PASSWORD); }
} }
public static void main(String[] args) { Base3.java
String deleteSQL = "DELETE FROM products WHERE name = 'Laptop'"; class Base3 extends Base2
// Step 1: Establishing a Connection {
try (Connection connection = DriverManager Base3()
.getConnection(URL,USER,PASSWORD); {
// Step 2:Create a statement using connection object System.out.println("Constructor of Base3");

You might also like