PUBLISHED ON: MAY 3, 2021
Java StringReader read() Method
In this tutorial, we will learn about the read()
method of StringReader class in Java. The task of this method is to read a single character from the given string reader. This method is declared as an abstract method. It means that the subclasses of the StringReader abstract class should override this method if the desired operation needs to be changed while reading a character.
Syntax:
This is the syntax declaration of this method. This method returns an integer value which is the integer value read from the stream. It can range from 0 to 65535. Else it returns -1 if no character has been read.
public abstract int read()
Example: StringReader read() Method
In the following example, we are using read()
method, this method reads each character of the string one by one. we can also implement this method in another way .i.e. read(char[] array, int start, int length)
here array
is the source and start
is the starting position from where we want to start reading, the length
is the length of the string.
import java.io.StringReader;
public class StudyTonight
{
public static void main(String args[])
{
try{
String str = "Hello";
StringReader reader= new StringReader(str);
int ch;
for (int i = 0; i < 5; i++) {
ch = reader.read();
System.out.print((char)ch);
}
reader.close();
}
catch(Exception e)
{
System.out.println("Error: "+e.toString());
}
}
}
Hello
Example 2: StringReader read() Method
This is another example to read the data using the overloading method of the read method, here we pass the buffer array to store the data then starting the index of the source array and the length of the array to be copied. This example will also give the same output as the output in the above programs.
import java.io.StringReader;
public class StudyTonight
{
public static void main(String args[])
{
try
{
String str = "Hello";
StringReader reader= new StringReader(str);
char arr[] = new char[5];
reader.read(arr, 0, 5);
System.out.print(arr);
reader.close();
}
catch(Exception e)
{
System.out.println("Error: "+e.toString());
}
}
}
Hello
Conclusion:
In this tutorial, we learned about read()
method of StringReader class in Java, which reads a single character from the given string reader and returns it as an integer value.