0% found this document useful (0 votes)
0 views14 pages

OOPs Using Java Notes UNIT-2

The document covers exception handling in Java, explaining the difference between exceptions and errors, types of exceptions (checked and unchecked), and the control flow during exceptions. It also discusses input/output operations using byte and character streams, as well as multithreading concepts including thread life cycle, creation, priorities, synchronization, and inter-thread communication. Examples of code are provided to illustrate each concept effectively.

Uploaded by

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

OOPs Using Java Notes UNIT-2

The document covers exception handling in Java, explaining the difference between exceptions and errors, types of exceptions (checked and unchecked), and the control flow during exceptions. It also discusses input/output operations using byte and character streams, as well as multithreading concepts including thread life cycle, creation, priorities, synchronization, and inter-thread communication. Examples of code are provided to illustrate each concept effectively.

Uploaded by

aryantiwari42675
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

UNIT-2

The Idea behind Exception

Exception handling is a mechanism to handle runtime errors so that the normal flow of
the application can be maintained. It allows us to handle exceptional conditions in a
controlled way.

Exceptions & Errors

Exceptions are events that occur during the execution of a program that disrupt the
normal flow of instructions. Errors are mistakes in the code that can be caught and
handled.

Types of Exception

There are two types of exceptions in Java:

1. Checked Exceptions: These are exceptions that are checked at compile-time. Examples
include IOException, SQLException, etc.

2. Unchecked Exceptions: These are exceptions that are not checked at compile-time.
Examples include ArithmeticException, NullPointerException, etc.

Control Flow in Exceptions

When an exception occurs, the control flow is transferred to the catch block. If there is
no catch block, the control flow is transferred to the default exception handler.

JVM Reaction to Exceptions

When an exception occurs, the JVM searches for a catch block to handle the exception.
If it finds one, it transfers the control flow to the catch block. If it doesn't find one, it
terminates the program.

Use of try, catch, finally, throw, throws in Exception Handling

 try: The try block contains the code that may throw an exception.
 catch: The catch block contains the code to handle the exception.
 finally: The finally block contains the code that is executed regardless of whether an
exception occurs or not.
 throw: The throw keyword is used to throw an exception explicitly.
 throws: The throws keyword is used to declare that a method may throw an exception.

Here's an example program:

