0% found this document useful (0 votes)
3 views

Java unit 3

The document provides a comprehensive overview of exception handling and multithreading in Java, covering key concepts such as exception hierarchy, built-in exceptions, thread life cycle, and synchronization. It includes examples demonstrating the use of try-catch blocks, custom exceptions, thread creation, and communication between threads. Additionally, it touches on related topics like annotations, generics, and autoboxing.

Uploaded by

ariardy1396
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java unit 3

The document provides a comprehensive overview of exception handling and multithreading in Java, covering key concepts such as exception hierarchy, built-in exceptions, thread life cycle, and synchronization. It includes examples demonstrating the use of try-catch blocks, custom exceptions, thread creation, and communication between threads. Additionally, it touches on related topics like annotations, generics, and autoboxing.

Uploaded by

ariardy1396
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

EXCEPTION HANDLING AND MULTITHREADING

1. What is exception handling in Java?


A: Exception handling in Java is a mechanism to handle runtime errors and maintain the normal flow of
the application.

Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}

Benefits of Exception Handling

2. What are the benefits of exception handling in Java?


A:
1. Separates error-handling code from regular code.
2. Propagates errors up the call stack.
3. Provides a mechanism to handle different types of errors.

Example:

try {
int[] arr = new int[5];
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds");
}

Termination vs. Resumptive Models

3. What are termination and resumptive models in exception handling?


A:
- Termination: Control does not return to the code where the exception occurred.
- Resumptive: Control returns to the code where the exception occurred (not directly supported in Java).

Example (Termination Model):

try {
int[] arr = new int[5];
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds");
}
System.out.println("Execution continues here");
Exception Hierarchy

4. What is the exception hierarchy in Java?


A: The root of the exception hierarchy is `Throwable`. It has two main subclasses: `Error` and
`Exception`. `Exception` is further divided into checked and unchecked exceptions.

Example:

try {
int num = Integer.parseInt("XYZ");
} catch (NumberFormatException e) {
System.out.println("Number format exception");
}

Usage of `try`, `catch`, `throw`, `throws`, and `finally`

5.How are `try`, `catch`, `throw`, `throws`, and `finally` used in Java?
A: They are used to handle exceptions in a structured manner.

Example:

public class ExceptionExample {


public static void main(String[] args) {
try {
int result = divide(10, 0);
} catch (ArithmeticException e) {
System.out.println("Caught an exception: " + e.getMessage());
} finally {
System.out.println("Finally block executed");
}
}

static int divide(int a, int b) throws ArithmeticException {


if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return a / b;
}
}

Built-in Exceptions

6. What are built-in exceptions in Java?


A: Built-in exceptions are predefined exceptions provided by Java, such as `NullPointerException`,
`ArrayIndexOutOfBoundsException`, etc.
Example:

try {
String str = null;
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("Null pointer exception");
}
```

Creating Own Exception Subclasses

7.How do you create your own exception subclasses in Java?


A: By extending the `Exception` class or any of its subclasses.

Example:

class MyException extends Exception {


public MyException(String message) {
super(message);
}
}

public class CustomExceptionExample {


public static void main(String[] args) {
try {
validate(15);
} catch (MyException e) {
System.out.println("Caught custom exception: " + e.getMessage());
}
}

static void validate(int age) throws MyException {


if (age < 18) {
throw new MyException("Age not valid");
}
}
}
```

String Handling

8. How do you concatenate strings in Java?


A: Using the `+` operator or `concat` method.

Example:

String str1 = "Hello";


String str2 = "World";
String result = str1 + " " + str2;
System.out.println(result); // Output: Hello World
```

Exploring `java.util`

9. What is the `ArrayList` class in the `java.util` package?


A: `ArrayList` is a resizable array implementation of the `List` interface.

Example:

import java.util.ArrayList;

public class ArrayListExample {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");

for (String fruit : list) {


System.out.println(fruit);
}
}
}
```

Differences between Multithreading and Multitasking

10. What is the difference between multithreading and multitasking?


A:
- Multithreading: Running multiple threads concurrently within a single process.
- Multitasking: Running multiple processes concurrently.

Example:
Multithreading example in Java:

class MyThread extends Thread {


public void run() {
System.out.println("Thread is running");
}
}

public class ThreadExample {


public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}
```

Thread Life Cycle

11.What are the stages of the thread life cycle in Java?


A: New, Runnable, Running, Blocked/Waiting, Terminated.

Example:

class MyThread extends Thread {


public void run() {
try {
Thread.sleep(1000); // Thread is in the waiting state
System.out.println("Thread is running");
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
}
}

public class ThreadLifeCycleExample {


public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // Thread is in runnable state
}
}
```

