Search code examples
javanullable

How to present the nullable primitive type int in Java?


I am designing an entity class which has a field named "documentYear", which might have unsigned integer values such as 1999, 2006, etc. Meanwhile, this field might also be "unknown", that is, not sure which year the document is created.

Therefore, a nullable int type as in C# will be well suited. However, Java does not have a nullable feature as C# has.

I have two options but I don't like them both:

  1. Use java.lang.Integer instead of the primitive type int;
  2. Use -1 to present the "unknown" value

Does anyone have better options or ideas?

Update: My entity class will have tens of thousands of instances; therefore the overhead of java.lang.Integer might be too heavy for overall performance of the system.


Solution

  • You're going to have to either ditch the primitive type or use some arbitrary int value as your "invalid year".

    A negative value is actually a good choice since there is little chance of having a valid year that would cause an integer overflow and there is no valid negative year.