0% found this document useful (0 votes)
5 views21 pages

Java Multi-threading and Exception Handling Examples

The document outlines multiple Java programming tasks, including simulating a banking system with thread synchronization, printing numbers and letters concurrently, and demonstrating object serialization. It also includes programs for file copying, exception handling, and creating custom exceptions for invalid age input. Each task is accompanied by source code and expected output, showcasing various Java concepts and functionalities.

Uploaded by

Devendra Tiwari
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views21 pages

Java Multi-threading and Exception Handling Examples

The document outlines multiple Java programming tasks, including simulating a banking system with thread synchronization, printing numbers and letters concurrently, and demonstrating object serialization. It also includes programs for file copying, exception handling, and creating custom exceptions for invalid age input. Each task is accompanied by source code and expected output, showcasing various Java concepts and functionalities.

Uploaded by

Devendra Tiwari
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Anurag A 18

13. Develop a program that creates multiple threads to simulate a banking


system where multiple users deposit and withdraw from the same
account (show synchronization).

Objective:
To develop a Java program that simulates a banking system using multiple
threads, allowing multiple users to deposit and withdraw from a shared
account. The program should demonstrate synchronization to prevent
data inconsistency.
Anurag A 18

Source Code
class Bank {
private int balance;

Bank(int balance)
{ [Link] =
balance;
}

synchronized void deposit(int


amount) { balance += amount;
[Link]([Link]().getName() + "
deposited " + amount);
[Link]("Balance: " + balance);
}

synchronized void withdraw(int


amount) { if (balance >=
amount) {
balance -= amount;
[Link]([Link]().getName() + " withdrew
" + amount);
} else {
[Link]([Link]().getName() + " tried to
withdraw "
+ amount + " — insufficient funds");
}
[Link]("Balance: " + balance);
}
}

class Customer extends


Thread { Bank bank;
boolean isDeposit;
Anurag A 18

int amount;

Customer(Bank bank, boolean isDeposit, int amount, String name)


{ super(name);
[Link] = bank;
[Link] =
isDeposit; [Link] =
amount;
}

public void
run() { if
(isDeposit)
[Link](amount);
else
[Link](amount);
}
}

public class BankTest {


public static void main(String[] args)
{ Bank bank = new Bank(1000);
Customer c1 = new Customer(bank, true, 100,
"C1"); Customer c2 = new Customer(bank,
false, 250, "C2"); Customer c3 = new
Customer(bank, false, 700, "C3"); Customer c4
= new Customer(bank, true, 800, "C4");
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Anurag A 18

Output:
C:\Desktop\Program>javac

[Link] C:\Desktop\

Program>java BankTest
C1 deposited 100

Balance: 1100

C4 deposited 800

Balance: 2200

C3 withdrew 700

Balance: 1500

C2 withdrew 250

Balance: 1250 C:\Desktop\

Program>
Anurag A 18

14. Create two threads in Java — one to print numbers from 1 to 10 and
another to print letters from A to J. Run both threads simultaneously.

Objective:
To develop a Java program that creates two threads — one to print
numbers from 1 to 10 and another to print letters from A to J. The
program should demonstrate concurrent thread execution.
Anurag A 18

Source Code
class Numbers extends Thread
{ public void run() {
for (int x = 1; x <= 10;
x++) {
[Link](x);
try {
[Link](200);
} catch (InterruptedException
e) { [Link](e);
}
}
}
}

class Letters extends Thread


{ public void run() {
for (char ch = 'A'; ch <= 'J'; ch+
+) { [Link](ch);
try {
[Link](200);
} catch (InterruptedException
e) { [Link](e);
}
}
}
}

public class ThreadDemo {


public static void main(String[] args)
{ Numbers numThread = new
Numbers();
Anurag A 18

Letters letterThread = new Letters();

[Link]();
[Link]();
}
}
Anurag A 18

Output:
C:\Desktop\Program>javac
[Link] C:\Desktop\
Program>java ThreadDemo

A B 1 C D 2 E F 3 G 5 H I 6 J 7 8 9 10

C:\Desktop\Program>
Anurag A 18

15. Write a Java program to serialize and deserialize an object


using ObjectOutputStream and ObjectInputStream.

Objective:
To develop a Java program that demonstrates object serialization and
deserialization using ObjectOutputStream and ObjectInputStream. The
program should store object data to a file and retrieve it accurately.
Anurag A 18

Source Code
import [Link].*;

class Novel implements


Serializable { int bookId;
String name;
String writer;

Novel(int bookId, String name, String writer)


{ [Link] = bookId;
[Link] = name;
[Link] = writer;
}

void display() {
[Link]("ID: " + bookId + ", Title: " + name + ", Author: "
+ writer);
}
}

public class FileStore {


public static void main(String[] args) {

try {
Novel n = new Novel(101, "The Great Gatsby", "F. Scott
Fitzgerald"); FileOutputStream fos = new
FileOutputStream("[Link]"); ObjectOutputStream oos =
new ObjectOutputStream(fos); [Link](n);
[Link]();
[Link]();
[Link]("Data stored successfully!");
Anurag A 18

} catch (IOException e)
{ [Link]("Error writing
object: " + e);
}

try {
FileInputStream fis = new
FileInputStream("[Link]");
ObjectInputStream ois = new
ObjectInputStream(fis); Novel n2 = (Novel)
[Link]();
[Link]();
[Link]();
[Link]("Data retrieved
successfully!"); [Link]();
} catch (Exception e) {
[Link]("Error reading object: " + e);
}
}
}
Anurag A 18

Output:
C:\Desktop\Program>javac
[Link] C:\Desktop\
Program>java FileStore
Data stored successfully!
Data retrieved
successfully!
ID: 101, Title: The Great Gatsby, Author: F. Scott Fitzgerald C:\

Desktop\Program>
Anurag A 18

16. Write a program to copy the contents from one file to another
using FileInputStream and FileOutputStream.

Objective:
To develop a Java program that copies the contents of one file to another
using FileInputStream and FileOutputStream. The program should ensure
that the data is transferred correctly between files.
Anurag A 18

Source Code
import [Link].*;

public class CopyFile {


public static void main(String[]
args) { try {
FileInputStream input = new FileInputStream("[Link]");
FileOutputStream output = new
FileOutputStream("[Link]");

int data;
while ((data = [Link]()) != -
1) { [Link](data);
}

[Link]();
[Link]();

[Link]("Copy completed successfully.");


} catch (IOException e)
{ [Link]("An error
occurred: " + e);
}
}
}
Anurag A 18

Output:

C:\Desktop\Program>javac [Link] C:\


Desktop\Program>java CopyFileStore [Link] [Link]
Copy completed successfully.
C:\Desktop\Program>
Anurag A 18

17. Write a Java program to demonstrate the use of try, catch, and
finally blocks.

Objective:
To develop a Java program that demonstrates exception handling using
try, catch, and finally blocks. The program should handle possible runtime
errors gracefully and ensure proper resource management.
Anurag A 18

Source Code
class DivisionDemo {
public static void main(String[]
args) { try {
int x =
10; int y
= 0;
int result = x / y;
[Link]("Result: " +
result);
}
catch (ArithmeticException ex)
{ [Link]("Cannot divide by
zero.");
}
finally {
[Link]("Finally block executed.");
}
}
}
Anurag A 18

Output:
C:\Desktop\Program>javac
[Link] C:\Desktop\
Program>java DivisionDemo Cannot
divide by zero.

C:\Desktop\Program>
Anurag A 18

18. Write a Java program to create and handle a user-defined


(custom) exception for invalid age input (e.g., age < 18).

Objective:
To develop a Java program that defines and handles a custom exception
for invalid age input. The program should throw an exception when the
entered age is below 18 and display an appropriate message.
Anurag A 18

Source Code
import [Link].*;

class NotEligibleException extends


Exception { NotEligibleException() {
super("You are not eligible to vote (under 18).");
}
}

public class VoteCheck {


public static void main(String[]
args) { Scanner sc = new
Scanner([Link]);
[Link]("Enter your age:
"); int age = [Link]();

try {
if (age < 18)
throw new
NotEligibleException(); else
[Link]("You are eligible to vote!");
}
catch (NotEligibleException e)
{ [Link]("Exception caught: " +
[Link]());
}
finally {
[Link]("Process complete.");
}
}
}
Anurag A 18

Output:
C:\Desktop\Program>javac

[Link] C:\Desktop\

Program>java VoteCheck Enter an

age: 19

Your age is valid C:\Desktop\

Program>

You might also like