user1221483
user1221483

Reputation: 431

NullPointerException with no real reason

    Character c = null;
    if (c != 'P') c = 'G';

Here's a simple code that is killing me with the results. Instead of the condition, I get an error NullPointerException. Although null! = 'P' and the condition must be fulfilled. I struggle with the problem of additional verification c! = null in condition "if". Is it should be? Are there any ways to make the comparison instead of an error? So it turns out that all the code just full of these unnecessary checks.

Upvotes: 0

Views: 139

Answers (4)

MrLore
MrLore

Reputation: 3780

Another solution would be to use the 'Yoda Conditional' syntax:

Character c = null;
if (!new Character('P').equals(c)) c = new Character('G');

This will mean that NullPointerException can never be thrown, as null.equals() is not valid, whereas new Character('P') can never be null.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503290

To expand slightly on nansen's answer, your code is equivalent to:

Character c = null;

char tmp = c.charValue();
if (tmp != 'P')
{
    c = Character.valueOf('G');
}

This is according to section 15.21.1 of the JLS (== and !=):

If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2).

Note that binary numeric promotion performs value set conversion (§5.1.13) and may perform unboxing conversion (§5.1.8).

Hopefully now you'll see why you're getting a NullPointerException. Do you need c to be of type Character rather than char? If you really do, you should use:

if (c == null || c != 'P')

Upvotes: 8

Yanick Rochon
Yanick Rochon

Reputation: 53616

You are trying to compare and object with a primitive. Java can only compare two elements of compatible types, thus it will not create an instance of Character with 'P', but will try to convert your variable c into a char and cannot do it because it is null.

Upvotes: 1

nansen
nansen

Reputation: 2962

You are using autoboxing, the wrapper type Character which is null is implicitly converted to a primitive char. That's when the NPE is happening.

Upvotes: 7

Related Questions