0% found this document useful (0 votes)
6 views34 pages

UNIT-3-Material (1)

The document covers various concepts related to exceptions and multithreading in Java, including definitions of exceptions, differences between errors and exceptions, and the Readers-Writers problem. It also includes code examples for applications like a stopwatch and sorting algorithms using threads. Additionally, it discusses thread life cycles, inter-thread communication, and matrix operations implemented through multithreading.
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)
6 views34 pages

UNIT-3-Material (1)

The document covers various concepts related to exceptions and multithreading in Java, including definitions of exceptions, differences between errors and exceptions, and the Readers-Writers problem. It also includes code examples for applications like a stopwatch and sorting algorithms using threads. Additionally, it discusses thread life cycles, inter-thread communication, and matrix operations implemented through multithreading.
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
You are on page 1/ 34

UNIT-3

1a) Define an Exception.


Ans. An exception is an event which occurs during the execution of
a program, that disrupts the normal flow of the program’s execution.
1b) Differentiate Error and Exception.
Ans.
 Error occurs only when system resources are deficient
where as an exception is caused if code has some problem.
 Errors are usually not recoverable by the program itself.
Once an error occurs, it often leads to the program's
termination.
 Exceptions can be caught and handled by the program using
mechanisms like try-catch blocks in languages like Java or
Python.
1c) Design an application to solve Readers- Writers Problem.
The Readers-Writers Problem is a classic synchronization issue
in operating systems that involves managing access to shared
data by multiple threads or processes. The problem addresses
the scenario where:
 Readers: Multiple readers can access the shared data
simultaneously without causing any issues because they
are only reading and not modifying the data.
 Writers: Only one writer can access the shared data at a