Creating Threads

12.How do you create threads in Java?


A: By extending the `Thread` class or implementing the `Runnable` interface.

Example:

// By extending Thread class


class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}

public class ThreadExample1 {


public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}

// By implementing Runnable interface


class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable is running");
}
}

public class ThreadExample2 {


public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
t1.start();
}
}
```

Thread Priorities

13. How do you set thread priorities in Java?


A: Using the `setPriority(int priority)` method.

Example:

class MyThread extends Thread {


public void run() {
System.out.println("Thread is running");
}
}

public class ThreadPriorityExample {


public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
}
}
```

Synchronizing Threads

14. What is thread synchronization in Java?


A: Synchronization is used to control the access of multiple threads to shared resources.
Example:

class Counter {
int count = 0;

public synchronized void increment() {


count++;
}
}

public class SynchronizationExample {


public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();

Thread t1 = new Thread(() -> {


for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

Thread t2 = new Thread(() -> {


for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

t1.start();
t2.start();

t1.join();
t2.join();

System.out.println("Count: " + counter.count); // Should be 2000


}
}
```

Inter-Thread Communication

15.How do threads communicate with each other in Java?


A: Using the `wait()`, `notify()`, and `notifyAll()` methods.

Example:

class SharedResource {
private int data;

public synchronized void produce(int value) {


data = value;
notify();
}

public synchronized int consume() throws InterruptedException {


wait();
return data;
}
}

public class InterThreadCommunicationExample {


public static void main(String[] args) {
SharedResource resource = new SharedResource();

Thread producer = new Thread(() -> {


try {
Thread.sleep(1000);
resource.produce(10);
System.out.println("Produced data: 10");
} catch (InterruptedException e) {
e.printStackTrace();
}
});

Thread consumer = new Thread(() -> {


try {
int data = resource.consume();
System.out

.println("Consumed data: " + data);


} catch (InterruptedException e) {
e.printStackTrace();
}
});

producer.start();
consumer.start();
}
}
```

Thread Groups

16. What are thread groups in Java?


A: Thread groups are used to group multiple threads into a single object and manage them together.

Example:
public class ThreadGroupExample {
public static void main(String[] args) {
ThreadGroup group = new ThreadGroup("My Thread Group");

Thread t1 = new Thread(group, () -> {


System.out.println("Thread 1");
});

Thread t2 = new Thread(group, () -> {


System.out.println("Thread 2");
});

t1.start();
t2.start();

System.out.println("Thread Group Name: " + group.getName());


group.list();
}
}

Daemon Threads

17.What is a daemon thread in Java?


A: Daemon threads are background threads that provide services to user threads and do not prevent the
JVM from exiting.

Example:

class DaemonThreadExample extends Thread {


public void run() {
if (Thread.currentThread().isDaemon()) {
System.out.println("Daemon thread is running");
} else {
System.out.println("User thread is running");
}
}

public static void main(String[] args) {


DaemonThreadExample t1 = new DaemonThreadExample();
DaemonThreadExample t2 = new DaemonThreadExample();

t1.setDaemon(true); // Set t1 as daemon thread


t1.start();
t2.start();
}
}
```
Enumerations

18. What are enumerations in Java?


A: Enumerations are a special class type in Java used to define collections of constants.

Example:

enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

public class EnumExample {


public static void main(String[] args) {
Day day = Day.MONDAY;
System.out.println(day);
}
}
```

Autoboxing

19. What is autoboxing in Java?


A: Autoboxing is the automatic conversion of primitive types to their corresponding wrapper classes.

Example:

public class AutoboxingExample {


public static void main(String[] args) {
Integer num = 10; // Autoboxing from int to Integer
int value = num; // Unboxing from Integer to int
System.out.println(value);
}
}
```

Annotations

20. What are annotations in Java?


A: Annotations provide metadata about the program but have no direct effect on the codes execution.

Example:

@interface MyAnnotation {
String value();
}

@MyAnnotation(value = "Example Annotation")


public class AnnotationExample {
public static void main(String[] args) {
System.out.println("Annotations example");
}
}
```

Generics

21. What are generics in Java?


A: Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces, and
methods, providing type safety.

Example:

import java.util.ArrayList;

public class GenericsExample {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");

for (String str : list) {


System.out.println(str);
}
}
}

You might also like