Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Java DataInputStream readBoolean() Method

In this tutorial, we will learn about the readBoolean() method of DataInputStream class in Java. This method is used to check whether this stream read the boolean value or not. It reads one input byte and if the byte read is zero it returns false, and if the byte read is non-zero it returns true.

Syntax

This is the syntax of this method. It does not accept any parameter and returns the boolean value read, i.e true or false.

public final boolean readBoolean() throws IOException

Example: DataInputStream readBoolean() Method

The below example reading the values from the byte stream, here we are having the interesting point to note that, it considered non-zero values as a true value except for the 0 (zero) and that is the reason it is printing false value only for the position where the zero has occurred in the byte array.

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
public class StudyTonight 
{
	public static void main(String[] args) throws IOException 
	{ 
        byte[] b = { 10, 5, 7, 1, 0 }; 
        ByteArrayInputStream byteArrayInputStr = new ByteArrayInputStream(b);   
        DataInputStream dataInputStr = new DataInputStream(byteArrayInputStr);   
        while (dataInputStr.available() > 0)
        { 
            System.out.println(dataInputStr.readBoolean()); 
        } 
	}  
}


true
true
true
true
false

Example: DataInputStream readBoolean() Method

Here, we will illustrate another scenario where we will read the data from the byte array but here some negative value is there but the readByte() method considers them true, it means this method considers false for zero(0) and other than this all the values are true.

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
public class StudyTonight 
{
	public static void main(String[] args) throws IOException 
	{ 
        byte[] b = { -1, 10, 5, 6, 0 }; 
        ByteArrayInputStream byteArrayInputStr = new ByteArrayInputStream(b);   
        DataInputStream dataInputStr = new DataInputStream(byteArrayInputStr);   
        int count=dataInputStr.available();
        while (count > 0)
        { 
            System.out.println(dataInputStr.readBoolean()); 
            count--;
        } 
	}  
}


true
true
true
true
false

Conclusion

In this tutorial, we learned about the readDouble() method of DataInputStream class in Java, which is used to check if the current stream reads the boolean value or not, if yes, it returns boolean value true, and if not, it returns the boolean value false.