-1

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();    
    }    
} 
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Sushant
  • 3
  • 2

1 Answers1

3

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197