ampc
ampc

Reputation: 312

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;
    }
}

Upvotes: 1

Views: 44840

Answers (3)

ACV
ACV

Reputation: 10562

this cannot be null because this is your instance of a Cell. Without changing char to Character:

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() {
        return letter == 0;
    }
}

Upvotes: 0

Boris the Spider
Boris the Spider

Reputation: 61148

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().

Upvotes: 2

Barranka
Barranka

Reputation: 21047

If the instance of an object exists, then it cannot be null! (as the comment of Code-Guru says). However, what you are trying to do is to check if the letter attribute of your object is (or is not) null.

Just as a suggestion, instead of using char as the type, use Character, which is the class that encapsulates the char type.

Your class then will may look like this:

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

    public Cell(int column, int row, Character letter) {
        super();
        this.column = column;
        this.row = row;
        this.letter = letter; // This is an object, not a primitive type 
    }

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

Upvotes: 0

Related Questions