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

Oopjava Unit III

The document discusses error and exception handling in Java, highlighting the differences between errors, which are irrecoverable, and exceptions, which can be caught and handled. It explains the hierarchy of exception classes, methods for printing exception information, and the process of custom exception handling using keywords like try, catch, and finally. Additionally, it covers Java I/O streams, including byte and character streams, and introduces serialization and deserialization for object state management.

Uploaded by

classgattapugari
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)
9 views

Oopjava Unit III

The document discusses error and exception handling in Java, highlighting the differences between errors, which are irrecoverable, and exceptions, which can be caught and handled. It explains the hierarchy of exception classes, methods for printing exception information, and the process of custom exception handling using keywords like try, catch, and finally. Additionally, it covers Java I/O streams, including byte and character streams, and introduces serialization and deserialization for object state management.

Uploaded by

classgattapugari
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/ 58

Object Oriented Programming Through JAVA

By
Dr. Srikanth Lakumarapu
Associate Professor
Dept. Of CSE
CVR COLLEE OF ENGINEERING
Error
Errors represent irrecoverable conditions such as Java virtual machine (JVM)
running out of memory, memory leaks, stack overflow errors, library
incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer, and we should not try
to handle errors.
Exception Handling
• Exception is an unwanted or unexpected event, which occurs during the
execution of a program, i.e. at run time, that disrupts the normal flow of the
program’s instructions.
• Exceptions can be caught and handled by the program. When an exception
occurs within a method, it creates an object.
• This object is called the exception object.
• It contains information about the exception, such as the name and description
of the exception and the state of the program when the exception occurred.
Exception Handling
Major reasons why an exception Occurs
• Invalid user input
• Device failure
• Loss of network connection
• Physical limitations (out-of-disk memory)
• Code errors
• Out of bound
• Null reference
• Type mismatch
• Opening an unavailable file
• Database errors
• Arithmetic errors
Types of Exceptions
Exception class Hierarchy
Methods to print the Exception
information
1. printStackTrace():
• This method prints exception information in the format of the Name of the
exception: description of the exception, stack trace.
2. toString()
• The toString() method prints exception information in the format of the Name
of the exception: description of the exception.
• 3. getMessage()
• The getMessage() method prints only the description of the exception.
Default Exception Handling
• Exception Handling automatically done by Java Runtime Environment is called
Default Exception Handling. It can be done in the following way:
• Whenever inside a method, if an exception has occurred, the method creates an
Object known as an Exception Object and hands it off to the run-time
system(JVM).
• Creating the Exception Object and handling it in the run-time system is called
throwing an Exception.
• The run-time system searches for the appropriate handler, if it not found then
the run-time system handover the Exception Object to the default exception
handler, which is part of the run-time system.
• This handler prints the exception information and terminates the
program abnormally.
Default Exception Handling
Custom Exception Handling
• Exception handling done by the user is called custom exception handling.
• It can be done in java by using these keywords- try, catch, throw, throws,
and finally.
• Program statements that you think can raise exceptions are contained within a try
block.
• If an exception occurs within the try block, it is thrown. System-generated exceptions
are automatically thrown by the Java run-time system. To manually throw an
exception, use the keyword throw.
• Your code can catch this exception (using catch block) and handle it in some rational
manner.
• Any exception that is thrown out of a method must be specified as such by a throws
clause.
• Any code that absolutely must be executed after a try block completes is put in a
finally block.
Summery of Exception Handling
User Defined Exception
• Creating our own Exception is known as a custom exception or
user-defined exception.
1. Define the Custom Exception class by extending the
Exception Class or RuntimeException class
• Provide constructors to initialize the exception with messages or causes.
2. Throw the Custom Exception
3`. Catch the Custom Exception
Built in Packages
Built in Packages
I/O STREAMS
• Java I/O (Input and Output) is used to process the input and produce the output.
• Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
• A stream is a sequence of data. In Java, a stream is composed of bytes.
• In Java, 3 standered streams are available. All these streams are attached with the
console.
• 1) System.in: This is the standard input stream that is used to read characters from
the keyboard or any other standard input device.
• 2) System.out: This is the standard output stream that is used to produce the result
of a program on an output device like the computer screen.
• 3) System.err: This is the standard error stream that is used to output all the error
data that a program might throw, on a computer screen or any standard output device.
TYPES OF STREAMS BASED ON FILE
Depending on the types of file, Streams can be divided into two primary classes
1. Byte Stream: This is used to process data byte by byte (8 bits).
• Byte streams in Java are used for handling raw binary data. They provide a way
to read and write bytes, which makes them suitable for various types of files,
including images, audio files, and other binary formats.
1. Character Stream: Character streams handle text data and read/write data
in characters. They use Unicode, making them suitable for
internationalization.
• Ideal for reading and writing text files or string data, ensuring proper encoding
and decoding of characters.
TYPES OF STREAMS BASED ON FILE
TYPES I/O STREAMS
1. Input Stream: These streams are used to read data that must be taken as an
input from a source array or file or any peripheral device. For eg.,
FileInputStream, BufferedInputStream, ByteArrayInputStream etc.
2. Output Stream: These streams are used to write data as outputs into an array
or file or any output peripheral device. For eg., FileOutputStream,
BufferedOutputStream, ByteArrayOutputStream etc.
Input Stream classes hierarchy
InputStream class
Java InputStream class is the superclass of all the io classes i.e. representing an
input stream of bytes.
It is an abstract class.
Declaration:
public abstract class InputStream extends Object implements Closeable
{ }
Methods of InputStream class:
int read(): Reads the next byte of data from the input stream. Returns the byte as
an integer in the range 0 to 255 or -1 if the end of the stream is reached.
int read(byte[] b): Reads some number of bytes from the input stream and stores
them into the specified byte array. Returns the total number of bytes read into the
buffer, or -1 if the end of the stream has been reached.
InputStream class
int read(byte[] b, int off, int len): Reads up to len bytes of data from the input
stream into an array of bytes starting at the specified offset off. Returns the
number of bytes read or -1 if the end of the stream has been reached.
int available(): Returns an estimate of the number of bytes that can be read from
the input stream without blocking.
void mark(int readlimit): Marks the current position in the input stream.
Subsequent calls to the reset() method will reposition the stream to this marked
location as long as the number of bytes read does not exceed readlimit.
void close(): Closes the input stream and releases any system resources
associated with it.
long skip(long n): void reset(): boolean markSupported(): long skip(long n):
Output Stream classes hierarchy
OutputStream class
OutputStream class is an abstract class.
It is the superclass of all classes representing an output stream of bytes.
An output stream accepts output bytes and sends them to some sink.
Methods of OutputStream class
void write(int b): Writes the specified byte to this output stream.
void write(byte[] b): Writes b.length bytes from the specified byte array to
this output stream.
void write(byte[] b, int off, int len): Writes len bytes from the specified byte
array starting at offset off to this output stream.
void flush(): Flushes the output stream and forces any buffered output bytes
to be written out.
void close(): Closes the output stream and releases any system resources
associated with it.
FileInputStream class
FileInputStream class provide mechanism to read byte streams from a file.
It provides a convenient way to read data from files in a binary format.
Constructors:
FileInputStream(String name): Creates a FileInputStream by opening a connection to
an actual file, using the file's pathname.
FileInputStream(File file): Creates a FileInputStream from a File object.
Methods:
int read(): Reads the next byte of data from the input stream and returns it as an
integer.
int read(byte[] b): Reads a certain number of bytes from the input stream into an
array of bytes.
int read(byte[] b, int off, int len): Reads up to len bytes of data from the input stream
into an array of bytes, starting at the specified offset.
void close(): Closes the input stream and releases any system resources associated
with it.
FileInputStream class
import java.io.FileInputStream;

import java.io.IOException;

public class FileInputStreamExample {

public static void main(String[] args) {

FileInputStream fis = null;

try {

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

int data;

while ((data = fis.read()) != -1) {

// Cast the byte to char and print it

System.out.print((char) data);

} catch (IOException e) {

e.printStackTrace();

} finally {

// Close the stream to free resources

if (fis != null) {

try {

fis.close();

} catch (IOException e) {

e.printStackTrace();

}
FileOutputStream class
The FileOutputStream class in Java, part of the java.io package, is used to write
byte streams to a file.
It is particularly useful for writing binary data, such as images or other
non-text files.
As a subclass of OutputStream, it provides methods for writing bytes to the
output stream.
Constructor:
FileOutputStream(String name): Creates a FileOutputStream to write to the
file specified by the pathname.
FileOutputStream(File file): Creates a FileOutputStream from a File object.
FileOutputStream(String name, boolean append): Creates a
FileOutputStream to write to the file with the option to append to the existing
content.
FileOutputStream class
Methods:
void write(int b): Writes the specified byte to the output stream.
void write(byte[] b): Writes the entire byte array to the output stream.
void write(byte[] b, int off, int len): Writes a portion of a byte array,
starting at the specified offset and writing len bytes.
void flush(): Flushes the output stream, forcing any buffered output
bytes to be written out.
void close(): Closes the output stream and releases any system
resources associated with it.
FileOutputStream class
import java.io.FileOutputStream;

import java.io.IOException;

public class FileOutputStreamExample {

public static void main(String[] args) {

FileOutputStream fos = null;

try {

// Create a FileOutputStream to write to example.txt

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

String data = "Hello, World!\nThis is an example of FileOutputStream.";

// Convert the string to a byte array and write it to the file

fos.write(data.getBytes());

// Optionally, flush the stream to ensure all data is written

fos.flush();

} catch (IOException e) {

e.printStackTrace();

} finally {

// Close the stream to free resources

if (fos != null) {

try {

fos.close();

} catch (IOException e) {

e.printStackTrace();

}
ByteArrayInputStream class
The `ByteArrayInputStream` class in Java, part of the `java.io` package,
allows an application to create an input stream from a byte array.
This is useful when you want to read data from a byte array as if it were
an input stream, making it easy to process data in memory.
As Subclass of InputStream it Inherits methods from `InputStream`,
making it easy to read data using standard input stream operations.
Constructors:
1. ByteArrayInputStream(byte[] buf): Creates a
`ByteArrayInputStream` initialized with the specified byte array.
2. ByteArrayInputStream(byte[] buf, int offset, int length): Creates a
`ByteArrayInputStream` with a specified portion of the byte array,
allowing you to specify an offset and the number of bytes to read.
ByteArrayInputStream class
Basic Methods:
int read(): Reads the next byte of data from the input stream and returns
it as an integer.
int read(byte[] b): Reads bytes into the specified byte array.
int read(byte[] b, int off, int len): Reads up to `len` bytes into the
specified byte array, starting at the given offset.
int available(): Returns the number of bytes that can be read without
blocking.
void mark(int readlimit): Marks the current position in the stream.
void reset(): Resets the stream to the most recent mark.
void close(): Closes the stream (no effect since it's memory-based).
ByteArrayOutputStream class
The `ByteArrayOutputStream` class in Java, part of the `java.io` package,
is used to write data to a byte array in memory.
It provides an easy way to collect output data and manipulate it as a
byte array without need of file I/O.
This is particularly useful for scenarios where you want to construct byte
arrays dynamically.
Data written to a `ByteArrayOutputStream` is stored in a byte array in
memory.
The underlying byte array grows automatically as you write more data
than its current capacity.
ByteArrayOutputStream class
Constructors:

1. ByteArrayOutputStream(): Creates a new `ByteArrayOutputStream`


with an initial buffer size of 32 bytes.

2. ByteArrayOutputStream(int size): Creates a new


`ByteArrayOutputStream` with a specified initial buffer size.
ByteArrayOutputStream class
Basic Methods:
void write(int b): void write(byte[] b):
void write(byte[] b, int off, int len):
byte[] toByteArray(): Converts the contents of the output stream to a
byte array.
int size(): Returns the current size (number of bytes written) of the
output stream.
void reset(): Resets the output stream so that all currently accumulated
output is discarded.
void close(): Closes the stream (no effect since it's memory-based).
Serialization & Deserialization
Serialization & Deserialization
Serialization is a mechanism of converting the state of an object into a byte
stream.
Deserialization is the reverse process where the byte stream is used to recreate
the actual Java object in memory.
The byte stream created is platform independent.
So, the object serialized on one platform can be deserialized on a different
platform.
To make a Java object serializable,the class need to implement
the java.io.Serializable interface.
Serializable is a marker interface (has no data member and method).
It is used to “mark” java classes so that objects of these classes may get certain
capability.
Advantages of Serialization
• To save/persist state of an object. To travel an object across a network.
SerialVersionUID: The Serialization runtime associates a version number with
each Serializable class called a SerialVersionUID.
This is used during Deserialization to verify that sender and receiver of a
serialized object have loaded classes for that object which are compatible with
respect to serialization.
If the receiver has loaded a class for the object that has different UID than that
of corresponding sender’s class, the Deserialization will result in
an InvalidClassException.
A Serializable class can declare its own UID explicitly by declaring a field name.
It must be static, final and of type long.
Ex: ANY-ACCESS-MODIFIER static final long serialVersionUID=42L;
Important Points
Points to remember
1. If a parent class has implemented Serializable interface then child class
doesn’t need to implement it but vice-versa is not true.
2. Only non-static data members are saved via Serialization process.
3. Static data members and transient data members are not saved via
Serialization process. So, if you don’t want to save value of a non-static data
member then make it transient.
4. Constructor of object is never called when an object is deserialized.
5. Associated objects must be implementing Serializable interface.
ObjectOutputStream
The `ObjectOutputStream` class is used to serialize objects, which
means converting them into a byte stream for storage or transmission.
This byte stream can later be deserialized back into an object using
`ObjectInputStream`.
Custom Serialization: You can customize the serialization process by
implementing the `writeObject` method.
Constructor:
ObjectOutputStream(OutputStream out)
ObjectOutputStream
writeObject(Object obj): Serializes the specified object to the output
stream.
writeInt(int v), writeFloat(float v), etc.: Methods for writing primitive data
types.

defaultWriteObject(): Used in the `writeObject()` method to write the


non-static and non-transient fields of the class.
ObjectIntputStream
The `ObjectInputStream` class is used to deserialize objects that have
been serialized using the `ObjectOutputStream`.
This means it can read data from a stream and convert it back into
objects, allowing you to retrieve the state of an object that was
previously saved.
Deserialization: Converts a stream of bytes back into a Java object.
Supports reading objects of specific types based on their class.
Constructor:
ObjectInputStream(InputStream in)
ObjectIntputStream
Common Methods
readObject(): Reads an object from the stream. This is the primary
method to use for deserialization.
readInt(), readFloat(), etc are the methods used to read primitive data
types from the stream.
Syntax:
public final Object readObject() throws IOException,
ClassNotFoundException
defaultReadObject(): Used in the `readObject()` method to read the
non-static and non-transient fields of the class.
BufferedOutputStream
The `BufferedOutputStream` class in Java is part of the `java.io` package.
It is used to wrap an output stream to provide buffering capabilities.
It maintains an internal buffer, which means that data is written to the
buffer first, and only when the buffer is full (or when you explicitly flush
it) is the data sent to the underlying output stream.
This helps improve the efficiency of writing data to the underlying output
stream by reducing the number of I/O operations.
Common Constructors:
BufferedOutputStream(OutputStream out)
BufferedOutputStream(OutputStream out, int size)
BufferedOutputStream
Common Methods:
void write(int b): Writes a single byte to the buffered output stream.
void write(byte[] b): Writes an array of bytes.
void write(byte[] b, int off, int len): Writes a specified number of bytes
from a byte array.
void flush(): Flushes the stream, ensuring that all buffered data is written
out.
void close(): Closes the stream and releases any system resources
associated with it.
BufferedInputStream
The `BufferedInputStream` class in Java is part of the `java.io` package.
This provides buffering for input streams.
BufferedInputStream` reads data into a buffer first, allowing you to read
multiple bytes at once rather than making frequent calls to the
underlying stream.
This enhances the efficiency of reading data from an underlying input
stream by reducing the number of I/O operations, which can be relatively
slow.
Common Constructors:
BufferedInputStream(InputStream in)
BufferedInputStream(InputStream in, int size)
BufferedInputStream
Common Methods:
int read() : Reads a single byte of data and returns it as an integer.
int read(byte[] b): Reads bytes into an array and returns the number of
bytes read.
int read(byte[] b, int off, int len) : Reads a specified number of bytes into
a byte array from a specific offset.
void close(): Closes the stream and releases any resources associated
with it.
int available() : Returns the number of bytes that can be read without
blocking.
Character Streams
• Character streams are essential for handling text in Java.
• They provide a convenient and efficient way to read and write character data,
making them a fundamental part of Java I/O operations.
• In Java, a Character Stream is a type of stream that is used to handle the input
and output of characters, which makes it suitable for reading and writing text
data.
• Unlike byte streams that deal with raw binary data, character streams operate
on the character encoding (like UTF-8, ASCII, etc.), allowing for proper
handling of text data, including international characters.
• Reader and Writer classes of java.io package are useful to handle character
streams.
Reader
Writer
Scanner class
• The `Scanner` class in Java is a part of the `java.util` package.
• It is used for reading input from various sources like keyboard input, files, and
streams.
• It provides methods to parse primitive types and strings using regular
expressions.
• It is commonly used for reading user input from the console.
• Constructors of the Scanner Class:
1. Scanner(InputStream source): Creates a `Scanner` that reads from the
specified input stream (e.g., `System.in`).
2. Scanner(File source): Creates a `Scanner` that reads from the specified file.
Ex: File file = new File("input.txt");
Scanner class constructors
3. Scanner(String source): Creates a `Scanner` that reads from the specified
string.
• Ex: String input = "Hello World"; Scanner scanner = new Scanner(input);
4. Scanner(Readable source): Creates a `Scanner` that reads from any object that
implements the `Readable` interface.
Ex: StringReader stringReader = new StringReader("Hello World");
• Scanner scanner = new Scanner(stringReader);
5. Scanner(InputStream source, String charsetName):Creates a `Scanner` that
reads from the specified input stream using the specified charset.
• Ex:Scanner scanner = new Scanner(System.in, "UTF-8");
Scanner class Methods
1. next(): Reads the next token as a string.
2. nextInt(): Reads the next integer.
3. nextDouble(): Reads the next double.
4. nextLine()`: Reads the next line of input as a string.
5. hasNext(), hasNextInt(), hasNextDouble(): These methods check if there are
more tokens available.
Delimiters: By default, the `Scanner` class uses whitespace as the delimiter, but
you can change it using the `useDelimiter()` method.
File Class in java
The File class in Java, part of the java.io package.
It file and directory pathnames in an abstract manner.
It provides methods to create, delete, and inspect files and directories.
However, it does not directly provide methods to read or write file contents; for that,
you typically use classes like FileReader, FileWriter, BufferedReader, and
BufferedWriter.
Key Features of the File Class:
File Representation: Represents both files and directories.
Path Manipulation: Provides methods to get file paths, names, and parent directories.
File Operations: Allows you to create, delete, and check for file existence.
Directory Operations: Provides methods to list files in a directory and check if a path is
a directory.
File Permissions: You can check and set read, write, and execute permissions for files.
File Class constructors
File(String pathname): Creates a File instance from a string path.
File(String parent, String child): Creates a File instance from a parent path and a
child path.
File(File parent, String child): Creates a File instance from a parent File and a
child path.
File Class Mehods
boolean createNewFile(): Creates a new file if it does not exist.
boolean delete(): Deletes the file or directory.
boolean exists(): Checks if the file or directory exists.
boolean isFile(): Checks if it is a file.
boolean isDirectory(): Checks if it is a directory.
String getName(): Returns the name of the file or directory.
String getAbsolutePath(): Returns the absolute path.
String getPath(): Returns the path as a string.
long length(): Returns the length of the file in bytes.
File Class Mehods
Directory Operations:
String[] list(): Returns an array of strings naming the files in the directory.
File[] listFiles(): Returns an array of File objects representing the files in the
directory.
Permissions:
boolean canRead(): Checks if the file is readable.
boolean canWrite(): Checks if the file is writable.
boolean canExecute(): Checks if the file is executable.
boolean setReadOnly(): Sets the file to read-only.
Console Class
The Console class in Java is part of the java.io package and is used for console
input and output operations.
It's important to note that the Console class does not have any public
constructors; you get an instance of it through the static System.console()
method.
Key Methods of the Console Class:
1. readLine(): Reads a single line of text from the console.
Ex: String line = console.readLine();
String lineWithPrompt = console.readLine("Enter something: ");
Console Class
2. readPassword(): Reads a password or sensitive information from the console
without echoing it.
Ex: char[] password = console.readPassword();
char[] passwordWithPrompt = console.readPassword("Enter your password: ");
3. printf(): Writes formatted output to the console, similar to System.out.printf().
Ex: console.printf("Formatted output: %s%n", value);
4. format(): Writes formatted output to the console using a format string.
Ex: console.format("Formatted output: %s%n", value);
5. writer(): Returns the PrintWriter object associated with the console.
Ex: PrintWriter writer = console.writer();
writer.println("Hello, World!");
Console Class
2. readPassword(): Reads a password or sensitive information from the console
without echoing it.
Ex: char[] password = console.readPassword();
char[] passwordWithPrompt = console.readPassword("Enter your password: ");
3. printf(): Writes formatted output to the console, similar to System.out.printf().
Ex: console.printf("Formatted output: %s%n", value);
4. format(): Writes formatted output to the console using a format string.
Ex: console.format("Formatted output: %s%n", value);
5. writer(): Returns the PrintWriter object associated with the console.
Ex: PrintWriter writer = console.writer();
writer.println("Hello, World!");

You might also like