yoggi yoggi - 7 months ago 9
Java Question

How to check if object is null in Java?

What is the best way to check if a position is occupied or not? I don't think I should be using "this==null"...

class Cell {
int column;
int row;
char letter;

public Cell(int column, int row, char letter) {
super();
this.column = column;
this.row = row;
this.letter = letter;
}

public boolean isEmpty() {
if (this==null) return true;
else return false;
}
}

Answer

I'm going to assume that the char is the content of your Cell and you want to check if that content is null.

First, this cannot ever be null. this is the current object, and therefore is always exists.

You are using a char - as this is a primitive is also cannot be null. Change that to the object wrapper and check that for null

class Cell {

    int column;
    int row;
    Character letter;

    public Cell(int column, int row, Character letter) {
        this.column = column;
        this.row = row;
        this.letter = letter;
    }

    public boolean isEmpty() {
        return letter == null;
    }
}

Another note is that the superclass constructor is always called by default, there is no reason to call super().