NullPointerException
KW.java
class KW
{
    public static void main(String args[])
    {
        String s=null;
        System.out.println("Length: "+s.length());
    }
}
Output
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW Exception in thread "main" java.lang.NullPointerException at KW.main(KW.java:6) kodingwindow@kw:~$
Java program to handle the NullPointerException
KW.java
class KW
{
    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
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW String is null, hence, Unable to find the length. kodingwindow@kw:~$
Advertisement