Greg Greg - 6 months ago 6x
Java Question

Java, NullPointerException on using array of Objects

Here is the code example. I want to create a 1 dimensional array of objects, give them values, use it in other methods, then print it out as a 2 dimensional array.

At first i want to print the starting board, but i get NullPointException when i try to loop throught the array.
The 2 dimensional array is a 6x6 matrix.

public class Field{
int diceCount, playerNumber;

//get and set methods etc.

public class Board{
public Field[] board = new Field[36];

public void boardBuilder(){
for(int i = 0; i < board.length; i++){
board[i] = new Field();
//give value to the Fields

public class IoMethods{
public Board board = new Board();

public void boardPrintOut(){
int helper;
for(int i = 0; i < 6; i++){
for(int j = 0; j < 6; j++){
//The next line is where it gets the Exception
helper = board.board[i*6 + j].getPlayerNumber();

//print part


This line public Field[] board = new Field[36]; creates an array of length 36 which can contain Field objects. But now all of its 36 cells are null. So when you try to access some board[i] you're accessing null.

Solution: Write a constructor for your Board class and inside that write what you've written inside boardBuilder() or simply call this.boardBuilder():

public Board(){
    for(int i = 0; i < board.length ; i++)
        board[i] = new Field();