Skip to content

Instantly share code, notes, and snippets.

@davidcorbin
Created January 26, 2018 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidcorbin/e9b34438a239057806ecca2ce171f8ff to your computer and use it in GitHub Desktop.
Save davidcorbin/e9b34438a239057806ecca2ce171f8ff to your computer and use it in GitHub Desktop.
Example of NullPointerException cause by failure to instantiate objects
//
// An example of a NullPointerException caused by a not initializing objects before using them
//
import java.util.ArrayList;
class test {
// An ArrayList is like a vector in c++
// This ArrayList hold Strings
public ArrayList<String> listOfStrings;
public static void main(String[] args) {
// Create a new instance of the test class
test instanceOfTest = new test();
// EXTREMELY IMPORTANT: Make sure to initialize objects before calling the onjects methods (such as add)
// The code will compile and run with this line commented by will always throw a NullPointerException
//instanceOfTest.listOfStrings = new ArrayList<String>();
// Add a String to a Arraylist
instanceOfTest.listOfStrings.add("test string");
// Print out the ArrayList
System.out.println(instanceOfTest.listOfStrings);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment