JDK 1.4 the NullPointerException - Java Tutorials

JDK 1 4 NullPointerException

Tutorials   

Ads

Ads

NullPointerException In Java

NullPointerException occurs when you perform an operation on a object or calling a method on the object.  The only way to solve Null Pointer Exception is to avoid executing operation on a object or calling a method on the object.

Example

Given below example will give you a clear idea :

package simpleCoreJava;

public class JavaNullpointerexception {
public static void main(String args[]) {
String string[] = new String[2];
System.out.println(string[1].charAt(1));

}
}

Code Description

In the above class we have declared a String array which has size 2. But we haven't initialize the array therefore at position 1 there is nothing. So When we call charAt() function, the above code throw NullPointerException.

Output


 Exception in thread "main" java.lang.NullPointerException
 at simpleCoreJava.JavaNullpointerexception.main(JavaNullpointerexception.java:8)                 

Correction of the above code

You can Correct the above code as follows :

package simpleCoreJava;

public class JavaNullpointerexception {
public static void main(String args[]) {
String string[] = new String[3];
string[0] = "ankit";
string[1] = "ankit";
string[2] = "ankit";
System.out.println(string[1].charAt(1));

}
}

The Output of the above code will be :


 n                       

 

 

Advertisements

Share on Google+Share on Google+

JDK 1.4 the NullPointerException - Java Tutorials

Posted on: April 18, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: JDK 1.4 the NullPointerException - Java Tutorials  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

 

Ads