public class ExceptionHandling {

public static void main(String[] args) {

try {

int x = 5 / 0; // This will throw an ArithmeticException

} catch (ArithmeticException e) {

System.out.println("Caught ArithmeticException: " + e.getMessage());

} finally {

System.out.println("Finally block executed");

In-built and User Defined Exceptions

In-built exceptions are exceptions that are already defined in Java, such as
ArithmeticException, NullPointerException, etc. User-defined exceptions are exceptions
that are defined by the user, such as custom exceptions for a specific application.

Here's an example program:

public class UserDefinedException {

public static void main(String[] args) {

try {
validateAge(15); // This will throw a UserDefinedException

} catch (UserDefinedException e) {

System.out.println("Caught UserDefinedException: " + e.getMessage());

public static void validateAge(int age) throws UserDefinedException {

if (age < 18) {

throw new UserDefinedException("You are not eligible to vote");

class UserDefinedException extends Exception {

public UserDefinedException(String message) {

super(message);

Checked and Un-Checked Exceptions

Here's an example program:

public class CheckedAndUncheckedExceptions {

public static void main(String[] args) {

try {
readFile("non-existent-file.txt"); // This will throw a Checked Exception
(IOException)

} catch (IOException e) {

System.out.println("Caught IOException: " + e.getMessage());

try {

int x = 5 / 0; // This will throw an Unchecked Exception (ArithmeticException)

} catch (ArithmeticException e) {

System.out.println("Caught ArithmeticException: " + e.getMessage());

public static void readFile(String filename) throws IOException {

FileReader fileReader = new FileReader(filename);

//...

}
Input/Output Basics: Byte Streams and Character Streams

In Java, input/output operations are performed using streams. There are two types of
streams:

1. Byte Streams: These streams deal with bytes, which are the basic units of data in
computers. They are used to read and write binary data, such as images and audio files.
Examples of byte streams include FileInputStream and FileOutputStream.
2. Character Streams: These streams deal with characters, which are the basic units of text
data. They are used to read and write text data, such as strings and characters. Examples
of character streams include FileReader and FileWriter.

Byte Streams

Here's an example program that demonstrates the use of byte streams to read and write
a file:

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

public class ByteStreamsExample {

public static void main(String[] args) {

try {

// Create a byte stream to read from a file

FileInputStream fis = new FileInputStream("input.txt");

byte[] buffer = new byte[1024];

int bytesRead = fis.read(buffer);

System.out.println("Read " + bytesRead + " bytes from file");


// Create a byte stream to write to a file

FileOutputStream fos = new FileOutputStream("output.txt");

fos.write(buffer, 0, bytesRead);

System.out.println("Wrote " + bytesRead + " bytes to file");

fis.close();

fos.close();

} catch (IOException e) {

System.out.println("Error: " + e.getMessage());

Character Streams

Here's an example program that demonstrates the use of character streams to read and
write a file:

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

public class CharacterStreamsExample {

public static void main(String[] args) {

try {

// Create a character stream to read from a file


FileReader fr = new FileReader("input.txt");

char[] buffer = new char[1024];

int charsRead = fr.read(buffer);

System.out.println("Read " + charsRead + " characters from file");

// Create a character stream to write to a file

FileWriter fw = new FileWriter("output.txt");

fw.write(buffer, 0, charsRead);

System.out.println("Wrote " + charsRead + " characters to file");

fr.close();

fw.close();

} catch (IOException e) {

System.out.println("Error: " + e.getMessage());

Reading and Writing Files in Java

Here's an example program that demonstrates how to read and write a file in Java using
character streams:

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;
public class ReadWriteFileExample {

public static void main(String[] args) {

try {

// Write to a file

FileWriter fw = new FileWriter("example.txt");

fw.write("Hello, World!");

fw.close();

System.out.println("Wrote to file");

// Read from a file

FileReader fr = new FileReader("example.txt");

char[] buffer = new char[1024];

int charsRead = fr.read(buffer);

System.out.println("Read from file: " + new String(buffer, 0, charsRead));

fr.close();

} catch (IOException e) {

System.out.println("Error: " + e.getMessage());

}
Multithreading: Thread

In Java, a thread is a separate path of execution that can run concurrently with other
threads. Threads are used to improve the responsiveness and performance of a
program.

Thread Life Cycle

The life cycle of a thread includes:

1. Newborn: The thread is created but not started.


2. Runnable: The thread is started and is eligible to run.
3. Running: The thread is currently executing.
4. Waiting: The thread is waiting for some event to occur.
5. Dead: The thread has finished executing.

Creating Threads

There are two ways to create threads in Java:

1. Extending the Thread class: By extending the Thread class, you can create a new
thread by overriding the run() method.
2. Implementing the Runnable interface: By implementing the Runnable interface, you
can create a new thread by providing a run() method.

Here's an example program that demonstrates creating threads using both methods:

// Extending the Thread class

class MyThread extends Thread {

public void run() {

System.out.println("Hello from MyThread!");

// Implementing the Runnable interface

class MyRunnable implements Runnable {


public void run() {

System.out.println("Hello from MyRunnable!");

public class CreatingThreads {

public static void main(String[] args) {

MyThread myThread = new MyThread();

myThread.start();

MyRunnable myRunnable = new MyRunnable();

Thread thread = new Thread(myRunnable);

thread.start();

Thread Priorities

Thread priorities are used to determine the order in which threads are executed. In Java,
threads have a priority between 1 and 10, with 10 being the highest priority.

Here's an example program that demonstrates setting thread priorities:

public class ThreadPriorities {

public static void main(String[] args) {

Thread thread1 = new Thread(new MyRunnable());

thread1.setPriority(5);

Thread thread2 = new Thread(new MyRunnable());


thread2.setPriority(10);

thread1.start();

thread2.start();

Synchronizing Threads

Synchronization is used to ensure that only one thread can access a shared resource at a
time. In Java, synchronization is achieved using the synchronized keyword.

Here's an example program that demonstrates synchronizing threads:

class MyRunnable implements Runnable {

private int count = 0;

public synchronized void increment() {

count++;

public void run() {

for (int i = 0; i < 100000; i++) {

increment();

}
public class SynchronizingThreads {

public static void main(String[] args) {

MyRunnable myRunnable = new MyRunnable();

Thread thread1 = new Thread(myRunnable);

Thread thread2 = new Thread(myRunnable);

thread1.start();

thread2.start();

try {

thread1.join();

thread2.join();

} catch (InterruptedException e) {

System.out.println("Error: " + e.getMessage());

System.out.println("Final count: " + myRunnable.count);

Inter-thread Communication

Inter-thread communication is used to exchange data between threads. In Java, inter-


thread communication is achieved using the wait() and notify() methods.

Here's an example program that demonstrates inter-thread communication:

class MyRunnable implements Runnable {


private boolean isReady = false;

public synchronized void setReady() {

isReady = true;

notify();

public void run() {

synchronized (this) {

while (!isReady) {

try {

wait();

} catch (InterruptedException e) {

System.out.println("Error: " + e.getMessage());

System.out.println("Thread is ready!");

public class InterThreadCommunication {

public static void main(String[] args) {


MyRunnable myRunnable = new MyRunnable();

Thread thread = new Thread(myRunnable);

thread.start();

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

System.out.println("Error: " + e.getMessage());

myRunnable.setReady();

You might also like