Search code examples
javabufferedreaderreader

How is br.read() giving out -1 at the end of reading the string or How exactly does the br.read() works?


Here is a sample program as an Example for Buffered reader, I got most of it and understood the fact that the while loop execution stop when (br.read()=-1) but couldn't understand why is that so?

import java.io.*;  
public class BufferedReaderExample {  
    public static void main(String args[])throws Exception{    
          FileReader fr=new FileReader("D:\\testout.txt");    
          BufferedReader br=new BufferedReader(fr);    
  
          int i;    
          while((i=br.read())!=-1)    //<<<<I'm talking about this here
          {  
          System.out.print((char)i);  
          }  
          br.close();    
          fr.close();    
    }    
} 

Solution

  • The -1 is a signal value that is outside of the normal range of return values of the method. It is used to signal that end-of-stream has been reached:

    Returns:
    The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached

    (from: BufferedReader.read())

    So in short, as also mentioned by Federico klez Culloca in the comments, the reason is because that is how read() was designed.