The readBoolean() method of DataInputStream class in Java is used to read one input byte and if the byte read is zero this method returns false and if the byte read is nonzero then this method returns true.
Syntax:
public final boolean readBoolean() throws IOException
Specified By: This method is specified by readBoolean() method of DataInput interface.
Parameters: This method does not accept any parameter.
Return value: This method returns the boolean value read i.e true or false.
Exceptions:
- EOFException – It throws EOFException if the input stream is ended.
- IOException – This method throws IOException if the stream is closed or some other I/O error occurs.
Below programs illustrate readBoolean() method in DataInputStream class in IO package:
Program 1:
// Java program to illustrate // DataInputStream readBoolean() method import java.io.*; public class GFG { public static void main(String[] args) throws IOException { // Create byte array byte [] b = { 10 , 0 , 0 , 20 , 0 }; // Create byte array input stream ByteArrayInputStream byteArrayInputStr = new ByteArrayInputStream(b); // Convert byte array input stream to // DataInputStream DataInputStream dataInputStr = new DataInputStream( byteArrayInputStr); while (dataInputStr.available() > 0 ) { // Print boolean value System.out.println( dataInputStr.readBoolean()); } } } |
true false false true false
Program 2:
// Java program to illustrate // DataInputStream readBoolean() method import java.io.*; public class GFG { public static void main(String[] args) throws IOException { // Create byte array byte [] b = { 10 , 5 , 7 , 1 , 0 }; // Create byte array input stream ByteArrayInputStream byteArrayInputStr = new ByteArrayInputStream(b); // Convert byte array input stream to // DataInputStream DataInputStream dataInputStr = new DataInputStream( byteArrayInputStr); while (dataInputStr.available() > 0 ) { // Print boolean value System.out.println( dataInputStr.readBoolean()); } } } |
true true true true false
References:
https://docs.oracle.com/javase/10/docs/api/java/io/DataInputStream.html#readBoolean()