Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to present the nullable primitive type int in Java?

Tags:

java

nullable

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.

like image 537
yinyueyouge Avatar asked Jun 12 '09 05:06

yinyueyouge


People also ask

Can Java primitive type be null?

Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.

How do you declare an integer as null in Java?

Integer a = null; int b = a; Does it mean that a function returning a possible null value for an integer is a bad practice? Edit 1: There are several different opinions in these answers. I am not enough confident to choose one or another.

Can int be nullable?

As you know, a value type cannot be assigned a null value. For example, int i = null will give you a compile time error. C# 2.0 introduced nullable types that allow you to assign null to value type variables.


2 Answers

Using the Integer class here is probably what you want to do. The overhead associated with the object is most likely (though not necessarily) trivial to your applications overall responsiveness and performance.

like image 119
Matthew Vines Avatar answered Oct 02 '22 10:10

Matthew Vines


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.

like image 37
hhafez Avatar answered Oct 02 '22 11:10

hhafez