NullPointer Exception in Java

Java Syntax & Run time Errors, Java Exceptions, ArithmeticException, NumberException, NullPointerException and ArrayIndexOutOfBoundsException etc,Inserting Exception handling code in Java Programs.
Post Reply
Vijay Kumar Varma
Posts: 58
Joined: Mon Nov 26, 2018 1:51 am

NullPointer Exception in Java

Post by Vijay Kumar Varma » Wed Nov 28, 2018 4:08 am

Give an example for NullPointer Exception in Java Programming?

Shankar
Posts: 13
Joined: Thu Dec 06, 2018 11:47 am

Re: NullPointer Exception in Java

Post by Shankar » Sun Dec 09, 2018 5:49 am

Scenario where NullPointerException occurs

if we have no value in any variable, performing operations by the variable.

ex:

String s = null;

System.out.prinln(s.length());//NullPointerException

kishore
Posts: 55
Joined: Thu Jan 03, 2019 3:57 am

Re: NullPointer Exception in Java

Post by kishore » Sat Jan 05, 2019 12:10 pm

NullPointerException :
===================
NullPointerException is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when program attempts to use an object reference that has the null value.

#Invoking a method from a null object.
#Accessing or modifying a null object’s field.
#Taking the length of null, as if it were an array.
#Accessing or modifying the slots of null object, as if it were an array.
#Throwing null, as if it were a Throwable value.
#When you try to synchronize over a null object.

Example:

// A Java program to demonstrate that invoking a method
// on null causes NullPointerException
import java.io.*;

class GFG
{
public static void main (String[] args)
{
// Initializing String variable with null value
String ptr = null;

// Checking if ptr.equals null or works fine.
try
{
// This line of code throws NullPointerException
// because ptr is null
if (ptr.equals("gfg"))
System.out.print("Same");
else
System.out.print("Not Same");
}
catch(NullPointerException e)
{
System.out.print("NullPointerException Caught");
}
}
}

Output:
===========================
NullPointerException Caught

Post Reply

Return to “Java Exception Handling”