time to ensure data integrity, as writers modify the data,
and concurrent modifications could lead to data
corruption or inconsistencies.
Ans.
class ReaderWriter {
private int readers = 0; // Counts the active readers
private boolean isWriting = false; // Indicates if a writer is
active
// Reader method
public synchronized void startReading(int readerId) {
while (isWriting) { // Wait if a writer is writing
try {
wait();
} catch (InterruptedException e) {
System.out.println("Reader " + readerId + " was
interrupted.");
}
}
readers++; // Increment reader count
System.out.println("Reader " + readerId + " starts reading.
Active readers: " + readers);
}
public synchronized void stopReading(int readerId) {
readers--; // Decrement reader count
System.out.println("Reader " + readerId + " stops reading.
Remaining readers: " + readers);
if (readers == 0) {
notify(); // Notify waiting writers if no readers are left
}
}
// Writer method
public synchronized void startWriting(int writerId) {
while (isWriting || readers > 0) { // Wait if another writer or
any reader is active
try {
wait();
} catch (InterruptedException e) {
System.out.println("Writer " + writerId + " was
interrupted.");
}
}
isWriting = true; // Indicate that a writer is active
System.out.println("Writer " + writerId + " starts writing.");
}
public synchronized void stopWriting(int writerId) {
isWriting = false; // Indicate that no writer is active
System.out.println("Writer " + writerId + " stops writing.");
notifyAll(); // Notify all waiting threads (readers or writers)
}
// Reader thread class
static class Reader extends Thread {
private final ReaderWriterProblem problem;
private final int readerId;
Reader(ReaderWriterProblem problem, int readerId) {
this.problem = problem;
this.readerId = readerId;
}
public void run() {
problem.startReading(readerId);
try {
Thread.sleep(100); // Simulate reading
} catch (InterruptedException e) {
System.out.println("Reader " + readerId + " was
interrupted during reading.");
}
problem.stopReading(readerId);
}
}
// Writer thread class
static class Writer extends Thread {
private final ReaderWriterProblem problem;
private final int writerId;
Writer(ReaderWriterProblem problem, int writerId) {
this.problem = problem;
this.writerId = writerId;
}
public void run() {
problem.startWri
ting(writerId);
try {
Thread.sleep(100); // Simulate writing
} catch (InterruptedException e) {
System.out.println("Writer " + writerId + " was
interrupted during writing.");
}
problem.stopWriting(writerId);
}
}
public static void main(String[] args) {
ReaderWriterProblem problem = new
ReaderWriterProblem();
// Start reader and writer threads
for (int i = 1; i <= 3; i++) {
new Reader(problem, i).start();
}
for (int i = 1; i <= 2; i++) {
new Writer(problem, i).start();
}
}
}
Output:
Reader 2 starts reading. Active readers: 1
Reader 3 starts reading. Active readers: 2
Reader 1 starts reading. Active readers: 3
Reader 1 stops reading. Remaining readers: 2
Reader 3 stops reading. Remaining readers: 1
Reader 2 stops reading. Remaining readers: 0
Writer 2 starts writing.
Writer 2 stops writing.
Writer 1 starts writing.
Writer 1 stops writing.
2a) Differentiate throw & throws keywords.
Ans.
 Most of the time system(i.e,compiler) generates exceptions
automatically by java run time system. throw keyword is
used to create customized exceptions.
 Syntax:
throw new CustomizedException();
 throws keyword is used to indicate what exception type
may be thrown by a method. We can apply throws in
throwable types only.
 "throws" keyword required only checked exceptions.
 Syntax:
MethodName() throws InteruptedException
2b) What is the purpose of finally keyword.
Ans. Finally block contains error free code, which executes always
whether the exceptions are handled or not.
2c) Develop a Java application to create a Stop watch using
multithreading. User should be prompted to enter time interval.
Ans.
import java.util.Scanner;
class Stopwatch implements Runnable {
private volatile boolean running = false;
private long elapsedTime = 0; // Elapsed time in
milliseconds
private final long interval; // Interval for time
display updates

public Stopwatch(long interval) {


this.interval = interval;
}

public void start() {


running = true;
new Thread(this).start();
}
public void stop() {
running = false;
}

public void reset() {


elapsedTime = 0;
}

@Override
public void run() {
while (running) {
try {
Thread.sleep(interval); // Wait for the
specified interval
elapsedTime += interval; // Increment the
elapsed time
displayTime();
} catch (InterruptedException e) {
System.out.println("Stopwatch
interrupted.");
}
}
}

private void displayTime() {


long seconds = (elapsedTime / 1000) % 60;
long minutes = (elapsedTime / (1000 * 60)) %
60;
long hours = (elapsedTime / (1000 * 60 * 60))
% 24;
System.out.printf("Elapsed Time: %02d:
%02d:%02d\n", hours, minutes, seconds);
}
}

public class StopWatchApp {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter time interval in
milliseconds for stopwatch updates: ");
long interval = scanner.nextLong();

Stopwatch stopwatch = new


Stopwatch(interval);
String command;

while (true) {
System.out.print("Enter command (start,
stop, reset, exit): ");
command = scanner.next().toLowerCase();
switch (command) {
case "start":
stopwatch.start();
System.out.println("Stopwatch
started.");
break;
case "stop":
stopwatch.stop();
System.out.println("Stopwatch
stopped.");
break;
case "reset":
stopwatch.reset();
System.out.println("Stopwatch reset.");
break;
case "exit":
stopwatch.stop();
System.out.println("Exiting...");
return;
default:
System.out.println("Invalid command.
Try again.");
}
}
}
}
Output:
Enter time interval in milliseconds for stopwatch
updates: 1000
Enter command (start, stop, reset, exit): start
Stopwatch started.
Enter command (start, stop, reset, exit): Elapsed
Time: 00:00:01
Elapsed Time: 00:00:02
Elapsed Time: 00:00:03
Elapsed Time: 00:00:04
stopElapsed Time: 00:00:05

Stopwatch stopped.
Enter command (start, stop, reset, exit): Elapsed
Time: 00:00:06
start
Stopwatch started.
Enter command (start, stop, reset, exit): Elapsed
Time: 00:00:07
Elapsed Time: 00:00:08
Elapsed Time: 00:00:09
Elapsed Time: 00:00:10
Elapsed Time: 00:00:11
Elapsed Time: 00:00:12
Elapsed Time: 00:00:13
Elapsed Time: 00:00:14
resetElapsed Time: 00:00:15

Stopwatch reset.
Enter command (start, stop, reset, exit): Elapsed
Time: 00:00:01
Elapsed Time: 00:00:02
Elapsed Time: 00:00:03
Elapsed Time: 00:00:04
Elapsed Time: 00:00:05
stopElapsed Time: 00:00:06
Stopwatch stopped.
Enter command (start, stop, reset, exit): Elapsed
Time: 00:00:07

3a) How do we start and stop a thread?


Ans. You can create a thread by either extending the Thread class
or implementing the Runnable interface.
 The start() method: This is used to begin the execution of
the thread. It internally calls the run() method.
 You can call interrupt() to signal the thread to stop if it is
waiting or sleeping.
3b) Summarize methods of Inter thread communication.
Ans. Two Threads can communicate with each other by using
wait(), notify() and notifyAll() methods.
 The Thread which is required updation it has to call wait()
method on the required object then immediately the
Thread will entered into waiting state.
 The Thread which is performing updation of object, it is
responsible to give notification by calling notify() method.
 After getting notification the waiting Thread will get those
updations.
3c) Design a multithreaded application to create two threads-
one implementing Bubble sort and another implementing
Merge sort technique. Input an unsorted list and sort it using
both techniques.
Ans.
import java.util.Arrays;
import java.util.Scanner;
class BubbleSortThread extends Thread {
private int[] array;

public BubbleSortThread(int[] array) {


this.array = Arrays.copyOf(array, array.length);
}
@Override
public void run() {
bubbleSort(array);
System.out.println("Sorted using Bubble Sort: " +
Arrays.toString(array));
}
private void bubbleSort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (array[j] > array[j + 1]) {
// Swap array[j] and array[j+1]
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
}
class MergeSortThread extends Thread {
private int[] array;
public MergeSortThread(int[] array) {
this.array = Arrays.copyOf(array, array.length);
}
@Override
public void run() {
mergeSort(array, 0, array.length - 1);
System.out.println("Sorted using Merge Sort: " +
Arrays.toString(array));
}
private void mergeSort(int[] array, int left, int right) {
if (left < right) {
int mid = (left + right) / 2;
mergeSort(array, left, mid);
mergeSort(array, mid + 1, right);
merge(array, left, mid, right);
}
}
private void merge(int[] array, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;

int[] leftArray = new int[n1];


int[] rightArray = new int[n2];
for (int i = 0; i < n1; i++)
leftArray[i] = array[left + i];
for (int j = 0; j < n2; j++)
rightArray[j] = array[mid + 1 + j];
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (leftArray[i] <= rightArray[j]) {
array[k] = leftArray[i];
i++;
} else {
array[k] = rightArray[j];
j++;
}
k++;
}
while (i < n1) {
array[k] = leftArray[i];
i++;
k++;
}
while (j < n2) {
array[k] = rightArray[j];
j++;
k++;
}
}
}
public class Sorting {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input the size and elements of the array
System.out.print("Enter the number of elements: ");
int n = sc.nextInt();
int[] array = new int[n];
System.out.println("Enter the elements:");
for (int i = 0; i < n; i++) {
array[i] = sc.nextInt();
}
Thread bubbleSortThread = new BubbleSortThread(array);
Thread mergeSortThread = new MergeSortThread(array);
bubbleSortThread.start();
mergeSortThread.start();
try {
bubbleSortThread.join();
mergeSortThread.join();
} catch (InterruptedException e) {
System.out.println("Sorting threads interrupted.");
}
sc.close();
}
}
Output:
Enter the number of elements: 5
Enter the elements:
63
25
43
24
15
Sorted using Bubble Sort: [15, 24, 25, 43, 63]
Sorted using Merge Sort: [15, 24, 25, 43, 63]
4a) Differentiate between thread and process.
Ans.
Process Based Multitasking:
Executing several tasks simultaneously, where each task is
having independent process.
 It is best suitable at OS level.
Thread based Multitasking:
Executing several tasks simultaneously, where all the
tasks are related to the same program.
 Each and every task is called as a Thread.
 It is best suitable at programmatic level.
4b) Explain the life cycle of a Thread.
Ans.

1. Once we created a Thread object then the Thread is said to


be in new or born state.
2. Once we call start() method then the Thread will be entered
into Ready or Runnable state.
3. If Thread Scheduler allocates CPU then the Thread will be
entered into running state.
4. Once run() method completes then the Thread will entered
into dead state.
4c) Design a multithreaded application to create two threads-
one thread performing Matrix addition and another
implementing Matrix multiplication.
Ans.
import java.util.Scanner;
class MatrixAdditionThread extends Thread {
private int[][] matrixA;
private int[][] matrixB;
private int[][] result;
public MatrixAdditionThread(int[][] matrixA, int[][] matrixB) {
this.matrixA = matrixA;
this.matrixB = matrixB;
this.result = new int[matrixA.length][matrixA[0].length];
}
@Override
public void run() {
for (int i = 0; i < matrixA.length; i++) {
for (int j = 0; j < matrixA[0].length; j++) {
result[i][j] = matrixA[i][j] + matrixB[i][j];
}
}
System.out.println("Matrix Addition:");
printMatrix(result);
}
private void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
}
class MatrixMultiplicationThread extends Thread {
private int[][] matrixA;
private int[][] matrixB;
private int[][] result;
public MatrixMultiplicationThread(int[][] matrixA, int[][]
matrixB) {
this.matrixA = matrixA;
this.matrixB = matrixB;
this.result = new int[matrixA.length][matrixB[0].length];
}
@Override
public void run() {
for (int i = 0; i < matrixA.length; i++) {
for (int j = 0; j < matrixB[0].length; j++) {
for (int k = 0; k < matrixA[0].length; k++) {
result[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}
System.out.println("Matrix Multiplication:");
printMatrix(result);
}
private void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
}
public class Matrix{
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of Rows and Columns
for Matrices: ");
int rows = sc.nextInt();
int cols = sc.nextInt();
int[][] matrixA = new int[rows][cols];
int[][] matrixB = new int[rows][cols];
System.out.println("Enter elements for Matrix A:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrixA[i][j] = sc.nextInt();
}
}
System.out.println("Enter elements for Matrix B:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrixB[i][j] = sc.nextInt();
}
}
// Ensure matrices are compatible for addition and
multiplication
if (rows == matrixB.length && cols == matrixB[0].length) {
Thread additionThread = new
MatrixAdditionThread(matrixA, matrixB);
additionThread.start();
Thread.sleep(1000);
} else {
System.out.println("Matrix Addition is not Possible.");
}
if (matrixA[0].length == matrixB.length) {
Thread multiplicationThread = new
MatrixMultiplicationThread(matrixA, matrixB);
multiplicationThread.start();
} else {
System.out.println("MatriX Multiplication is not
Possible.");
}
sc.close();
}
}
Output:
4d) How do we set priorities for threads? Construct a java
program to explain thread priorities usage.
Ans.
class MyThread extends Thread {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " -
Priority: " + Thread.currentThread().getPriority() + " - Count: " +
i);
try {
Thread.sleep(1000); // Simulating some work
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
public class ThreadPriorityExample {
public static void main(String[] args) {
// Creating threads
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
// Setting thread priorities
t1.setPriority(Thread.MIN_PRIORITY); // Lowest priority
t2.setPriority(Thread.NORM_PRIORITY); // Default
priority(5)
t3.setPriority(Thread.MAX_PRIORITY); // Highest priority
// Starting threads
t1.start();
t2.start();
t3.start();
// Ensure the main thread waits for the child threads to
finish
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println("Main thread execution finished.");
}
}
Output:
Thread-3 - Priority: 10 - Count: 1
Thread-3 - Priority: 10 - Count: 2
Thread-3 - Priority: 10 - Count: 3
Thread-3 - Priority: 10 - Count: 4
Thread-3 - Priority: 10 - Count: 5
Thread-2 - Priority: 5 - Count: 1
Thread-2 - Priority: 5 - Count: 2
Thread-2 - Priority: 5 - Count: 3
Thread-2 - Priority: 5 - Count: 4
Thread-2 - Priority: 5 - Count: 5
Thread-1 - Priority: 1 - Count: 1
Thread-1 - Priority: 1 - Count: 2
Thread-1 - Priority: 1 - Count: 3
Thread-1 - Priority: 1 - Count: 4
Thread-1 - Priority: 1 - Count: 5
Main thread execution finished.
5a) What is synchronization and why is it important?
Ans. Synchronized is the keyword applicable for methods and
blocks but not for classes and variables.
 If a method or block declared as the synchronized then at a
