Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Javatutorials JDK 1.4 the NullPointerException - Java Tutorials

Related Tutorials


 
 

Share on Google+Share on Google+

JDK 1.4 the NullPointerException - Java Tutorials

Advertisement
JDK 1 4 NullPointerException

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

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 18, 2011

Related Tutorials

Discuss: JDK 1.4 the NullPointerException - Java Tutorials  

Post your Comment


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