NullPointerException
Codeaft.java
class Codeaft
{
    public static void main(String args[])
    {
        String s=null;
        System.out.println("Length: "+s.length());
    }
}
Output
codeaft@codeaft:~$ javac Codeaft.java
codeaft@codeaft:~$ java Codeaft Exception in thread "main" java.lang.NullPointerException at Codeaft.main(Codeaft.java:6) codeaft@codeaft:~$
Java program to handle the NullPointerException
Codeaft.java
class Codeaft
{
    public static void main(String args[])
    {
        String s=null;
        try
        {
            System.out.println("Length: "+s.length());
        }
        catch(NullPointerException e)
        {
            System.out.println("String is null, hence, Unable to find the length.");
        }
    }
}
Output
codeaft@codeaft:~$ javac Codeaft.java
codeaft@codeaft:~$ java Codeaft String is null, hence, Unable to find the length. codeaft@codeaft:~$
Comments and Reactions