Created
January 26, 2018 13:36
-
-
Save davidcorbin/e9b34438a239057806ecca2ce171f8ff to your computer and use it in GitHub Desktop.
Example of NullPointerException cause by failure to instantiate objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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