Unit - 5
Exception Handling and I/O Streams
Q1) What is exception handling?
A1) Exception Handling
● The Exception Handling in Java is one of the powerful mechanisms to handle the runtime errors so that the normal flow of the application can be maintained.
● In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
What is Exception in Java
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.
The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application that is why we use exception handling. Let's take a scenario:
- Statement 1;
- Statement 2;
- Statement 3;
- Statement 4;
- Statement 5;//exception occurs
- Statement 6;
- Statement 7;
- Statement 8;
- Statement 9;
- Statement 10;
Suppose there are 10 statements in your program and there occurs an exception at statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform exception handling, the rest of the statement will be executed. That is why we use exception handling in Java.
Q2) Write the benefits of exception handling?
A2) Benefits of exception handling
● When an exception occurs, exception handling guarantees that the program's flow is preserved.
● This allows us to identify the different types of faults.
● This allows us to develop error-handling code separately from the rest of the code.
When an exception occurs, exception handling ensures that the program's flow does not break. For example, if a programme has a large number of statements and an exception occurs in the middle of executing some of them, the statements after the exception will not be executed, and the programme will end abruptly.
By handling, we ensure that all of the statements are executed and that the program's flow is not disrupted.
Q3) Explain hierarchy of java exception classes?
A3) The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error. A hierarchy of Java Exception classes are given below:
Fig 1 - A hierarchy of Java Exception classes
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
Fig 2 – Exception handling
1) Checked Exception
The classes which directly inherit Throwable class except Runtime Exception and Error are known as checked exceptions e.g. IO Exception, SQL Exception etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes which inherit Runtime Exception are known as unchecked exceptions e.g. Arithmetic Exception, Null Pointer Exception, Array Index Out Of Bounds Exception etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. Out Of Memory Error, Virtual Machine Error, Assertion Error etc.
Q4) Write the keywords of java exception?
A4) Java Exception Keywords
There are 5 keywords which are used in handling exceptions in Java.
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. |
Q5) Write any example of exception handling?
A5) Java Exception Handling Example
Let's see an example of Java Exception Handling where we use a try-catch statement to handle the exception.
- Public class JavaExceptionExample{
- Public static void main(String args[]){
- Try{
- //code that may raise exception
- Int data=100/0;
- }catch(ArithmeticException e){System.out.println(e);}
- //rest code of the program
- System.out.println("rest of the code...");
- }
- }
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
Rest of the code…
In the above example, 100/0 raises an Arithmetic Exception which is handled by a try-catch block.
Q6) What do you mean by checked exceptions?
A6) Checked Exception:
❖ The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions.
❖ For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.
1. ClassNotFoundException: The ClassNotFoundException is a kind of checked exception that is thrown when we attempt to use a class that does not exist.
Checked exceptions are those exceptions that are checked by the Java compiler itself.
2. FileNotFoundException: The FileNotFoundException is a checked exception that is thrown when we attempt to access a non-existing file.
3. InterruptedException: InterruptedException is a checked exception that is thrown when a thread is in sleeping or waiting state and another thread attempt to interrupt it.
4. InstantiationException: This exception is also a checked exception that is thrown when we try to create an object of abstract class or interface. That is, InstantiationException exception occurs when an abstract class or interface is instantiated.
5. IllegalAccessException: The IllegalAccessException is a checked exception and it is thrown when a method is called in another method or class but the calling method or class does not have permission to access that method.
6. CloneNotSupportedException: This checked exception is thrown when we try to clone an object without implementing the cloneable interface.
7. NoSuchFieldException: This is a checked exception that is thrown when an unknown variable is used in a program.
8. NoSuchMethodException: This checked exception is thrown when the undefined method is used in a program.
Q7) Define an unchecked exception?
A7) Unchecked Exception
❖ The classes that inherit the RuntimeException are known as unchecked exceptions.
❖ For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc
❖ Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
Let’s see a brief description of them.
1. ArithmeticException: This exception is thrown when arithmetic problems, such as a number is divided by zero, is occurred. That is, it is caused by maths error.
2. ClassCastException: The ClassCastException is a runtime exception that is thrown by JVM when we attempt to invalid typecasting in the program. That is, it is thrown when we cast an object to a subclass of which an object is not an instance.
3. IllegalArgumentException: This runtime exception is thrown by programmatically when an illegal or appropriate argument is passed to call a method. This exception class has further two subclasses:
● Number Format Exception
● Illegal Thread State Exception
Numeric Format Exception: Number Format Exception is thrown by programmatically when we try to convert a string into the numeric type and the process of illegal conversion fails. That is, it occurs due to the illegal conversion of a string to a numeric format.
Illegal Thread State Exception: Illegal Thread State Exception is a runtime exception that is thrown by programmatically when we attempt to perform any operation on a thread but it is incompatible with the current thread state.
4. IndexOutOfBoundsException: This exception class is thrown by JVM when an array or string is going out of the specified index. It has two further subclasses:
● ArrayIndexOutOfBoundsException
● StringIndexOutOfBoundsException
ArrayIndexOutOfBoundsException: ArrayIndexOutOfBoundsException exception is thrown when an array element is accessed out of the index.
StringIndexOutOfBoundsException: StringIndexOutOfBoundsException exception is thrown when a String or StringBuffer element is accessed out of the index.
5. NullPointerException: NullPointerException is a runtime exception that is thrown by JVM when we attempt to use null instead of an object. That is, it is thrown when the reference is null.
6. ArrayStoreException: This exception occurs when we attempt to store any value in an array which is not of array type. For example, suppose, an array is of integer type but we are trying to store a value of an element of another type.
7. IllegalStateException: The IllegalStateException exception is thrown by programmatically when the runtime environment is not in an appropriate state for calling any method.
8. IllegalMonitorStateException: This exception is thrown when a thread does not have the right to monitor an object and tries to access wait(), notify(), and notifyAll() methods of the object.
9. NegativeArraySizeException: The NegativeArraySizeException exception is thrown when an array is created with a negative size.
Q8) Write the difference between checked and unchecked exception?
A8) Difference between Checked and Unchecked Exceptions
Checked Exception | Unchecked Exception |
These exceptions are checked at compile time. These exceptions are handled at compile time too. | These exceptions are just opposite to the checked exceptions. These exceptions are not checked and handled at compile time. |
These exceptions are direct subclasses of exception but not extended from RuntimeException class. | They are the direct subclasses of the RuntimeException class. |
The code gives a compilation error in the case when a method throws a checked exception. The compiler is not able to handle the exception on its own. | The code compiles without any error because the exceptions escape the notice of the compiler. These exceptions are the results of user-created errors in programming logic. |
These exceptions mostly occur when the probability of failure is too high. | These exceptions occur mostly due to programming mistakes. |
Common checked exceptions include IOException, DataAccessException, InterruptedException, etc. | Common unchecked exceptions include ArithmeticException, InvalidClassException, NullPointerException, etc. |
These exceptions are propagated using the throws keyword. | These are automatically propagated. |
It is required to provide the try-catch and try-finally block to handle the checked exception. | In the case of unchecked exception it is not mandatory. |
Q9) Explain try and catch blocks?
A9) Java try block is used to enclose the code that might throw an exception. It must be used within the method.
If an exception occurs at the particular statement of try block, the rest of the block code will not execute. So, it is recommended not to keeping the code in try block that will not throw an exception.
Java try block must be followed by either catch or finally block.
Syntax of Java try-catch
- Try{
- //code that may throw an exception
- }catch(Exception_class_Name ref){}
Syntax of try-finally block
- Try{
- //code that may throw an exception
- }finally{}
Java catch block
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. You can use multiple catch block with a single try block.
Q10) Write the syntax of finally, throw and throws?
A10) Finally:
a) Syntax of finally without catch
Try{
//block of statement
}
Finally {
}
b) Syntax of finally with catch
Try {
//Block of statement}
Catch(Exception Handler class)
{
} finally{
}
Throw:
Syntax:
Throw exception_object;
Throws:
Syntax:
MethodName () throws comma separated list of exceptionClassNames{}
Q11) What is the difference between throw and throws?
A11) Difference between throw and throws
Throw keyword | Throws keyword |
|
|
Q12) What is the difference between final, finally and finalize?
A12) Difference between final, finally and finalize
● The final, finally, and finalize are keywords in Java that are used in exception handling. Each of these keywords has a different functionality.
● The basic difference between final, finally and finalize is that the final is an access modifier, finally is the block in Exception Handling and finalize is the method of object class.
Key | Final | Finally | Finalize |
Definition | Final is the keyword and access modifier which is used to apply restrictions on a class, method or variable. | Finally is the block in Java Exception Handling to execute the important code whether the exception occurs or not. | Finalize is the method in Java which is used to perform clean up processing just before object is garbage collected. |
Applicable to | Final keyword is used with the classes, methods and variables. | Finally block is always related to the try and catch block in exception handling. | Finalize() method is used with the objects. |
Functionality | (1) Once declared, final variable becomes constant and cannot be modified. | (1) finally block runs the important code even if exception occurs or not. | Finalize method performs the cleaning activities with respect to the object before its destruction. |
Execution | Final method is executed only when we call it. | Finally block is executed as soon as the try-catch block is executed. It's execution is not dependant on the exception. | Finalize method is executed just before the object is destroyed. |
Q13) Write an example to handle another unchecked exception?
A13) Let's see an example to handle another unchecked exception.
- Public class TryCatchExample9 {
- Public static void main(String[] args) {
- Try
- {
- Int arr[]= {1,3,5,7};
- System.out.println(arr[10]); //may throw exception
- }
- // handling the array exception
- Catch(ArrayIndexOutOfBoundsException e)
- {
- System.out.println(e);
- }
- System.out.println("rest of the code");
- }
- }
Output:
Java.lang.ArrayIndexOutOfBoundsException: 10
Rest of the code
Q14) Write any example to handle checked exception?
A14) Let's see an example to handle checked exception.
- Import java.io.FileNotFoundException;
- Import java.io.PrintWriter;
- Public class TryCatchExample10 {
- Public static void main(String[] args) {
- PrintWriter pw;
- Try {
- Pw = new PrintWriter("jtp.txt"); //may throw exception
- Pw.println("saved");
- }
- // providing the checked exception handler
- Catch (FileNotFoundException e) {
- System.out.println(e);
- }
- System.out.println("File saved successfully");
- }
- }
Output:
File saved successfully
Q15) Describe rethrow exception?
A15) You can use the throw keyword to rethrow an exception that has been cached in a catch block (which is used to throw the exception objects).
You can re-throw the same exception without altering it while re-throwing exceptions.
Try {
Int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
Catch(ArithmeticException e) {
Throw e;
}
Alternatively, you can wrap it in a new exception and throw it. Exception chaining or exception wrapping is when you wrap a cached exception within another exception and throw it. This allows you to change your exception by throwing a higher level of exception while retaining the abstraction.
Try {
Int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
Catch(ArrayIndexOutOfBoundsException e) {
Throw new IndexOutOfBoundsException();
}
Example
In the Java example below, our demoMethod() code may throw an ArrayIndexOutOfBoundsException and an ArithmeticException. These two exceptions are caught in two different catch blocks.
We re-throw both exceptions in the catch blocks, one by wrapping it within the higher exceptions and the other directly.
Import java.util.Arrays;
Import java.util.Scanner;
Public class RethrowExample {
Public void demoMethod() {
Scanner sc = new Scanner(System.in);
Int[] arr = {10, 20, 30, 2, 0, 8};
System.out.println("Array: "+Arrays.toString(arr));
System.out.println("Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)");
Int a = sc.nextInt();
Int b = sc.nextInt();
Try {
Int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
Catch(ArrayIndexOutOfBoundsException e) {
Throw new IndexOutOfBoundsException();
}
Catch(ArithmeticException e) {
Throw e;
}
}
Public static void main(String [] args) {
New RethrowExample().demoMethod();
}
}
Output1
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
0
4
Exception in thread "main" java.lang.ArithmeticException: / by zero
At myPackage.RethrowExample.demoMethod(RethrowExample.java:16)
At myPackage.RethrowExample.main(RethrowExample.java:25)
Output2
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
124
5
Exception in thread "main" java.lang.IndexOutOfBoundsException
At myPackage.RethrowExample.demoMethod(RethrowExample.java:17)
At myPackage.RethrowExample.main(RethrowExample.java:23)
Q16) Introduce database connectivity?
A16) Java Database Connectivity (JDBC) is a Java application programming interface (API) that specifies how a client can interact with a database. It is a Java-based data access technology that is used to link Java databases. Oracle Corporation's Java Standard Edition platform includes it. It is geared toward relational databases and provides techniques for querying and updating data in a database. In the Java virtual machine (JVM) host environment, a JDBC-to-ODBC bridge allows connections to any ODBC-accessible data source.
Java Database Connectivity (JDBC) is a Sun Microsystems specification that provides a common abstraction (API or Protocol) for Java programmes to interface with multiple databases. It implements the Java database connectivity standard in the language. It's used to create programmes that connect to databases. Databases and spreadsheets can be accessed via JDBC and the database driver. JDBC APIs can be used to access enterprise data stored in a relational database (RDB).
JDBC is an API (application programming interface) for interacting with databases in Java programming.
JDBC classes and interfaces enable applications to communicate user requests to a specific database.
JDBC's Purpose
Enterprise applications built with the JAVA EE technology must connect with databases in order to store application-specific data. As a result, communicating with a database necessitates effective database connectivity, which can be accomplished with the ODBC (Open database connectivity) driver. This driver is used in conjunction with JDBC to connect or communicate with a variety of databases, including Oracle, MS Access, Mysql, and SQL Server.
Components
JDBC is made up of four basic components that allow it to interact with a database. The following is a list of them:
● JDBC API - It offers a variety of methods and interfaces for interacting with databases.
It includes the following two packages, which contain the Java SE and Java EE platforms to demonstrate WORA (write once run anywhere) capabilities.
1. Java.sql.*;
2. Javax.sql.*;
It also establishes a standard for connecting a client application to a database.
● JDBC Driver Manager - The JDBC Driver Manager loads a database-specific driver into an application in order to connect to a database. It's used to process the user's request by making a database-specific call to the database.
● JDBC Test Suite - It is used to test JDBC Drivers' operations (such as insertion, deletion, and updating).
● JDBC-ODBC Bridge Drivers - Bridge Drivers for JDBC and ODBC: It establishes a connection between database drivers and the database. This bridge converts ODBC function calls to JDBC method calls. It makes use of the
Sun.jdbc.odbc
This package contains a native library for accessing ODBC properties.
Q17) What do you mean by file handling?
A17) In Java, file handling entails reading and writing data to a file. The java.io package's File class allows us to work with a variety of file formats. You must create an object of the File class and supply the filename or directory name in order to utilize it.
We can work with files in Java using the File Class. The java.io package contains this File Class. To use the File class, first create an object of the class and then specify the file's name.
Why is File Handling Necessary?
File handling is an essential aspect of any programming language since it allows us to save the output of any programme in a file and execute operations on it.
To put it another way, file handling is the process of reading and writing data to a file.
Example
// Import the File class
Import java.io.File
// Specify the filename
File obj = new File("filename.txt");
To perform I/O operations on a file, Java employs the concept of a stream. So, let's look at what a Stream is in Java.
Java File Methods
The methods for conducting operations on Java files are shown in the table below.
Method | Type | Description |
CanRead() | Boolean | It tests whether the file is readable or not |
CanWrite() | Boolean | It tests whether the file is writable or not |
CreateNewFile() | Boolean | This method creates an empty file |
Delete() | Boolean | Deletes a file |
Exists() | Boolean | It tests whether the file exists |
GetName() | String | Returns the name of the file |
GetAbsolutePath() | String | Returns the absolute pathname of the file |
Length() | Long | Returns the size of the file in bytes |
List() | String[] | Returns an array of the files in the directory |
Mkdir() | Boolean | Creates a directory |
Q18) Define byte stream classes?
A18) Byte Stream Classes:
● Byte Stream classes are used to read bytes from the input stream and write bytes to the output stream.
● In other word, Byte Stream classes read/write the data of 8-bits. We can store video, audio, characters, etc., by using Byte Stream classes.
● These classes are part of the java.io package.
● The Byte Stream classes are divided into two types of classes, i.e., Input Stream and Output Stream. These classes are abstract and the super classes of all the Input/Output stream classes.
Input Stream Class:
The Input Stream class provides methods to read bytes from a file, console or memory. It is an abstract class
SN | Class | Description | ||
1 | Buffered Input Stream | This class provides methods to read bytes from the buffer. | ||
2 | Byte Array Input Stream | This class provides methods to read bytes from the byte array. | ||
3 | Data Input Stream | This class provides methods to read Java primitive data types. | ||
4 | File Input Stream | This class provides methods to read bytes from a file. | ||
5 | Filter Input Stream | This class contains methods to read bytes from the other input streams, which are used as the primary source of data. | ||
6 | Object Input Stream | This class provides methods to read objects. | ||
7 | Piped Input Stream | This class provides methods to read from a piped output stream to which the piped input stream must be connected. | ||
8 | Sequence Input Stream | This class provides methods to connect multiple Input Stream and read data from them. | ||
The Input Stream class contains various methods to read the data from an input stream. These methods are overridden by the classes that inherit the Input Stream 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, int nBytes) | This method is used to read the 'nBytes' bytes from the buffer starting at a 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, IO Exception is thrown by the method. |
Output Stream Class
● The Output Stream 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.
● It is inherited by various subclasses that are given in the following table.
SN | Class | Description |
1 | Buffered Output Stream | This class provides methods to write the bytes to the buffer. |
2 | Byte Array Output Stream | This class provides methods to write bytes to the byte array. |
3 | Data Output Stream | This class provides methods to write the java primitive data types. |
4 | File Output Stream | This class provides methods to write bytes to a file. |
5 | Filter Output Stream | This class provides methods to write to other output streams. |
6 | Object Output Stream | This class provides methods to write objects. |
7 | Piped Output Stream | It provides methods to write bytes to a piped output stream. |
8 | Print Stream | It provides methods to print Java primitive data types. |
The Output Stream class provides various methods to write bytes to the output streams. The methods are given in the following table.
SN | Method | Description |
1 | Void write (int i) | This method is used to write the specified single byte to the output stream. |
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. |
4 | Void flush () | It is used to flush the output stream and writes the pending buffered bytes. |
5 | Void close () | It is used to close the output stream. However, if we try to close the already closed output stream, the IO Exception will be thrown by this method. |
Q19) Explain character stream?
A19) Character Stream
● Character Stream classes to overcome the limitations of Byte Stream classes, which can only handle the 8-bit bytes and is not compatible to work directly with the Unicode characters.
● Character Stream classes are used to work with 16-bit Unicode characters. They can perform operations on characters, char arrays and Strings.
● Character Stream classes are mainly used to read characters from the source and write them to the destination.
● These 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.
◆ All methods of the Reader class throw an IO Exception. The subclasses of the Reader class are given in the following table
SN | Class | Description |
1. | Buffered Reader | It provides methods to read characters from the buffer. |
2. | Char Array Reader | It provides methods to read characters from the char array. |
3. | File Reader | It provides methods to read characters from the file. |
4. | Filter Reader | It provides methods to read characters from the underlying character input stream. |
5 | Input Stream Reader | It provides methods to convert bytes to characters. |
6 | Piped Reader | It provides methods to read characters from the connected piped output stream. |
7 | String Reader | It provides methods to read characters from a string. |
The Reader class methods are given in the following table.
SN | Method | Description |
1 | Int read () | It 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 []) | It 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 nChars) | It is used to read the specified nChars from the buffer at the specified location. It returns the total number of characters successfully read. |
4 | Void mark (int nchars) | It is used to mark the current position in the input stream until nChars characters are read. |
5 | Void reset () | It is used to reset the input pointer to the previous set mark. |
6 | Long skip (long nChars) | It is used to skip the specified nChars characters from the input stream and returns the number of characters skipped. |
7 | Boolean ready () | It returns a boolean value true if the next request of input is ready. Otherwise, it returns false. |
8 | Void close () | It is used to close the input stream. However, if the program attempts to access the input, it generates IO Exception. |
Writer Class
Writer class is used to write 16-bit Unicode characters to the output stream.
SN | Class | Description |
1 | Buffered Writer | It provides methods to write characters to the buffer. |
2 | File Writer | It provides methods to write characters to the file. |
3 | Char Array Writer | It provides methods to write the characters to the character array. |
4 | Output Stream Writer | It provides methods to convert from bytes to characters. |
5 | Piped Writer | It provides methods to write the characters to the piped output stream. |
6 | String Writer | It provides methods to write the characters to the string. |
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 | Method | Description |
1 | Void write () | It is used to write the data to the output stream. |
2 | Void write (int i) | It is used to write a single character to the output stream. |
3 | Void write (char buffer []) | It is used to write the array of characters to the output stream. |
4 | Void write (char buffer [], int loc, int nChars) | It is used to write the nChars characters to the character array from the specified location. |
5 | Void close () | It is used to close the output stream. However, this generates the IO Exception if an attempt is made to write to the output stream after closing the stream. |
6 | Void flush () | It is used to flush the output stream and writes the waiting buffered characters. |
Q20) Write the difference between input/output Streams and Readers/Writers?
A20) Difference between input/output Streams and Readers/Writers
● The input/output stream classes read and write byte stream data, which is the main difference between them. Characters are handled by the Reader/Writer classes.
● The methods of the input/output stream classes use a byte array as a parameter, while the Reader/Writer classes take a character array.
● The Reader/Writer classes handle all Unicode characters and are more efficient than input/output streams for internalization.
● As a result, until you're dealing with binary data like images, it's best to stick with Reader/Writer classes.
Unit - 5
Exception Handling and I/O Streams
Q1) What is exception handling?
A1) Exception Handling
● The Exception Handling in Java is one of the powerful mechanisms to handle the runtime errors so that the normal flow of the application can be maintained.
● In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
What is Exception in Java
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.
The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application that is why we use exception handling. Let's take a scenario:
- Statement 1;
- Statement 2;
- Statement 3;
- Statement 4;
- Statement 5;//exception occurs
- Statement 6;
- Statement 7;
- Statement 8;
- Statement 9;
- Statement 10;
Suppose there are 10 statements in your program and there occurs an exception at statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform exception handling, the rest of the statement will be executed. That is why we use exception handling in Java.
Q2) Write the benefits of exception handling?
A2) Benefits of exception handling
● When an exception occurs, exception handling guarantees that the program's flow is preserved.
● This allows us to identify the different types of faults.
● This allows us to develop error-handling code separately from the rest of the code.
When an exception occurs, exception handling ensures that the program's flow does not break. For example, if a programme has a large number of statements and an exception occurs in the middle of executing some of them, the statements after the exception will not be executed, and the programme will end abruptly.
By handling, we ensure that all of the statements are executed and that the program's flow is not disrupted.
Q3) Explain hierarchy of java exception classes?
A3) The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error. A hierarchy of Java Exception classes are given below:
Fig 1 - A hierarchy of Java Exception classes
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
Fig 2 – Exception handling
1) Checked Exception
The classes which directly inherit Throwable class except Runtime Exception and Error are known as checked exceptions e.g. IO Exception, SQL Exception etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes which inherit Runtime Exception are known as unchecked exceptions e.g. Arithmetic Exception, Null Pointer Exception, Array Index Out Of Bounds Exception etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. Out Of Memory Error, Virtual Machine Error, Assertion Error etc.
Q4) Write the keywords of java exception?
A4) Java Exception Keywords
There are 5 keywords which are used in handling exceptions in Java.
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. |
Q5) Write any example of exception handling?
A5) Java Exception Handling Example
Let's see an example of Java Exception Handling where we use a try-catch statement to handle the exception.
- Public class JavaExceptionExample{
- Public static void main(String args[]){
- Try{
- //code that may raise exception
- Int data=100/0;
- }catch(ArithmeticException e){System.out.println(e);}
- //rest code of the program
- System.out.println("rest of the code...");
- }
- }
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
Rest of the code…
In the above example, 100/0 raises an Arithmetic Exception which is handled by a try-catch block.
Q6) What do you mean by checked exceptions?
A6) Checked Exception:
❖ The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions.
❖ For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.
1. ClassNotFoundException: The ClassNotFoundException is a kind of checked exception that is thrown when we attempt to use a class that does not exist.
Checked exceptions are those exceptions that are checked by the Java compiler itself.
2. FileNotFoundException: The FileNotFoundException is a checked exception that is thrown when we attempt to access a non-existing file.
3. InterruptedException: InterruptedException is a checked exception that is thrown when a thread is in sleeping or waiting state and another thread attempt to interrupt it.
4. InstantiationException: This exception is also a checked exception that is thrown when we try to create an object of abstract class or interface. That is, InstantiationException exception occurs when an abstract class or interface is instantiated.
5. IllegalAccessException: The IllegalAccessException is a checked exception and it is thrown when a method is called in another method or class but the calling method or class does not have permission to access that method.
6. CloneNotSupportedException: This checked exception is thrown when we try to clone an object without implementing the cloneable interface.
7. NoSuchFieldException: This is a checked exception that is thrown when an unknown variable is used in a program.
8. NoSuchMethodException: This checked exception is thrown when the undefined method is used in a program.
Q7) Define an unchecked exception?
A7) Unchecked Exception
❖ The classes that inherit the RuntimeException are known as unchecked exceptions.
❖ For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc
❖ Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
Let’s see a brief description of them.
1. ArithmeticException: This exception is thrown when arithmetic problems, such as a number is divided by zero, is occurred. That is, it is caused by maths error.
2. ClassCastException: The ClassCastException is a runtime exception that is thrown by JVM when we attempt to invalid typecasting in the program. That is, it is thrown when we cast an object to a subclass of which an object is not an instance.
3. IllegalArgumentException: This runtime exception is thrown by programmatically when an illegal or appropriate argument is passed to call a method. This exception class has further two subclasses:
● Number Format Exception
● Illegal Thread State Exception
Numeric Format Exception: Number Format Exception is thrown by programmatically when we try to convert a string into the numeric type and the process of illegal conversion fails. That is, it occurs due to the illegal conversion of a string to a numeric format.
Illegal Thread State Exception: Illegal Thread State Exception is a runtime exception that is thrown by programmatically when we attempt to perform any operation on a thread but it is incompatible with the current thread state.
4. IndexOutOfBoundsException: This exception class is thrown by JVM when an array or string is going out of the specified index. It has two further subclasses:
● ArrayIndexOutOfBoundsException
● StringIndexOutOfBoundsException
ArrayIndexOutOfBoundsException: ArrayIndexOutOfBoundsException exception is thrown when an array element is accessed out of the index.
StringIndexOutOfBoundsException: StringIndexOutOfBoundsException exception is thrown when a String or StringBuffer element is accessed out of the index.
5. NullPointerException: NullPointerException is a runtime exception that is thrown by JVM when we attempt to use null instead of an object. That is, it is thrown when the reference is null.
6. ArrayStoreException: This exception occurs when we attempt to store any value in an array which is not of array type. For example, suppose, an array is of integer type but we are trying to store a value of an element of another type.
7. IllegalStateException: The IllegalStateException exception is thrown by programmatically when the runtime environment is not in an appropriate state for calling any method.
8. IllegalMonitorStateException: This exception is thrown when a thread does not have the right to monitor an object and tries to access wait(), notify(), and notifyAll() methods of the object.
9. NegativeArraySizeException: The NegativeArraySizeException exception is thrown when an array is created with a negative size.
Q8) Write the difference between checked and unchecked exception?
A8) Difference between Checked and Unchecked Exceptions
Checked Exception | Unchecked Exception |
These exceptions are checked at compile time. These exceptions are handled at compile time too. | These exceptions are just opposite to the checked exceptions. These exceptions are not checked and handled at compile time. |
These exceptions are direct subclasses of exception but not extended from RuntimeException class. | They are the direct subclasses of the RuntimeException class. |
The code gives a compilation error in the case when a method throws a checked exception. The compiler is not able to handle the exception on its own. | The code compiles without any error because the exceptions escape the notice of the compiler. These exceptions are the results of user-created errors in programming logic. |
These exceptions mostly occur when the probability of failure is too high. | These exceptions occur mostly due to programming mistakes. |
Common checked exceptions include IOException, DataAccessException, InterruptedException, etc. | Common unchecked exceptions include ArithmeticException, InvalidClassException, NullPointerException, etc. |
These exceptions are propagated using the throws keyword. | These are automatically propagated. |
It is required to provide the try-catch and try-finally block to handle the checked exception. | In the case of unchecked exception it is not mandatory. |
Q9) Explain try and catch blocks?
A9) Java try block is used to enclose the code that might throw an exception. It must be used within the method.
If an exception occurs at the particular statement of try block, the rest of the block code will not execute. So, it is recommended not to keeping the code in try block that will not throw an exception.
Java try block must be followed by either catch or finally block.
Syntax of Java try-catch
- Try{
- //code that may throw an exception
- }catch(Exception_class_Name ref){}
Syntax of try-finally block
- Try{
- //code that may throw an exception
- }finally{}
Java catch block
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. You can use multiple catch block with a single try block.
Q10) Write the syntax of finally, throw and throws?
A10) Finally:
a) Syntax of finally without catch
Try{
//block of statement
}
Finally {
}
b) Syntax of finally with catch
Try {
//Block of statement}
Catch(Exception Handler class)
{
} finally{
}
Throw:
Syntax:
Throw exception_object;
Throws:
Syntax:
MethodName () throws comma separated list of exceptionClassNames{}
Q11) What is the difference between throw and throws?
A11) Difference between throw and throws
Throw keyword | Throws keyword |
|
|
Q12) What is the difference between final, finally and finalize?
A12) Difference between final, finally and finalize
● The final, finally, and finalize are keywords in Java that are used in exception handling. Each of these keywords has a different functionality.
● The basic difference between final, finally and finalize is that the final is an access modifier, finally is the block in Exception Handling and finalize is the method of object class.
Key | Final | Finally | Finalize |
Definition | Final is the keyword and access modifier which is used to apply restrictions on a class, method or variable. | Finally is the block in Java Exception Handling to execute the important code whether the exception occurs or not. | Finalize is the method in Java which is used to perform clean up processing just before object is garbage collected. |
Applicable to | Final keyword is used with the classes, methods and variables. | Finally block is always related to the try and catch block in exception handling. | Finalize() method is used with the objects. |
Functionality | (1) Once declared, final variable becomes constant and cannot be modified. | (1) finally block runs the important code even if exception occurs or not. | Finalize method performs the cleaning activities with respect to the object before its destruction. |
Execution | Final method is executed only when we call it. | Finally block is executed as soon as the try-catch block is executed. It's execution is not dependant on the exception. | Finalize method is executed just before the object is destroyed. |
Q13) Write an example to handle another unchecked exception?
A13) Let's see an example to handle another unchecked exception.
- Public class TryCatchExample9 {
- Public static void main(String[] args) {
- Try
- {
- Int arr[]= {1,3,5,7};
- System.out.println(arr[10]); //may throw exception
- }
- // handling the array exception
- Catch(ArrayIndexOutOfBoundsException e)
- {
- System.out.println(e);
- }
- System.out.println("rest of the code");
- }
- }
Output:
Java.lang.ArrayIndexOutOfBoundsException: 10
Rest of the code
Q14) Write any example to handle checked exception?
A14) Let's see an example to handle checked exception.
- Import java.io.FileNotFoundException;
- Import java.io.PrintWriter;
- Public class TryCatchExample10 {
- Public static void main(String[] args) {
- PrintWriter pw;
- Try {
- Pw = new PrintWriter("jtp.txt"); //may throw exception
- Pw.println("saved");
- }
- // providing the checked exception handler
- Catch (FileNotFoundException e) {
- System.out.println(e);
- }
- System.out.println("File saved successfully");
- }
- }
Output:
File saved successfully
Q15) Describe rethrow exception?
A15) You can use the throw keyword to rethrow an exception that has been cached in a catch block (which is used to throw the exception objects).
You can re-throw the same exception without altering it while re-throwing exceptions.
Try {
Int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
Catch(ArithmeticException e) {
Throw e;
}
Alternatively, you can wrap it in a new exception and throw it. Exception chaining or exception wrapping is when you wrap a cached exception within another exception and throw it. This allows you to change your exception by throwing a higher level of exception while retaining the abstraction.
Try {
Int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
Catch(ArrayIndexOutOfBoundsException e) {
Throw new IndexOutOfBoundsException();
}
Example
In the Java example below, our demoMethod() code may throw an ArrayIndexOutOfBoundsException and an ArithmeticException. These two exceptions are caught in two different catch blocks.
We re-throw both exceptions in the catch blocks, one by wrapping it within the higher exceptions and the other directly.
Import java.util.Arrays;
Import java.util.Scanner;
Public class RethrowExample {
Public void demoMethod() {
Scanner sc = new Scanner(System.in);
Int[] arr = {10, 20, 30, 2, 0, 8};
System.out.println("Array: "+Arrays.toString(arr));
System.out.println("Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)");
Int a = sc.nextInt();
Int b = sc.nextInt();
Try {
Int result = (arr[a])/(arr[b]);
System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}
Catch(ArrayIndexOutOfBoundsException e) {
Throw new IndexOutOfBoundsException();
}
Catch(ArithmeticException e) {
Throw e;
}
}
Public static void main(String [] args) {
New RethrowExample().demoMethod();
}
}
Output1
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
0
4
Exception in thread "main" java.lang.ArithmeticException: / by zero
At myPackage.RethrowExample.demoMethod(RethrowExample.java:16)
At myPackage.RethrowExample.main(RethrowExample.java:25)
Output2
Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
124
5
Exception in thread "main" java.lang.IndexOutOfBoundsException
At myPackage.RethrowExample.demoMethod(RethrowExample.java:17)
At myPackage.RethrowExample.main(RethrowExample.java:23)
Q16) Introduce database connectivity?
A16) Java Database Connectivity (JDBC) is a Java application programming interface (API) that specifies how a client can interact with a database. It is a Java-based data access technology that is used to link Java databases. Oracle Corporation's Java Standard Edition platform includes it. It is geared toward relational databases and provides techniques for querying and updating data in a database. In the Java virtual machine (JVM) host environment, a JDBC-to-ODBC bridge allows connections to any ODBC-accessible data source.
Java Database Connectivity (JDBC) is a Sun Microsystems specification that provides a common abstraction (API or Protocol) for Java programmes to interface with multiple databases. It implements the Java database connectivity standard in the language. It's used to create programmes that connect to databases. Databases and spreadsheets can be accessed via JDBC and the database driver. JDBC APIs can be used to access enterprise data stored in a relational database (RDB).
JDBC is an API (application programming interface) for interacting with databases in Java programming.
JDBC classes and interfaces enable applications to communicate user requests to a specific database.
JDBC's Purpose
Enterprise applications built with the JAVA EE technology must connect with databases in order to store application-specific data. As a result, communicating with a database necessitates effective database connectivity, which can be accomplished with the ODBC (Open database connectivity) driver. This driver is used in conjunction with JDBC to connect or communicate with a variety of databases, including Oracle, MS Access, Mysql, and SQL Server.
Components
JDBC is made up of four basic components that allow it to interact with a database. The following is a list of them:
● JDBC API - It offers a variety of methods and interfaces for interacting with databases.
It includes the following two packages, which contain the Java SE and Java EE platforms to demonstrate WORA (write once run anywhere) capabilities.
1. Java.sql.*;
2. Javax.sql.*;
It also establishes a standard for connecting a client application to a database.
● JDBC Driver Manager - The JDBC Driver Manager loads a database-specific driver into an application in order to connect to a database. It's used to process the user's request by making a database-specific call to the database.
● JDBC Test Suite - It is used to test JDBC Drivers' operations (such as insertion, deletion, and updating).
● JDBC-ODBC Bridge Drivers - Bridge Drivers for JDBC and ODBC: It establishes a connection between database drivers and the database. This bridge converts ODBC function calls to JDBC method calls. It makes use of the
Sun.jdbc.odbc
This package contains a native library for accessing ODBC properties.
Q17) What do you mean by file handling?
A17) In Java, file handling entails reading and writing data to a file. The java.io package's File class allows us to work with a variety of file formats. You must create an object of the File class and supply the filename or directory name in order to utilize it.
We can work with files in Java using the File Class. The java.io package contains this File Class. To use the File class, first create an object of the class and then specify the file's name.
Why is File Handling Necessary?
File handling is an essential aspect of any programming language since it allows us to save the output of any programme in a file and execute operations on it.
To put it another way, file handling is the process of reading and writing data to a file.
Example
// Import the File class
Import java.io.File
// Specify the filename
File obj = new File("filename.txt");
To perform I/O operations on a file, Java employs the concept of a stream. So, let's look at what a Stream is in Java.
Java File Methods
The methods for conducting operations on Java files are shown in the table below.
Method | Type | Description |
CanRead() | Boolean | It tests whether the file is readable or not |
CanWrite() | Boolean | It tests whether the file is writable or not |
CreateNewFile() | Boolean | This method creates an empty file |
Delete() | Boolean | Deletes a file |
Exists() | Boolean | It tests whether the file exists |
GetName() | String | Returns the name of the file |
GetAbsolutePath() | String | Returns the absolute pathname of the file |
Length() | Long | Returns the size of the file in bytes |
List() | String[] | Returns an array of the files in the directory |
Mkdir() | Boolean | Creates a directory |
Q18) Define byte stream classes?
A18) Byte Stream Classes:
● Byte Stream classes are used to read bytes from the input stream and write bytes to the output stream.
● In other word, Byte Stream classes read/write the data of 8-bits. We can store video, audio, characters, etc., by using Byte Stream classes.
● These classes are part of the java.io package.
● The Byte Stream classes are divided into two types of classes, i.e., Input Stream and Output Stream. These classes are abstract and the super classes of all the Input/Output stream classes.
Input Stream Class:
The Input Stream class provides methods to read bytes from a file, console or memory. It is an abstract class
SN | Class | Description | ||
1 | Buffered Input Stream | This class provides methods to read bytes from the buffer. | ||
2 | Byte Array Input Stream | This class provides methods to read bytes from the byte array. | ||
3 | Data Input Stream | This class provides methods to read Java primitive data types. | ||
4 | File Input Stream | This class provides methods to read bytes from a file. | ||
5 | Filter Input Stream | This class contains methods to read bytes from the other input streams, which are used as the primary source of data. | ||
6 | Object Input Stream | This class provides methods to read objects. | ||
7 | Piped Input Stream | This class provides methods to read from a piped output stream to which the piped input stream must be connected. | ||
8 | Sequence Input Stream | This class provides methods to connect multiple Input Stream and read data from them. | ||
The Input Stream class contains various methods to read the data from an input stream. These methods are overridden by the classes that inherit the Input Stream 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, int nBytes) | This method is used to read the 'nBytes' bytes from the buffer starting at a 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, IO Exception is thrown by the method. |
Output Stream Class
● The Output Stream 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.
● It is inherited by various subclasses that are given in the following table.
SN | Class | Description |
1 | Buffered Output Stream | This class provides methods to write the bytes to the buffer. |
2 | Byte Array Output Stream | This class provides methods to write bytes to the byte array. |
3 | Data Output Stream | This class provides methods to write the java primitive data types. |
4 | File Output Stream | This class provides methods to write bytes to a file. |
5 | Filter Output Stream | This class provides methods to write to other output streams. |
6 | Object Output Stream | This class provides methods to write objects. |
7 | Piped Output Stream | It provides methods to write bytes to a piped output stream. |
8 | Print Stream | It provides methods to print Java primitive data types. |
The Output Stream class provides various methods to write bytes to the output streams. The methods are given in the following table.
SN | Method | Description |
1 | Void write (int i) | This method is used to write the specified single byte to the output stream. |
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. |
4 | Void flush () | It is used to flush the output stream and writes the pending buffered bytes. |
5 | Void close () | It is used to close the output stream. However, if we try to close the already closed output stream, the IO Exception will be thrown by this method. |
Q19) Explain character stream?
A19) Character Stream
● Character Stream classes to overcome the limitations of Byte Stream classes, which can only handle the 8-bit bytes and is not compatible to work directly with the Unicode characters.
● Character Stream classes are used to work with 16-bit Unicode characters. They can perform operations on characters, char arrays and Strings.
● Character Stream classes are mainly used to read characters from the source and write them to the destination.
● These 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.
◆ All methods of the Reader class throw an IO Exception. The subclasses of the Reader class are given in the following table
SN | Class | Description |
1. | Buffered Reader | It provides methods to read characters from the buffer. |
2. | Char Array Reader | It provides methods to read characters from the char array. |
3. | File Reader | It provides methods to read characters from the file. |
4. | Filter Reader | It provides methods to read characters from the underlying character input stream. |
5 | Input Stream Reader | It provides methods to convert bytes to characters. |
6 | Piped Reader | It provides methods to read characters from the connected piped output stream. |
7 | String Reader | It provides methods to read characters from a string. |
The Reader class methods are given in the following table.
SN | Method | Description |
1 | Int read () | It 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 []) | It 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 nChars) | It is used to read the specified nChars from the buffer at the specified location. It returns the total number of characters successfully read. |
4 | Void mark (int nchars) | It is used to mark the current position in the input stream until nChars characters are read. |
5 | Void reset () | It is used to reset the input pointer to the previous set mark. |
6 | Long skip (long nChars) | It is used to skip the specified nChars characters from the input stream and returns the number of characters skipped. |
7 | Boolean ready () | It returns a boolean value true if the next request of input is ready. Otherwise, it returns false. |
8 | Void close () | It is used to close the input stream. However, if the program attempts to access the input, it generates IO Exception. |
Writer Class
Writer class is used to write 16-bit Unicode characters to the output stream.
SN | Class | Description |
1 | Buffered Writer | It provides methods to write characters to the buffer. |
2 | File Writer | It provides methods to write characters to the file. |
3 | Char Array Writer | It provides methods to write the characters to the character array. |
4 | Output Stream Writer | It provides methods to convert from bytes to characters. |
5 | Piped Writer | It provides methods to write the characters to the piped output stream. |
6 | String Writer | It provides methods to write the characters to the string. |
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 | Method | Description |
1 | Void write () | It is used to write the data to the output stream. |
2 | Void write (int i) | It is used to write a single character to the output stream. |
3 | Void write (char buffer []) | It is used to write the array of characters to the output stream. |
4 | Void write (char buffer [], int loc, int nChars) | It is used to write the nChars characters to the character array from the specified location. |
5 | Void close () | It is used to close the output stream. However, this generates the IO Exception if an attempt is made to write to the output stream after closing the stream. |
6 | Void flush () | It is used to flush the output stream and writes the waiting buffered characters. |
Q20) Write the difference between input/output Streams and Readers/Writers?
A20) Difference between input/output Streams and Readers/Writers
● The input/output stream classes read and write byte stream data, which is the main difference between them. Characters are handled by the Reader/Writer classes.
● The methods of the input/output stream classes use a byte array as a parameter, while the Reader/Writer classes take a character array.
● The Reader/Writer classes handle all Unicode characters and are more efficient than input/output streams for internalization.
● As a result, until you're dealing with binary data like images, it's best to stick with Reader/Writer classes.