In Java, the java.lang.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.
In some cases, the compiler prevents this exception with the compile-time error “The variable might not have been initialized” when a null
reference variable is passed as an argument of a method:
String s;
foo(s); // Compiler gives an error.
However, the compiler does not give this error when null
is directly passed to a function; however, there is a higher chance of it throwing a NullPointerException:
foo(null); // Higher probability of an exception
public class NullPointerExcept { public static void main(String[] args) { String s = "abcd"; foo(null); bar(null); } // Using a try-catch block: static void foo(String x){ try { System.out.println("First character: " + x.charAt(0)); } catch(NullPointerException e) { System.out.println("NullPointerException thrown!"); } } // Using if-else condition: static void bar(String x){ if(x != null) System.out.println("First character: " + x.charAt(0)); else System.out.println("NullPointerException thrown!"); } }
RELATED TAGS
View all Courses