Bitwise Learning Java Unit 2
Bitwise Learning Java Unit 2
I T S
E
OBJECT ORIENTED E
G
A R N
N I
T W I
PROGRAMMING WITH JAVA
I S
E
(BCS-403)
G
A R N
N I
Complete Notes
OOPS WITH JAVA (BCS-403)
UNIT 2 - SYLLABUS
T W I
I S
Exception Handling: The Idea behind Exception, Exceptions & Errors, Types of Exception,
E
Control Flow in Exceptions, JVM Reaction to Exceptions, Use of try, catch, finally, throw,
throws in Exception Handling, In-built and User Defined Exceptions, Checked and Un-
Checked Exceptions.
Input /Output Basics: Byte Streams and Character Streams, Reading and Writing File in Java.
L E
G
Multithreading: Thread, Thread Life Cycle,
A Creating N
Threads, Thread Priorities,
R N I
Synchronizing Threads, Inter-thread Communication.
2
OOPS WITH JAVA (BCS-403)
EXCEPTION HANDLING
W Exception
The IdeaTBehind I
I S
In any Java program, there can be three types of errors: Syntax Errors (missing semicolons, caught by
E
compiler), Logical Errors (bugs, wrong formulas, producing incorrect outputs), and Runtime Errors.
Definition: An exception is an unexpected, unwanted, or abnormal event that occurs at runtime
and disrupts the normal flow of program instructions.
The Core Idea: An exception is an unwanted, unexpected, or abnormal event that occurs at runtime
(Runtime Error) and disrupts the normal flow of the program (e.g., dividing by zero, network
G
failure, missing file).
E
Why Handle It? If not handled, the JavaAVirtual MachineN(JVM) abnormally terminates the
R N I
program, meaning subsequent lines of code are never executed. Exception handling provides a
robust mechanism to handle these situations gracefully, allowing the program to either recover or
terminate safely after executing necessary clean-up (like closing files).
3
OOPS WITH JAVA (BCS-403)
EXCEPTION HANDLING
Exceptions
W& Errors
T I S
I
Both are subclasses of the root class [Link], but they represent different severities..
E
Exception: These are manageable conditions that an application can and should catch and recover
from (e.g., NullPointerException, ArithmeticException). They represent application-level issues.
Error: These represent severe, critical problems happening at the system or JVM level that a typical
application cannot catch or recover from (e.g., OutOfMemoryError, StackOverflowError). If an
error occurs, the program must terminate.
Hierarchy Tree
L
G
E
Throwable
A N
├── Error (StackOverflowError, OutOfMemoryError, etc.)
R N I
└── Exception
├── RuntimeException (Unchecked: ArithmeticException, NullPointerException, etc.)
└── IOException, SQLException, etc. (Checked Exceptions) 4
OOPS WITH JAVA (BCS-403)
EXCEPTION HANDLING
5
OOPS WITH JAVA (BCS-403)
EXCEPTION HANDLING
Exceptions
W& Errors
T I S
Types of errors: I
E
Syntax Error: Occurs when the compiler finds something wrong with the structure of the code (e.g.,
missing a semicolon, using an undeclared variable). It is caught at compile time.
Logical Error (Bug): Occurs when a program compiles and runs successfully but produces the
wrong output (e.g., using a + operator instead of *). These are due to algorithmic mistakes by the
programmer.
Runtime Error (Exception): Errors that occur while the program is actually running. These happen
L
G
E
due to circumstances like bad input by the N a number by zero) or resource
A user (e.g., dividing
I
R N
constraints. In Java, runtime errors are called Exceptions.
6
OOPS WITH JAVA (BCS-403)
EXCEPTION HANDLING
Types
T ofW I
Exceptions
I S
Checked Exceptions (Compile-Time Exceptions):
E
Definition: Exceptions that are checked by the compiler at compile-time for the smooth execution of
the program.
Mechanism: The compiler issues a warning and forces the programmer to handle these exceptions
(using try-catch) or declare them (using throws). If not handled, the program will not compile.
Examples: IOException, SQLException, ClassNotFoundException.
Unchecked Exceptions (Run-Time Exceptions):
L
G
E
N and are directly taken care of by the
A by the compiler
Definition: Exceptions that are not checked
JVM at run-time.
R N I
Mechanism: They are direct subclasses of the RuntimeException class. They usually indicate
programming mistakes or logical flaws.
Examples: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException. 7
OOPS WITH JAVA (BCS-403)
EXCEPTION HANDLING
T Win Exceptions
Control Flow I S
I
The control flow dictates how Java moves through the code when an error occurs:
E
1. Normal Flow: Code inside the try block executes line by line.
2. Exception Occurs: If a risky statement throws an exception, the remaining code in the try
block is skipped.
3. Catching: The JVM transfers control to the matching catch block to handle it.
4. Finally: Regardless of whether an exception occurred or was caught, the finally block
L
G
executes. E
A N
R N I
8
OOPS WITH JAVA (BCS-403)
EXCEPTION HANDLING
T W I S
I
E
L
G
E
A N
R N I
9
OOPS WITH JAVA (BCS-403)
EXCEPTION HANDLING
T W I S
Output of previous program I Summary of the Flow
E
Flow Step 1: Program Starts Execution runs normally until 10 / 0 triggers an
Flow Step 2: Entering Try Block exception inside try.
Flow Step 4: Catch Block Executed - / by zero Remaining statements in the try block are skipped.
Flow Step 5: Finally Block Executed Control moves to the matching catch block.
Flow Step 6: Program Ends Gracefully After catch, the finally block executes always.
L
G
E Since the exception is handled, the program
A I N
R N continues with the remaining code.
10
OOPS WITH JAVA (BCS-403)
EXCEPTION HANDLING
T W I
I in ExceptionSHandling
Keywords
Java provides 5 specific keywords to implement exception handling.
E
try:
Whenever we write code that is "error-suspecting" or "risky", we place it inside the try block.
If an exception occurs here, the rest of the code inside the try block is immediately skipped, and
control is transferred to the catch block.
catch:
L
G
E
Its main purpose is to handle the exception object thrown by the try block. It contains the logic to
A N
execute if an exception occurs (like printing aR N I message).
user-friendly
A single try block can be followed by multiple catch blocks to handle different types of exceptions
specifically.
11
OOPS WITH JAVA (BCS-403)
EXCEPTION HANDLING
Keywords in Exception
W Handling
T I S
finally: I
E
It is a block of code that is always executed, regardless of whether an exception occurs, whether it is
caught, or whether it is left uncaught.
Theoretical Purpose: It is primarily used to handle and release system resources (like closing database
connections, closing files, or closing scanner inputs) so they are not permanently blocked.
throw:
It is used to throw an exception explicitly by the programmer.
L
G
E
Instead of waiting for the JVM to generate
I N programmer creates an exception object
A an exception, the
R N
using the new keyword and throws it (often used for Custom/User-Defined Exceptions).
throws:
It is used in the method signature to declare that a method might throw an exception.
Theoretical Purpose: It acts as a warning or indicator to the caller of the method. 12
OOPS WITH JAVA (BCS-403)
T W I S
I
E
L
G
E
A N
R N I
13
OOPS WITH JAVA (BCS-403)
FINALLY KEYWORD
T W I S
I
E
L
G
E
A N
R N I
14
OOPS WITH JAVA (BCS-403)
THROW KEYWORD
T W I S
I
E
L
G
E
A N
R N I
15
OOPS WITH JAVA (BCS-403)
THROWS KEYWORD
T W I S
I
E
L
G
E
A N
R N I
16
OOPS WITH JAVA (BCS-403)
EXCEPTION HANDLING
T W
In-built I S
exception
I
Definition - In-built Exceptions (also known as pre-defined exceptions) are the standard exception
E
classes provided by the Java API, primarily available inside the [Link] package (along with others
like [Link], [Link])
Categories of In-Built Exceptions - divided into two main categories:
Unchecked Exceptions: Most general-purpose exceptions are direct subclasses of the
RuntimeException class. The Java compiler does not force the programmer to declare or handle
G
E E.g. - NullPointerException, ArithmeticException
these explicitly using try-catch blocks.
Checked Exceptions: These are checked A N
I compile-time. You must either handle
by the compiler at
R N
them using a try-catch block or declare them in the method signature using the throws keyword;
otherwise, the program will not compile. E.g. - IOException, SQLException
17
OOPS WITH JAVA (BCS-403)
IN-BUILT EXCEPTION
T W I S
I
E
L
G
E
A N
R N I
18
OOPS WITH JAVA (BCS-403)
IN-BUILT EXCEPTION
T W I S
I
Output of previous program
E
Program Execution Started...
In-Built Exception Caught: Arithmetic Error - Cannot divide by zero.
Finally block executed. Resource cleanup done.
Program Execution Completed Gracefully.
L
G
E
A N
R N I
19
OOPS WITH JAVA (BCS-403)
EXCEPTION HANDLING
User-Defined
W exception
T I S
I
Sometimes, built-in exceptions (like ArithmeticException) do not cover specific business logic
E
scenarios (e.g., throwing an error if a user enters a negative age for voting).
How to create: A user-defined exception is created by defining a new class that extends the
built-in Exception class (for checked) or RuntimeException (for unchecked).
Key Methods: The custom class usually implements a constructor that calls super(message)
to pass a custom error string to the parent Throwable class. Methods like getMessage(),
L
G
E
toString(), and printStackTrace() areAinherited and
I N
used to display the error.
R N
20
OOPS WITH JAVA (BCS-403)
CUSTOM EXCEPTION
T W I S
I
E
Output
Custom Error: Age must be 18+
G
E
A N
R N I
21
OOPS WITH JAVA (BCS-403)
T W I/O
Introduction to Java I and Streams
I S
In Java, Input refers to receiving data from an external source (like a keyboard, a file, or a
E
network), and Output means sending data to an external destination (like a console, a file, or a
network).
Java performs all its I/O operations using the concept of Streams.
What is a Stream? A stream is a logical entity that represents a continuous sequence or flow of
data from a source to a destination.
L
G
E
Analogy: Just as a continuous flow of A N
I water stream, a continuous flow of data
water is called a
R N
is called a data stream.
Package: All classes required for stream manipulation are available in the [Link] package.
22
OOPS WITH JAVA (BCS-403)
W
Byte and Character
T
Streams
I S
The [Link] package divides stream classes intoI two distinct hierarchies based on the type of data they handle:
E
Byte Streams and Character Streams.
A. Byte Streams
Byte streams provide a convenient means for handling the input and output of 8-bit raw binary data
Usage: They are primarily used for reading and writing non-textual data, such as images, audio files,
video files, executable (.exe) files, and zip files.
L
G
E derived from two abstract superclasses:
Base Classes: All byte stream classes are
A I N
R N
InputStream: The superclass for reading byte streams.
OutputStream: The superclass for writing byte streams.
Important Concrete Classes: FileInputStream, FileOutputStream, BufferedInputStream,
BufferedOutputStream. 23
OOPS WITH JAVA (BCS-403)
W I Streams
Byte and TCharacter
I S
B. Character Streams
E
Character streams are designed to handle the input and output of 16-bit Unicode characters.
Usage: They are exclusively used for reading and writing textual data, making them perfect for
handling international text files (.txt, .csv, HTML documents).
Base Classes: All character stream classes are derived from two abstract superclasses:
G
Reader: The superclass for reading character streams.
E
A
Writer: The superclass for writing character I
streams. N
R N
Important Concrete Classes: FileReader, FileWriter, BufferedReader, BufferedWriter.
24
OOPS WITH JAVA (BCS-403)
INPUT / OUTPUT BASICS
E
Handles 16-bit Unicode character
Data Type Handles 8-bit raw binary data
data
G
Suitability E
Best for media: images, audio, video, .exe
.html
A N
R N I
Base Classes InputStream and OutputStream Reader and Writer
E
using stream methods, and then strictly closing the connection using the close() method to release system
resources.
A. Using Byte Streams (FileInputStream & FileOutputStream)
1. Writing to a file (FileOutputStream):
Constructors: FileOutputStream("filePath") (overwrites data) or FileOutputStream("filePath", true)
(appends data).
L
G
E
Key Methods: write(int b), write(byte[] b), flush(), close().N
A I
2. Reading from a file (FileInputStream): R N
Constructors: FileInputStream("filePath").
Key Methods: read() (reads a single byte and returns -1 if End Of File is reached), available() (returns
remaining bytes), skip(n), close(). 26
OOPS WITH JAVA (BCS-403)
T W I S
I
E
Output
Exception Occurred: [Link] (No
such file or directory)
L
G
E
A N
R N I
27
OOPS WITH JAVA (BCS-403)
E
1. Writing to a file (FileWriter):
Constructors: FileWriter("filePath") (overwrites) or FileWriter("filePath", true) (appends).
Key Methods: write(String str), write(char[] cbuf), append(CharSequence), flush(), close(). The
append() method allows chaining (e.g., [Link]("A").append("B"))
2. Reading from a file (FileReader):
L
G
E
Constructors: FileReader("filePath") A N
R N I
Key Methods: read() (reads a single character and returns -1 at EOF), read(char[] buffer), skip(n),
close(). Notice that FileReader does not have an available() method.
28
OOPS WITH JAVA (BCS-403)
T W I S
I
E
Output
Text successfully written to file.
G
E
A NJava I/O is based on Streams.
R N I
Character streams handle 16-bit text.
29
OOPS WITH JAVA (BCS-403)
E
FileInputStream(), read(), write(), close()) can throw a Checked Exception (specifically
IOException or FileNotFoundException). Therefore, they must be enclosed within a try-catch
block or declared with the throws keyword.
2. Resource Cleanup: Releasing a file connection using the close() method is mandatory to prevent
resource leaks. It is a best practice to place the close() calls inside the finally block because finally
L
G
E
A
is guaranteed to execute even if an I/O exception N
crashes
I the try block.
R N
3. End of File (EOF): Both FileInputStream and FileReader use the logic of iterating until the read()
method returns -1, which is the universal indicator that the end of the stream has been reached.
30
OOPS WITH JAVA (BCS-403)
MULTITHREADING
ProcessW
vs. Thread
I
T S
I
To understand multithreading, one must differentiate it from multiprocessing.
E
Process: A program in execution. It is heavyweight and has its own isolated memory space.
Context switching between processes takes a long time. Communication between two processes is
complex.
Thread: A thread is a lightweight sub-process. It is the smallest unit of CPU execution. Multiple
threads belong to the same process and share the same memory space and resources, making
L
G
E
A
context switching and inter-thread communication N
much
I faster and easier.
R N
31
OOPS WITH JAVA (BCS-403)
MULTITHREADING
What is Multithreading
W
T I S
I that allows a single program to execute multiple threads
Definition: Multithreading is a core concept
E
concurrently (at the same time) to maximize CPU utilization.
Independence: Threads are known for independent execution. If one thread is paused or waiting, other
threads continue to execute without dependency.
Real-world Analogy: Think of a large task like building a house. If you divide the task among friends
(one builds the roof, one builds the stairs), they are acting as threads. They work simultaneously
L
G
E
A distinct part.
without waiting for the other to finish their I N
R N
32
OOPS WITH JAVA (BCS-403)
MULTITHREADING
W I in Java
Creating Threads
T
I S
Because Java does not support multiple class inheritance, it provides two distinct ways to create threads:
E
By Extending the Thread Class:
A class inherits from [Link].
The class must override the run() method, which contains the logic/job the thread will execute.
Limitation: Since the class already extends Thread, it cannot inherit from any other class.
By Implementing the Runnable Interface:
L
G
E and overrides its run() method.
A class implements [Link]
A N
N I class and pass your Runnable object into its
R Thread
To start it, you must create an instance of the
constructor.
Advantage: Highly preferred because it leaves the class free to extend another parent class if needed
33
OOPS WITH JAVA (BCS-403)
T W I S
I
E
L
G
E
A N
R N I
34
OOPS WITH JAVA (BCS-403)
T W I S
I
E
L
G
E
A N
R N I
35
OOPS WITH JAVA (BCS-403)
T W I S
I
E
L
G
E
A N
R N I
36
OOPS WITH JAVA (BCS-403)
T W I S
I
E
L
G
E
A N
R N I
37
OOPS WITH JAVA (BCS-403)
MULTITHREADING
ThreadW
Life Cycle
T I S
I 5 specific states managed by the JVM:
During its lifetime, a thread transitions through
E
1. New (Born) State: A thread object is created using new Thread(), but the start() method has not been
called yet.
2. Runnable (Ready) State: The start() method is invoked. The thread is now ready to run and is waiting in a
pool for the Thread Scheduler to allocate CPU time to it.
3. Running State: The Thread Scheduler randomly selects the thread from the ready pool, and it is currently
G
E
executing its run() method on the processor.
A
4. Blocked (Waiting) State: The thread temporarily pauses I N
execution. This happens if it calls sleep(), wait(),
R N
or join(), or if it is waiting to acquire a lock on a synchronized resource.
5. Terminated (Dead) State: The thread has successfully finished executing its run() method, or the stop()
method was forcefully called. A dead thread cannot be restarted.
38
OOPS WITH JAVA (BCS-403)
MULTITHREADING
39
OOPS WITH JAVA (BCS-403)
MULTITHREADING
T W IThreads
Synchronizing S
I
The Problem: When multiple threads try to access the same shared resource at the exact same time, it
E
leads to data inconsistency and corrupted results. For example, if three threads try to simultaneously
withdraw 5000 from a joint bank account that only holds 5000, all three might succeed if not checked
properly, resulting in a negative balance.
The Solution (Synchronization): It is a mechanism to control multiple threads such that only one thread
can access the shared resource at a given time.
L
G
E object has an intrinsic lock (monitor). When a thread enters a
The Monitor (Lock) Concept: In Java, every
A N
N I must wait outside until the first thread finishes
R threads
synchronized area, it acquires this lock. All other
its task and releases the lock
40
OOPS WITH JAVA (BCS-403)
MULTITHREADING
T W I
Synchronizing
I S
Threads
Types of synchronizing thread:
E
Method Level Synchronization: The entire method is locked using the synchronized keyword.
Block Level Synchronization: Only a specific critical block of code within a method is locked
using synchronized(this), which is more efficient.
G
E
A N
R N I
41
OOPS WITH JAVA (BCS-403)
T W I S
I
E
L
G
E
A N
R N I
42
OOPS WITH JAVA (BCS-403)
T W I S
I
E
L
G
E
A N
R N I
43
OOPS WITH JAVA (BCS-403)
T W I S
I
Output for previous code
E
FIRST THREAD Start
FIRST THREAD data = 10
FIRST THREAD End
SECOND THREAD Start
L
G
SECOND THREAD data = 10 E
A N
SECOND THREAD End R N I
44
OOPS WITH JAVA (BCS-403)
T W I S
I
E
L
G
E
A N
R N I
45
OOPS WITH JAVA (BCS-403)
T W I S
I
E
L
G
E
A N
R N I
46
OOPS WITH JAVA (BCS-403)
T W I S
I
Output for previous code
E
FIRST THREAD Start
FIRST THREAD data = 10
FIRST THREAD End
SECOND THREAD Start
L
G
SECOND THREAD data = 10 E
A N
SECOND THREAD End R N I
47
OOPS WITH JAVA (BCS-403)
MULTITHREADING
Inter-threadW
communication
T I S
Definition: Inter-thread communication isIa mechanism where two synchronized threads communicate
E
with each other. It is used when one thread needs to pause its execution and hand over the lock to
another thread to complete a prerequisite task.
Classic Example (Producer-Consumer): A Producer thread creates an item and puts it in a buffer. If the
buffer is full, it must wait(). A Consumer thread takes the item. If the buffer is empty, it must wait(). Once
the Consumer takes an item, it notify()s the Producer to create more
L
G
E
A N
Key Methods (from Object class):
R N I
wait(): Forces the current thread to release its lock and go to a waiting/paused state.
notify(): Wakes up a single thread that is waiting for the lock on that specific object.
notifyAll(): Wakes up all threads waiting for the lock. 48
OOPS WITH JAVA (BCS-403)
Synchronizing Threads
T W I S
I
E
L
G
E
A N
R N I
49
OOPS WITH JAVA (BCS-403)
Synchronizing Threads
T W I S
I
E
L
G
E
A N
R N I
50
OOPS WITH JAVA (BCS-403)
Synchronizing Threads
T W I S
I
E
L
G
E
A N
R N I
51
OOPS WITH JAVA (BCS-403)
Synchronizing Threads
T W I S
I
E
L
G
E
A N
R N I
52
OOPS WITH JAVA (BCS-403)
Synchronizing Threads
T W I S
I
E
L
G
E
A N
R N I
53
OOPS WITH JAVA (BCS-403)
T W I S
Output for
I previous code
E
Mother puts a toffee in the container.
Son takes the toffee from the container.
Mother puts a toffee in the container.
Son takes the toffee from the container.
Mother puts a toffee in the container.
L
G
Son takes the
E toffee from the container.
A N
R N inI the container.
Mother puts a toffee
Son takes the toffee from the container.
Mother puts a toffee in the container.
Son takes the toffee from the container.
54
T W I S
I
E
L
G
E
A N
R N I
55