I do not have much to ask really. Heck I don’t even know what the question should say. Basically, this Java code works fine without any compilation errors.
public class Application {
static String[][] tiles;
public Application() {
tiles = new String[9][9];
}
public static void main(String[] args) {
Application app = new Application();
Grid mines = new Grid();
mines.fillTiles(tiles, 9, 9, 10);
}
}
class Grid {
Random rand;
public void fillTiles(String[][] tiles, int rowSize, int colSize,
int numMines) {
rand = new Random();
int rowIndex;
int columnIndex;
while (numMines > 0) {
rowIndex = rand.nextInt(rowSize);
columnIndex = rand.nextInt(colSize);
tiles[rowIndex][columnIndex] = "M";
numMines--;
}
}
}
But, when I remove the line
Application app = new Application();
from the main method in the first class, it is throwing a NullPointerException at
tiles[rowIndex][columnIndex] = new String("M");
Any reason why?
You notice that you have instantiated your array in your constructor?
So, if you don’t instantiate your
Applicationusingnew Application(), your array would not be initialized, and your reference will be pointing to null.Also, it is not a good idea to initialize your static variables in constructor. Ideally, you should initialize your static array in a
static initializer blockor at the place of declaration itself: –or
If you initialize your array in your constructor, it will be re-initialized for every instance, every time you create one. As
staticvariables are common to all the instances. So, the change you make to yourstaticvariable, will be reflected in all your instances.