What I wanted is to reach EOF by typing Ctrl + z from command line with BufferedReader reading from console. The following code does so. But the problem is, it issues a NullPointerException after reaching EOF. Is there a way to skip this exception? Or more precisely, what is the proper way of reaching EOF with BufferedReader reading from console?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class EOF {
    public static void main(String args[]) {
        String s = "";
        String EOF = "^z";
        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
        try {
            while (!s.equals(EOF)) {
                s = read.readLine();   
            }
        } catch (IOException e) {} 
    }
}
                NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.
What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.
Answer: Some of the best practices to avoid NullPointerException are: Use equals() and equalsIgnoreCase() method with String literal instead of using it on the unknown object that can be null. Use valueOf() instead of toString() ; and both return the same result. Use Java annotation @NotNull and @Nullable.
java.lang.NullPointerException. Thrown when an application attempts to use null in a case where an object is required. These include: Calling the instance method of a null object. Accessing or modifying the field of a null object.
Or more precisely, what is the proper way of reaching EOF with bufferedReader reading from console?
Currently you're actually detecting the characters '^' and 'z' it's not like '^' is really a control character.
The exception you're getting is actually a hint as to how you should be handling this. From the docs for BufferedReader.readLine:
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
So basically you should loop until readLine returns null.
String line;
while((line = read.readLine()) != null)
{
    // Do something with line
}
                        See how much a debugger can help:

After I press ctrl + z, s has null value, hence you're getting this exception, since it's like writing !null.equals(EOF).
Why?
Because BufferedReader#readLine returns "null if the end of the stream has been reached".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With