Java unit 3
Java unit 3
Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
Example:
try {
int[] arr = new int[5];
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds");
}
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
Example:
try {
int num = Integer.parseInt("XYZ");
} catch (NumberFormatException e) {
System.out.println("Number format exception");
}
5.How are `try`, `catch`, `throw`, `throws`, and `finally` used in Java?
A: They are used to handle exceptions in a structured manner.
Example:
Built-in Exceptions
try {
String str = null;
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("Null pointer exception");
}
```
Example:
String Handling
Example:
Exploring `java.util`
Example:
import java.util.ArrayList;
Example:
Multithreading example in Java:
Example:
Creating Threads
Example:
Thread Priorities
Example:
Synchronizing Threads
class Counter {
int count = 0;
t1.start();
t2.start();
t1.join();
t2.join();
Inter-Thread Communication
Example:
class SharedResource {
private int data;
producer.start();
consumer.start();
}
}
```
Thread Groups
Example:
public class ThreadGroupExample {
public static void main(String[] args) {
ThreadGroup group = new ThreadGroup("My Thread Group");
t1.start();
t2.start();
Daemon Threads
Example:
Example:
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
Autoboxing
Example:
Annotations
Example:
@interface MyAnnotation {
String value();
}
Generics
Example:
import java.util.ArrayList;