time only one Thread is allowed to execute that method or
block on the given object.
 The main advantage of synchronized keyword is we can
resolve date inconsistency problems.
 Internally synchronization concept is implemented by using
lock concept.
 Every object in java has a unique lock.
5b) Differentiate between Checked and Unchecked Exceptions.
Ans.
 Checked exceptions are exceptions that the compiler forces
the programmer to handle explicitly. If a method can throw
a checked exception, the programmer must either handle it
with a try-catch block or declare it using the throws
keyword in the method signature.
 Unchecked exceptions are exceptions that are not required
to be explicitly handled or declared by the programmer.
These are subclasses of RuntimeException, and they usually
represent programming errors or incorrect logic that is
difficult to anticipate or handle programmatically.
5c) Write the differences between StringBuffer and StringBuilder.
Ans.
StringBuffer StringBuilder
 Every method present in  No method present in
StringBuffer is StringBuilder is
synchronized. synchronized.
 At a time only one  At a time Multiple Threads
thread is allow to are allowed to operate
operate on the simultaneously on the
StringBuffer object StringBuilder object hence
hence StringBuffer StringBuilder is not Thread
object is Thread safe. safe.

 It increases waiting time


 Threads are not required to
of the Thread and hence
wait and hence relatively
relatively performance
performance is high.
is low.
5d) Develop a Java application to implement Ceaser Cipher.
In this technique, each letter of the given text is replaced by a
letter of some fixed number of positions down the alphabet.
Perform both encryption and decryption.
Ans.
import java.util.Scanner;
public class Ceaser {
public static String encrypt(String text, int shift)
{
StringBuilder encryptedText = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char character = text.charAt(i);
if (Character.isLetter(character)) {
char shiftedChar;
// Check if the character is uppercase or lowercase
if (Character.isUpperCase(character)) {
shiftedChar = (char) (((int) character + shift - 65) %
26 + 65);
} else {
shiftedChar = (char) (((int) character + shift - 97) %
26 + 97);
}
encryptedText.append(shiftedChar);
}
else {
// If it's not a letter, just append the character
without changing it
encryptedText.append(character);
}
}
return encryptedText.toString();
}
// Decrypting the text
public static String decrypt(String text, int shift) {
StringBuilder decryptedText = new StringBuilder();
// Loop through each character in the text
for (int i = 0; i < text.length(); i++) {
char character = text.charAt(i);
// Decrypt only alphabetic characters
if (Character.isLetter(character)) {
char shiftedChar;
// Check if the character is uppercase or lowercase
if (Character.isUpperCase(character)) {
shiftedChar = (char) (((int) character - shift - 65 +
26) % 26 + 65);
} else {
shiftedChar = (char) (((int) character - shift - 97 +
26) % 26 + 97);
}
decryptedText.append(shiftedChar);
} else {
// If it's not a letter, just append the character
without changing it
decryptedText.append(character);
}
}
return decryptedText.toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Taking input for the text to be encrypted
System.out.print("Enter the Data: ");
String text = scanner.nextLine();
// Taking input for the shift key
System.out.print("Enter the shift key (integer): ");
int shift = scanner.nextInt();
// Encrypt the input text
String encryptedText = encrypt(text, shift);
System.out.println("Encrypted Data: " + encryptedText);
// Decrypt the encrypted text
String decryptedText = decrypt(encryptedText, shift);
System.out.println("Decrypted Data: " + decryptedText);
scanner.close();
}
}
Output:
Enter the Data: Welcome to Java Programming.
Enter the shift key (integer): 2
Encrypted Data: Ygneqog vq Lcxc Rtqitcookpi.
Decryptrd Data: Welcome to Java Programming.
6a) Define daemon thread.
Ans. The Threads which are executing in the background are called
daemon Threads.
 The main objective of daemon Threads is to provide support for
