minorThreat minorThreat - 1 year ago 75
Java Question

How to properly instantiate a bi-dimensional array in Java

I am having problems on how to instantiate bi-dimensional array of objects. I tried to demonstrate below a small sample to reproduce the error I am getting.

I have this class named Node that basically stores one character. This class is used inside the class named Test as a bi-dimensional attribute. I used some user input to establish the size of the array and instantiate it inside the instantiate() method. Then, I try to populate the map using a set method. However, the compiler gives me the following error message:

Eclipse Console Output:

Exception in thread "main" java.lang.NullPointerException
at Test.populate(Main.java:44)
at Main.main(Main.java:77)

My input was:

Enter height:
Enter width:

Below is the code I am using to reproduce this error:

Class Node:

class Node {
private char content;

this.content = ' ';

Node(Node node){
this.content = node.getContent();

public void setContent(char c) {
this.content = c;

public char getContent() {
return this.content;

Class Test:

class Test {
private Node[][] map;
private int height, width;

public void instantiate(){
Scanner reader = new Scanner(System.in);
System.out.println("Enter height: ");
this.height = reader.nextInt();
System.out.println("Enter width: ");
this.width = reader.nextInt();
map = new Node[height][width];

public void populate(){
for(int i=0;i<height;i++)
for(int j=0;j<width;j++){
if((i+j) %2 == 0)
* a b a b
* b a b a ...
* a b a b
* b a b a
* . . .

public void print(){
for(int i=0;i<height;i++){
for(int j=0;j<width;j++){

public Node[][] getMap(){
return this.map;


Main method:

public class Main {

public static void main(String[] args) {
Test testing = new Test();

The code can also be seen here: http://pastebin.com/agFMmB38

I am still getting used to Java (coming from C++), so they have some differences that I couldn't figure it out yet.

Any help would be greatly appreciated.
Thank you!

Answer Source

map[i][j] needs to be set to a new object, like map[i][j] = new Node('a') (well, if you had a constructor in Node which worked like that: it would be written Node(char a) { this.content = a; }).

You cannot do map[i][j].setContent('a') because it is not a preexisting Node object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download