Unit 3
Unit 3
Unit 3
Error vs Exception
•Error: An Error indicates serious problem that a reasonable application should not try to
catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.
Exception Hierarchy
• All exception and errors types are sub classes
of class Throwable, which is base class of
hierarchy.One branch is headed by Exception.
• This class is used for exceptional conditions
that user programs should catch.
NullPointerException is an example of such an
exception.Another branch,Error are used by
the Java run-time system(JVM) to indicate
errors having to do with the run-time
environment itself(JRE).
• StackOverflowError is an example of such an
error.
Types of Java Exceptions
• There are mainly two types of exceptions: checked and unchecked. Here, an error is
considered as the unchecked exception. According to Oracle, there are three types of
exceptions:
• Checked Exception
• Unchecked Exception
• Error
Difference between Checked and Unchecked Exceptions
1) Checked Exception
•The classes which directly inherit Throwable class except RuntimeException and Error are
known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are
checked at compile-time.
2) Unchecked Exception
•The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
•Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Java Exception Keywords
Keyword Description
try The "try" keyword is used to specify a block where we should place exception
code. The try block must be followed by either catch or finally. It means, we can't
use try block alone.
catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by finally
block later.
finally The "finally" block is used to execute the important code of the program. It is
executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It doesn't throw an
exception. It specifies that there may occur an exception in the method. It is
always used with method signature.
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They are as follows:
1.int a=50/0;//ArithmeticException
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
1.String s=null;
2.System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
The wrong formatting of any value may occur NumberFormatException. Suppose I have a string variable
that has characters, converting this variable into digit will occur NumberFormatException.
1.String s="abc";
2.int i=Integer.parseInt(s);//NumberFormatException
If you are inserting any value in the wrong index, it would result in ArrayIndexOutOfBoundsException
as shown below:
• Java catch block is used to handle the Exception by declaring the type of exception within the
parameter.
• The declared exception must be the parent class exception ( i.e., Exception) or the generated
exception type.
• However, the good approach is to declare the generated type of exception.
• The catch block must be used after the try block only.
• Multiple catch blocks can be used with a single try block.
Problem without exception handling
int data=100/0;
System.out.println("rest of the code..");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at exce.main(exce.java:6)
Solution by exception handling
Output:
public class exce java.lang.ArithmeticException: / by zero
{ rest of the code..
public static void main(String args[])
{
try
{
int data=100/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code..");
}
}
An example to print a custom message on exception.
• But if exception is handled by the application programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
Example 2: Keep the code in a try block that will not throw an exception.
public class exce
{
OUTPUT
public static void main(String args[])
{
Can't divide by zero
try
{
int data=100/0;
System.out.println("rest of the code..");
}
catch(ArithmeticException e)
{
System.out.println("Can't divide by
zero");
}
}
}
Example 3: We handle the exception using the parent class exception.
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("rest of the code..");
}
}
Example 4: example to resolve the exception in a catch block.
}
catch(Exception e)
{
System.out.println(i/(j+2));
}
System.out.println("rest of the code..");
}
}
Example 5: along with try block, we also enclose exception code in a catch block.
}
catch(Exception e)
{
int data1=50/0;
}
System.out.println("rest of the code..");
}
}
Example 6: to handle another unchecked exception.
try java.lang.ArrayIndexOutOfBoundsException: 10
{ rest of the code..
int data[]={1,2,3,4,5};
System.out.println(data[10]);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("rest of the code..");
}
}
Example 7: To handle checked exception
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class exce
{
public static void main(String args[])
{
PrintWriter pw; OUTPUT:
}
catch(FileNotFoundException e)
{
System.out.println(e);
}
System.out.println("File Saved Successfully");
}
}
Types of Exception in Java with Examples
Types of Exception in Java with Examples
Java defines several types of exceptions that relate to its various class libraries. Java also allows users to
define their own exceptions.
Built-in exceptions
Built-in exceptions are the exceptions which are available in Java libraries. These exceptions are suitable to explain certain
error situations. Below is the list of important built-in exceptions in Java.
ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic operation.
ArrayIndexOutOfBoundsException
It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative
or greater than or equal to the size of the array.
ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found.
FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
IOException
It is thrown when an input-output operation failed or interrupted
InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it is interrupted.
NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
NoSuchMethodException
It is thrown when accessing a method which is not found.
NullPointerException
This exception is raised when referring to the members of a null object. Null represents nothing.
NumberFormatException
This exception is raised when a method could not convert a string into a numeric format.
RuntimeException
This represents any exception which occurs during runtime.
StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative or greater than the size of the
string.
Example 1: ArithmeticException
class exce {
public static void main(String args[])
{
try {
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5 OUTPUT
} Array Index is Out Of Bounds
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index is Out Of Bounds");
}
}
}
Example : ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found.
class Bishal
OUTPUT:
{
exce.java:13: error: unreported exception
}
ClassNotFoundException; must be caught or declared to be
class Geeks
thrown
{
Object o = Class.forName(args[0]).newInstance();
^
}
exce.java:13: error: unreported exception InstantiationException;
class exce
must be caught or declared to be thrown
{
Object o = Class.forName(args[0]).newInstance();
public static void main(String[] args)
{
Object o = Class.forName(args[0]).newInstance();
System.out.println("Class created for" + o.getClass().getName());
}
}
FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {
Output:
public static void main(String args[]) File does not exist
{
try {
class Geeks {
public static void main(String args[])
{
Thread t = new Thread();
t.sleep(10000);
}
}
Output:
This exception is raised when referring to the members of a null object. Null represents nothing
class NullPointer_Demo {
public static void main(String args[]) Output:
{ NullPointerException..
try {
String a = null; // null value
System.out.println(a.charAt(0));
}
catch (NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}
NumberFormatException :
This exception is raised when a method could not convert a string into a numeric format.
class NumberFormat_Demo {
public static void main(String args[])
Output:
{
Number format exception
try {
// "akki" is not a number
int num = Integer.parseInt("akki");
System.out.println(num);
}
catch (NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
StringIndexOutOfBoundsException : It is thrown by String class methods to indicate that an index is either
negative than the size of the string.
class StringIndexOutOfBound_Demo {
public static void main(String args[])
{
try { Output:
StringIndexOutOfBoundsException
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch (StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}
User-Defined Exceptions
•User Defined Exception or custom exception is creating your own exception class and throws that exception using ‘throw’
keyword. This can be done by extending the class Exception.
•The user should create an exception class as a subclass of Exception class. Since all the exceptions are subclasses of
Exception class, the user should also make his class a subclass of it.
•This is done as:
MyException(){}
• We can also create a parameterized constructor with a string as a parameter.
• We can use this to store exception details.
• We can call super class(Exception) constructor from this and send the string there.
MyException(String str)
{
super(str);
}
•To raise exception of user-defined type, we need to create an object to his exception class and throw it using throw clause,
as:
•The following program illustrates how to create own exception class MyException.
•Details of account numbers, customer names, and balance amounts are taken in the form of three arrays.
•In main() method, the details are displayed using a for-loop. At this time, check is done if in any account the balance amount
is less than the minimum balance amount to be apt in the account.
•If it is so, then MyException is raised and a message is displayed “Balance amount is less”.
class JavaException{
public static void main(String args[]){
try{
throw new MyException(2);
// throw is used to create a new exception and throw it.
}
catch(MyException e){
System.out.println(e) ;
}
}
}
class MyException extends Exception{ NOTE:
int a; The keyword “throw” is used to create a new Exception and
MyException(int b) { throw it to the catch block.
a=b;
}
public String toString(){
return ("Exception Number = "+a) ;
}
}
STACK TRACE ELEMENT
Stack
• The stack is a linear data structure that is used to store the collection of objects. It is based on
Last-In-First-Out (LIFO). The push operation inserts an element into the stack and pop
operation removes an element from the top of the stack. Let's see how they work on stack.
Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the stack.
Let's remove (pop) 18, 45, and 11 from the stack.
Empty Stack: If the stack has no element is known as an empty stack. When the stack
is empty the value of the top variable is -1.
When we push an element into the stack the top is increased by 1. In the following
figure,
•Push 12, top=0
•Push 6, top=1
•Push 9, top=2
When we pop an element from the stack the value of top is decreased by 1. In the following
figure, we have popped 9.
The following table shows the different values of the top.
What’s a Java Stack Trace?
• A stack trace, also called a stack backtrace or even just a backtrace, is a list of stack
frames.
• These frames represent a moment during an application’s execution.
• A stack frame is information about a method or function that your code called.
• So the Java stack trace is a list of frames that starts at the current method and extends to
when the program started.
• Sometimes there’s confusion between a stack and the Stack.
• A stack is a data structure that acts as a stack of papers on your desk: it’s first-in-last-out.
• You add documents to the pile and take them off in the reverse order you put them there.
• The Stack, more accurately called the runtime or call stack, is a set of stack frames a
program creates as it executes, organized in a stack data structure.
Java Stack Trace
Example
This class calls four methods and prints a stack trace to the console from the last one.
• The d() method() is at the top of the stack because that’s where the app generated the trace.
• The main() method is at the bottom because that’s where the program started.
• When the program started, the Java runtime executed the main() method. Main() called a().
• A() called b(), and b() called c(), which called d().
• Finally, d() called dumpStack(), which generated the output.
• This Java stack trace gives us a picture of what the program did, in the order that it did it.
• A Java stack trace is a snapshot of a moment in time.
• You can see where your application was and how it got there.
• That’s valuable insight that you can use a few different ways.
Java.lang.StackTraceElement class in Java
• An element in a stack trace, as returned by Throwable.getStackTrace().
• Each element represents a single stack frame.
• All stack frames except for the one at the top of the stack represent a method invocation.
• The frame at the top of the stack represents the execution point at which the stack trace was
generated.
This class describes single stack frame, which is an individual element of a stack trace when an
exception occur.
• All stack frames except for the one at the top of the stack represent a method invocation.
• The frame at the top of the stack represent the execution point of which the stack trace was
generated.
• Each stack frame represents an execution point, which includes such things as the name of
the method, the name of file and the source code line number.
• An array of StackTraceElement is returned by getStackTrace()
method of the Throwable class.
Constructor: Creates a stack trace element representing the specified execution point.
Parameters:
•declaringClass – the fully qualified name of the class containing the execution point represented
by the stack trace element.
•methodName – the name of the method containing the execution point represented by the stack
trace element.
•fileName – the name of the file containing the execution point represented by the stack trace
element, or null if this information is unavailable
•lineNumber – the line number of the source line containing the execution point represented by
this stack trace element, or a negative number if this information is unavailable. A value of -2
indicates that the method containing the execution point is a native method.
4 int getLineNumber()
This method returns the line number of the source line containing the execution point represented by this stack trace
element.
5 String getMethodName()
This method returns the name of the method containing the execution point represented by this stack trace element.
6 int hashCode()
This method returns a hash code value for this stack trace element.
7 boolean isNativeMethod()
This method returns true if the method containing the execution point represented by this stack trace element is a native
method.
8 String toString()
This method returns a string representation of this stack trace element.
boolean equals(ob):
Returns try if the invoking StackTraceElement is as the one passed in ob.
Otherwise it returns false.
Syntax:
public boolean equals(ob)
Returns: true if the specified object is another StackTraceElement instance representing the same
execution point as this instance.
Exception: NA
import java.lang.*;
Output:
import java.io.*;
import java.util.*; true
public class StackTraceElementDemo
{
public static void main(String[] arg)
{
StackTraceElement st1 = new StackTraceElement("foo", "fuction1", "StackTrace.java", 1);
StackTraceElement st2 = new StackTraceElement("bar", "function2","StackTrace.java", 1);
Object ob = st1.getFileName();
import java.lang.*;
Output:
import java.io.*;
import java.util.*; file name: Thread.java
public class StackTraceElementDemo StackTraceElementDemo.java
{
public static void main(String[] arg)
{
System.out.println("file name: ");
for(int i = 0; i<2; i++)
System.out.println(Thread.currentThread().getStackTrace()[i].
getFileName());
}
}
int getLineNumber():
Returns the source-code line number of the execution point described by the invoking StackTraceElement. In
some situation the line number will not be available, in which case a negative value is returned.
Syntax: public int getLineNumber().
Returns: the line number of the source line containing the execution point represented by this stack trace element,
or a negative number if this information is unavailable.
Exception: NA.
import java.lang.*;
import java.io.*; Output:
import java.util.*; false
public class StackTraceElementDemo false
{
public static void main(String[] arg)
{
• throws is a keyword in Java which is used in the signature of method to indicate that this
method might throw one of the listed type exceptions.
• The caller to these methods has to handle the exception using a try-catch block.
Syntax:
type method_name(parameters) throws exception_list
exception_list is a comma separated list of all the exceptions which a method might throw.
throws in Java
import java.io.*;
class Main
{
public static void findFile() throws IOException
{ Output
throw new IOException("File not found"); File not found
}
public static void main(String[] args)
{
try
{
findFile();
System.out.println("Rest of code in try block");
}
catch (IOException e)
{
System.out.println(e.getMessage());
}}}
super keyword in Java
The concept of super keyword comes with the idea of inheritance in Java.
The super keyword in Java acts like a reference variable to the parent class.
It’s mainly used when we want to access a variable, method, or constructor in the base class, from the derived
class.
1. Accessing base class variables
• When we have the data members of the same name in both the base and derived class, we can use
the super keyword to access the base class member, data, in the derived class.
// Base Class
class Base {
int num = 30;
}
// Derived Class
class Derived extends Base { Output
int num = 20; Base `num`: 30
void callThis() { Derived `num`: 20
// print `num` of both classes
System.out.println("Base `num`: " + super.num);
System.out.println("Derived `num`: " + num);
}
}
/* Driver Routine */
class Test {
public static void main(String[] args) {
Derived temp = new Derived();
temp.callThis();
}
}
2. Invoking base class method
When the name of a function if the same in both the base and derived class, the super keyword can be used to invoke the base
class function in the derived class.
class Base {
void display(){
System.out.println("Base Class");
}
}
// Derived Class
Output
class Derived extends Base {
// invoke `display()` method for both the classes
Base Class
void callThis(){ Derived Class
super.display();
display();
}
void display(){
System.out.println("Derived Class");
}
}
/* Driver Routine */
class Test {
public static void main(String[] args) {
Derived temp = new Derived();
temp.callThis();
}
}
3. Invoking base class constructor
The super keyword can also be used to invoke the parent class constructor, both parameterized and empty, in the
derived class.
// Base Class
class Base {
Base(){
System.out.println("Base Class Constructor");
}
}
// Derived Class Output
class Derived extends Base { Base Class Constructor
// invoke `display()` method for both the classes Derived Class Constructor
Derived(){
super();
System.out.println("Derived Class Constructor");
}
}
/* Driver Routine */
class Test {
public static void main(String[] args) {
Derived temp = new Derived();
}
}
Input / Output Basics
Input / Output Basics
Java brings various Streams with its I/O package that helps the user to perform all the input-output operations. These
streams support all the types of objects, data-types, characters, files etc to fully execute the I/O operations
Before exploring various input and output streams lets look at 3 standard or default streams that Java has to provide
which are also most common in use:
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it is
like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with the console.
Syntax:System.out.print(parameter);
import java.io.*;
class Demo_print {
Output:
public static void main(String[] args)
{ GfG! GfG! GfG!
// using print()
// all are printed in the
// same line
System.out.print("GfG! ");
System.out.print("GfG! ");
System.out.print("GfG! ");
}
}
println(): This method in Java is also used to display a text on the console. It prints the text on the console and the
cursor moves to the start of the next line at the console. The next printing takes place from the next line.
Syntax:System.out.println(parameter);
// using println()
// all are printed in the
// different line
System.out.println("GfG! ");
System.out.println("GfG! ");
System.out.println("GfG! ");
}
}
printf(): This is the easiest of all methods as this is similar to printf in C.
Note that System.out.print() and System.out.println() take a single argument, but printf() may take multiple arguments.
This is used to format the output in Java.
•print()
•println()
•printf()
System.err.println("error message");
Types of Streams:
Depending on the type of operations, streams can be divided into two primary classes:
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.
Depending on the types of file, Streams can be divided into two primary classes which can be further
divided into other classes as can be seen through the diagram below followed by the explanations.
Stream Example
E:\PJ>java JavaStreamExample
[90000.0]
ByteStream Classes in Java
ByteStream classes are used to read bytes from the input stream and write bytes to the output stream. In other words, we
can say that ByteStream classes read/write the data of 8-bits. We can store video, audio, characters, etc., by using
ByteStream classes. These classes are part of the java.io package.
The ByteStream classes are divided into two types of classes, i.e., InputStream and OutputStream. These classes are
abstract and the super classes of all the Input/Output stream classes.
InputStream Class
The InputStream class provides methods to read bytes from a file, console or memory. It is an abstract class and can't be
instantiated; however, various classes inherit the InputStream class and override its methods. The subclasses of
InputStream class are given in the following table.
SN Class Description
1 BufferedInputStream This class provides methods to read bytes from the buffer.
2 ByteArrayInputStream This class provides methods to read bytes from the byte array.
3 DataInputStream This class provides methods to read Java primitive data types.
5 FilterInputStream This class contains methods to read bytes from the other input streams, which
are used as the primary source of data.
7 PipedInputStream This class provides methods to read from a piped output stream to which the
piped input stream must be connected.
8 SequenceInputStream This class provides methods to connect multiple Input Stream and read data
from them.
ByteArrayInput Stream
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class InputOutputStreamExample {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
byte content[] = "Google is the best website to learn new technologies".getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(content);
inputStream.read(content);
File newFile = new File("/E:/PJ/MyNewFile.doc");
FileOutputStream outputStream = new FileOutputStream(newFile);
outputStream.write(content);
}
}
The InputStream class contains various methods to read the data from an input stream. These methods are overridden by
the classes that inherit the InputStream class. However, the methods are given in the following table.
SN Method Description
1 int read() This method returns an integer, an integral representation of the next available
byte of the input. The integer -1 is returned once the end of the input is
encountered.
2 int read (byte buffer []) This method is used to read the specified buffer length bytes from the input and
returns the total number of bytes successfully read. It returns -1 once the end of
the input is encountered.
3 int read (byte buffer [], int loc, This method is used to read the 'nBytes' bytes from the buffer starting at a
int nBytes) specified location, 'loc'. It returns the total number of bytes successfully read
from the input. It returns -1 once the end of the input is encountered.
4 int available () This method returns the number of bytes that are available to read.
5 Void mark(int nBytes) This method is used to mark the current position in the input stream until the
specified nBytes are read.
6 void reset () This method is used to reset the input pointer to the previously set mark.
7 long skip (long nBytes) This method is used to skip the nBytes of the input stream and returns the total
number of bytes that are skipped.
8 void close () This method is used to close the input source. If an attempt is made to read even
after the closing, IOException is thrown by the method.
OutputStream Class
The OutputStream is an abstract class that is used to write 8-bit bytes to the stream. It is the superclass of all the output stream classes. This class
can't be instantiated; however, it is inherited by various subclasses that are given in the following table.
The OutputStream class provides various methods to write bytes to the output streams. The methods are given in the following table.
SN Class Description
1 BufferedOutputStream This class provides methods to write the bytes to the buffer.
2 ByteArrayOutputStream This class provides methods to write bytes to the byte array.
3 DataOutputStream This class provides methods to write the java primitive data types.
2 void write (byte buffer [] ) It is used to write a byte array to the output
stream.
3 Void write(bytes buffer[],int loc, int nBytes) It is used to write nByte bytes to the output
stream from the buffer starting at the specified
location.
•The java.io package provides CharacterStream classes to overcome the limitations of ByteStream
classes, which can only handle the 8-bit bytes and is not compatible to work directly with the Unicode
characters.
•CharacterStream classes are used to work with 16-bit Unicode characters.
•They can perform operations on characters, char arrays and Strings.
•However, the CharacterStream classes are mainly used to read characters from the source and write
them to the destination. For this purpose, the CharacterStream classes are divided into two types of
classes, I.e., Reader class and Writer class.
Reader Class
Reader class is used to read the 16-bit characters from the input stream. However, it is an abstract class
and can't be instantiated, but there are various subclasses that inherit the Reader class and override the
methods of the Reader class. All methods of the Reader class throw an IOException. The subclasses of
the Reader class are given in the following table.
SN Class Description
1. BufferedReader This class provides methods to read characters from the buffer.
2. CharArrayReader This class provides methods to read characters from the char array.
3. FileReader This class provides methods to read characters from the file.
4. FilterReader This class provides methods to read characters from the underlying
character input stream.
6 PipedReader This class provides methods to read characters from the connected piped
output stream.
SN Method Description
1 int read() This method returns the integral representation of the next character
present in the input. It returns -1 if the end of the input is
encountered.
2 int read(char buffer[]) This method is used to read from the specified buffer. It returns the
total number of characters successfully read. It returns -1 if the end of
the input is encountered.
3 int read(char buffer[], int loc, int This method is used to read the specified nChars from the buffer at
nChars) the specified location. It returns the total number of characters
successfully read.
4 void mark(int nchars) This method is used to mark the current position in the input stream
until nChars characters are read.
5 void reset() This method is used to reset the input pointer to the previous set
mark.
6 long skip(long nChars) This method is used to skip the specified nChars characters from the
input stream and returns the number of characters skipped.
7 boolean ready() This method returns a boolean value true if the next request of input
is ready. Otherwise, it returns false.
8 void close() This method is used to close the input stream. However, if the
program attempts to access the input, it generates IOException.
Writer Class
Writer class is used to write 16-bit Unicode characters to the output stream. The methods of the Writer class generate IOException.
Like Reader class, Writer class is also an abstract class that cannot be instantiated; therefore, the subclasses of the Writer class are used
to write the characters onto the output stream. The subclasses of the Writer class are given in the below table.
To write the characters to the output stream, the Write class provides various methods given in the following table.
SN Class Description
1 BufferedWriter This class provides methods to write characters to the
buffer.
2 void write(int i) This method is used to write a single character to the output stream.
3 Void write(char buffer[]) This method is used to write the array of characters to the output
stream.
4 void write(char buffer [],int loc, int nChars) This method is used to write the nChars characters to the character
array from the specified location.
5 void close () This method is used to close the output stream. However, this
generates the IOException if an attempt is made to write to the output
stream after closing the stream.
6 void flush () This method is used to flush the output stream and writes the waiting
buffered characters.