Program 1: This program is very simple for Null Pointer exception example
//define class
class NullPointerEx
{
// define main method from where execution starts
public static void main(String args[])
{
// define variable string type and assign null
String name = null;
// if user want to get number of character into the above string type variable, then user will get run time exception which is nothing but NullPointerException.
int n=name.length();
System.out.println(n);
}
}
Program 2:
//import Scanner class
import java.util.Scanner;
class NullPointerEx
{
// define main method from where execution starts
public static void main(String args[])
{
//create scanner object for run time input
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String name1=sc.next();
String name2 = null;
System.out.println(name2.length());
}
}
Program 3:
//import Scanner class
import java.util.Scanner;
class NullPointerEx
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name1: ");
String name1=sc.next();
System.out.println("Enter your name2: ");
String name2 = null;
try
{
// got NullPointerException Here
System.out.println("No of elements is "+name2.length());
}
catch(NullPointerException e)
{
// alternate way to handle exception
System.out.println("Enter again your name2: ");
name2=sc.next();
System.out.println("No of elements is "+name2.length());
}
}
}