user3724404
user3724404

Reputation: 220

Java: Can you treat null like integer 0 like in C?

I want to check how many fields of an object are null. Can I do something like:

int numNotNull = !!(obj.a) + !!(obj.b) + !!(obj.c) + !!(obj.d);

This would work if null was a pointer to the 0 address, as in C.

Upvotes: 0

Views: 75

Answers (2)

VHS
VHS

Reputation: 10184

The other answer which is already accepted now, explains what null means in Java.

However if your original goal was to get the count of the null fields in one liner code, you can do it the following way:

int numNotNull = (((numNotNull = 0) == 0 && obj.a == null && ++numNotNull < 0) || (obj.b == null && ++numNotNull < 0) || (obj.c == null && ++numNotNull < 0) || (obj.d == null && ++numNotNull < 0)) ? 0 : numNotNull;

Upvotes: 0

Alex Taylor
Alex Taylor

Reputation: 8813

For a good understanding of what null is in Java, have a look at this answer. The major point of discussion is that as well as being a keyword referring to the null value, the type of that value is the nameless type 'null':

There is also a special null type, the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type. In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.

Hence the inability to use it directly in numerical calculations - it's a type mismatch.

Upvotes: 1

Related Questions