x.equals(x) and x.equals(null)

284 Views Asked by At

Let's assume we have this example code:

Fish fish;

fish.equals(null);
fish.equals(fish);

The equals method has not been overwritten and the fish variable has not been initialized which means, that java will nullify it?

So would both line return true? And why would that be so? Would it also be possible to use an class variable when the object is not initialized?

2

There are 2 best solutions below

0
On

If fish is a local variable, this code won't pass compilation, since fish must be initialized.

If fish is an instance variable, this code will throw NullPointerException, since the default value of fish will be null, and de-referencing a null reference throws this exception.

2
On

After the statement Fish fish;, fish will be null; i.e. it is not referring to an object.

You'll get null pointer exception when executing fish.equals(null); since fish is itself null, so equals will not be available.