Theory Concepts After Oops
Theory Concepts After Oops
CONCEPTS
AFTER
OOPS
EXCEPTION HANDLING
only one exception will be handled the 1st on will be handled after that it wont
be handled,even if there is a exception type of its ,its handled by its own
method only if its type is not present then only exception type will be handled
and can't write any catch blocks after exception type it wont be reached
public class Prg3 {
public static void main(String[] args) {
try {
String s = "abc";
char c = s.charAt(5);
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Caught an ArithmeticException.");
}
catch (StringIndexOutOfBoundsException e) {
System.out.println("Caught a StringIndexOutOfBoundsException.");
}
catch(Exception e) {
System.out.println("same type handled");
}
}
}
NESTED BLOCK:
package ExceptionHnadling;
try {
// This line won't execute because the outer try will throw an
exception
int result = 10 / 0; // This would throw an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Inner catch block: ArithmeticException
caught.");
}
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Outer catch block:
StringIndexOutOfBoundsException caught.");
} catch (Exception e) {
System.out.println("Outer catch block: Some other exception
caught.");
}
}
}
SYNTAX:
try{
try{
catch(){
}}catch(){
Try{
}
Catch(){
}}
FINALLY BLOCK:
package ExceptionHnadling;
// finally is will get executed even if u handle the execution or not
public class Prg5 {
public static void main(String[] args) {
try {
System.out.println("Accessing element at index 5:");
int num = numbers[5]; // This will throw
IndexOutOfBoundsException
System.out.println("Dividing 10 by divisor:");
int result = 10 / divisor; // This would throw ArithmeticException
if it were reached
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " +
e.getMessage());
} catch (IndexOutOfBoundsException e) {
System.out.println("Caught IndexOutOfBoundsException: " +
e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
EXCPTION PROPAGATION:
Passing a exception to its caller method is called exception propagation
TYPES:
CHECKED
UNCHECKED
CHECKED
import java.io.FileReader;
import java.io.IOException;
UNCHECKED:
Check the examples
PROPAGATION EXAMPLE:
package ExceptionHnadling;
Used in a method
Used to explicitly throw an exception in signature to declare
Purpose
code. exceptions that might be
thrown by the method.
MULTITASING
TYPES:
In process-based multitasking, multiple independent programs (processes) are run
concurrently. Each process has its own memory space, program code, and data. The
operating system allocates resources to each process and ensures they don’t
interfere with each other.
Example: Running a browser, a text editor, and a media player
simultaneously on a computer.
Thread-based multitasking, also known as multithreading, involves dividing a
single process into multiple threads. Each thread can perform a different task within
the same program, sharing the same memory and resources.
Example: A web browser with multiple tabs, where each tab runs as a
separate thread within the same process.
THREAD:
a thread is the smallest unit of execution within a process. It represents a single
sequence of instructions that can be managed independently by the operating
system's scheduler. Threads allow a program to perform multiple tasks
simultaneously, which is particularly useful in applications requiring responsiveness,
concurrency, or parallelism.
EXAMPLE 1
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread " + Thread.currentThread().getId() + " is running,
iteration: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
}
EXAMPLE 2:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running: " + Thread.currentThread().getName());
}
}
EXAMPLE 3:
class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread " + Thread.currentThread().getId() + " is running,
iteration: " + i);
try {
Thread.sleep(500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
System.out.println("Thread interrupted: " + e.getMessage());
}
}
}
}
Begins a new thread of Contains the code that defines the task or
Purpose
execution in the JVM. job the thread will execute.
How it Invokes the run() method in a Executes in the current thread without
Works new, separate thread. creating a new thread.
Used Starting a thread in a separate, Defining the behavior of the thread
For concurrent execution path. (the code it runs).
Creates a new thread and then Runs as a normal method within the
Behavior
invokes run() on that thread. current thread if called directly.
THREAD PRIORITY
public class ThreadPriorityExample {
Priority and Often lower priority than user Can have any
Scheduling threads priority
SYNCHORIZATION:
In Java, synchronization is achieved by using the synchronized keyword on methods
or blocks of code. When a method or block is marked as synchronized, it acquires a
lock to prevent other threads from accessing the same method or block until the lock
is released.
class Counter {
private int count = 0;
t1.start();
t2.start();
t1.join();
t2.join();
t1.start();
t2.start();
}
}
Explanation
Here, synchronized(this) locks on the Printer instance (printer), so only one
thread can access printDocument() at a time for that specific instance.
If multiple instances of Printer existed, each instance would have its own lock,
and different threads could access printDocument() on different instances
concurrently.
3. Class-Level Lock
Class-level lock is acquired on the class object itself, which is the .class object
associated with a class. This type of lock is used when we want to synchronize static
methods or blocks across all instances of a class, ensuring that only one thread can
access the synchronized block or method at a time for the entire class.
Example of Class-Level Lock
java
Copy code
class Database {
// Static synchronized method (class-level lock)
public static synchronized void accessDatabase(String threadName) {
for (int i = 1; i <= 5; i++) {
System.out.println(threadName + " is accessing the database - Step " + i);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
t1.start();
t2.start();
}
}
Explanation
The accessDatabase() method is static synchronized, meaning it uses a
class-level lock.
Since this lock is on the Database.class object, only one thread can execute
accessDatabase() at a time across all threads, regardless of the instance.
Even if multiple Database instances are created, accessDatabase() can only
be accessed by one thread at a time because of the class-level lock.