Null Pointer Exception:
The NullPointerException would be thrown if a variable with null value is used in the statements in the program before assigning it a legitimate value.So whenever a variable is used in the program it should be given a value before using it.
Example1:
public class Nullpointer
{
public static void main(String args[])
{
String name=null;
check(name);
}
public static void check(String s)
{
if(s.equals("ram"))
System.out.println("granted access");
}
}
Error
Exception in thread "main" java.lang.NullPointerException
at Nullpointer.check(Nullpointer.java:11)
at Nullpointer.main(Nullpointer.java:6)
This exception is thrown because the string object is not assigned a legitimate value before using in the if conditional statement.
Example2:
public class Nullpointer
{
public void call()
{
String name=null;;
check(name);
}
public void check(String s)
{
if(s.equals("ram"))
System.out.println("granted access");
}
}
public class Temp
{
public static void main(String args[])
{
Nullpointer np=null;
np.call();
}
}
Error:
Exception in thread "main" java.lang.NullPointerException
at Temp.main(Temp.java:6)
In the above shown code this error was thrown because the object of Nullpointer is not defined with a legitimate value.Thus a variable of any type must be given a reasonable value before using it otherwise this error would be thrown.
0 comments:
Post a Comment