Avoid NullPointerException from user input

how to avoid null pointer exception in java 8
null pointer exception java
how to handle null pointer exception in selenium
throw nullpointerexception
how to handle null pointer exception in junit
nullpointerexception java array
java.lang.nullpointerexception in eclipse
null pointer exception in android studio

I am using JDK 1.7, I am checking the code for all conditions of input. if user does not enter any value in the String then it throws a NullPointerException. Is there a way to prevent causing NullPointerException even if the user does not enter any value?

i tried try catch block to catch exception

import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
class TestClass {
   public static void main(String args[]) throws Exception {

    Scanner s = new Scanner(System.in);    
    int i=s.nextInt();
    System.out.println(i);

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String str = br.readLine();
    try{
        int length=str.length();  //NullPointerException here

        if(length>=1 && length<=15)
        {
            System.out.println(str);
        }
    }
    catch(NullPointerException e)
    {
        System.out.println("Must enter a string");
    }
   }
}

sample input- 5 null

Expected Output- 5 (Empty string value-> "" but no exception thrown message)

Java 8
int length = Optional.ofNullable(str).orElse("").length();
Java 7
int length = str == null ? 0 : str.length();
Java 7 + Apache Commons
int length = StringUtils.length(str);
Use Scanner

Use Scanner instead of BufferedReader; scane.nextLine() returns not null string.


public static void main(String... args) {
    try (Scanner s = new Scanner(System.in)) {
        System.out.println(s.nextInt());

        s.nextLine();

        String str = s.nextLine();

        if (str.length() >= 1 && str.length() <= 15)
            System.out.println(str);
    }
}

Avoid NullPointerException from user input, Java 8. int length = Optional.ofNullable(str).orElse("").length();. Java 7. int length = str == null ? 0 : str.length();. Java 7 + Apache Commons. Note that, allowing runtime exception is considered to be relatively expensive process than to avoid it. It is due to the fact that throwing exceptions require various stacktrace objects to be initialization.

Instead of try/catch you could check if str is not null before you call str.length()

Scanner s = new Scanner(System.in);
String str = s.nextLine();
if (str != null && str.length() <= 15) {
   System.out.println(str);
} else {
   System.out.println("Must enter a string");
}

Java NullPointerException, NullPointerException doesn't force us to use catch block to handle it. so that the rest of your code does not have to deal with the possibility of incorrect input. Java 8 introduced an Optional class which is a nicer way to avoid NullPointerExceptions. You can use Optional to encapsulate the potential null values and pass or return it safely without worrying about the exception. Without Optional, when a method signature has return type of certain object.

import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
class TestClass {
   public static void main(String args[]) throws Exception {

    Scanner s = new Scanner(System.in);    
    int i=s.nextInt();
    System.out.println(i);

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String str = br.readLine();
        if(str!=null && str.length() >=1 && str.length()<=15)
        {
            System.out.println(str);
        }
    }
   }
}

How to avoid NullPointerException in Java using Optional class , NullPointerException is thrown when program attempts to use an object reference that has the null value. These can be: Invoking a method from a null object. One of the best way to avoid NullPointerException in Java is as simple as defining contracts and following them. Most of the NullPointerException occurs because Object is created with incomplete information or all required dependency is not provided.

1) Read the documentation - note that BufferedReader.readline can legitimately return null under well-defined circumstances.

2) Write code that can handle the possible null return.

java.lang.NullPointerException, 5) Use of annotation @NotNull and @Nullable. While writing method you can define contracts about nullability, by declaring whether a method is null safe or not,  The ternary operator can be used to avoid NullPointerException. First, the Boolean expression is evaluated. If the expression is true then, the value1 is returned, otherwise, the value2 is returned. We can use the ternary operator for handling null pointers:

Java Tips and Best practices to avoid NullPointerException in Java , Avoid Null Pointer Exception in Java and Java Tips and Best practices (NPE) is an exception that occur when you try to use a reference that  An awesome tip to avoid NPE is to return empty strings or empty collections rather than a null. Do this consistently across your application. You will note that a bucket load of null checks become unneeded if you do so. An example could be:

Have you Noticed java.lang.NullPointerException (NPE)? 8 Best , NullPointerException is thrown when an application attempts to use an object reference that has the null value. These include: Calling an instance method on  E.g., they do not check pointers. They assume that a piece of code should be given correct input and it should not be responsible for what happens if the input is wrong. Also, if a NULL pointer exception crashes the program, a bug will be found more easily during testing and have more chances of being fixed.

Preventing NullPointerException, According to the Javadoc for NullPointerException, it's thrown when an application attempts to use null in a case where an object is required,  NullPointerException is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when an application attempts to use an object reference that has the null value. These include: Calling an instance method on the object referred by a null reference.

Comments
  • NPE is an unchecked exception, so it is bad practice to catch it. Instead just do a simple null check
  • Also why have both a Scanner and a BufferedReader to read from System.in? Why not remove the BufferedReader and just have String str = s.nextLine()? (And in reference to your likely future question read this)
  • I think this is an environment issue. I do not get a NullPointerException when I compile and run it in JDK 1.7. Please ensure you are running the right class.
  • if str is null, calling any method such as .length() will cause a NullPointerException