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