Arrays


Run Time Errors


Error Message Name:

	NullPointerException:
	at {class name}.{method name}({class name}.java:{line number})

Example:

	public static void main(String[] args)
        {  Board[] stack = new Board[5];
           stack[0].putPeg(Board.BLUE, 0, 1);
	} 

Cause: This is one of the most common error messages you will see in Java. This occurs when you are trying to call a method on an object that is currently null (e.g., it is not referenced to anything). In the example above, although you have allocated space for the array, you have not initialized each element in the array. Hence, they are all null references. When calling the putPeg method on a null object, you will get the NullPointerException message.

Solution: You must initialize elements in your array first. To do so, you need to call the constructor of the base type. In the above example, you would call the Board constructor, and create 5 boards:

	public static void main(String[] args)
        {  Board[] stack = new Board[5];
           for (int i = 0; I < stack.length; i++)
           {  stack[i] = new Board(5, 5); //initializing the board objects
           }
           stack[0].putPeg(Board.BLUE, 0, 1)
	}