non-daemon Threads like main Thread.
 Example: Garbage collector
6b) Defne autoboxing.
Ans. The automatic conversion of primitive data types into its
equivalent Wrapper class is known as autoboxing.
6c) Develop java program to implement enum.
Ans.
enum Season
{
WINTER, SPRING, SUMMER, FALL
}

public class EnumSeasonExample


{
public static void main(String[] args)
{
Season currentSeason = Season.SUMMER;
switch (currentSeason)
{
case WINTER: System.out.println("It's cold!");
break;
case SPRING: System.out.println ("Flowers are blooming!");
break;
case SUMMER: System.out.println ("It's hot!");
break;
case FALL: System.out.println("Leaves are falling!");
break;
}
}
}
Output:
It's hot!
6d) Write java program to implement generics.
Ans.
// Generic class with a type parameter T
class GenericBox<T> {
private T value;
// Constructor
public GenericBox(T value) {
this.value = value;
}
// Getter method
public T getValue() {
return value;
}
// Setter method
public void setValue(T value) {
this.value = value;
}
}
// Generic method
public class GenericExample {
// Generic method that prints the type of the input
public static <T> void printType(T value) {
System.out.println("Value: " + value + ", Type: " +
value.getClass().getName());
}
public static void main(String[] args) {
// Using GenericBox with Integer
GenericBox<Integer> intBox = new GenericBox<>(42);
System.out.println("Integer value: " + intBox.getValue());
// Using GenericBox with String
GenericBox<String> strBox = new GenericBox<>("Hello,
Generics!");
System.out.println("String value: " + strBox.getValue());
// Using the generic method printType
printType(123); // Integer type
printType("Java"); // String type
printType(3.14); // Double type
}
}
Output:
Integer value: 42
String value: Hello, Generics!
Value: 123, Type: java.lang.Integer
Value: Java, Type: java.lang.String
Value: 3.14, Type: java.lang.Double

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy