How to work with Numbers in Java

Luiz Gustavo De O. Costa
2 min readJun 24, 2019

--

At first glance looks easy choose what kind of number use, but sometimes the system grow up and the first kind choose became useless.

So, let’s remember how many and best choice so far when you have to make a choice regarding the number.

Why should I use a number?

The answer looks easy sometimes, because my table has the PK (primary key) as int, long etc. But sometimes the choice is based on math operations, calculate, estimate and so on.

Let’s remember, is not a rule use a number for PK, since you can choice for instance work with UUID.

Difference between primitives and wrappers

There are some differences, such as: initialize the primitives, memory footprint.

Nowadays is not necessary convert to primitive to wrapper and vice-versa. This process is named as autoboxing/unboxing.

See below the primitive use and the current instance of each number.

Flavors of Number

In Java 11 there are 15 classes that extends Numbers, there classes are:

Relationship extract from IntelliJ IDEA

Let’s pass one by one and in the end you can choose the best for you.

Conclusion

Based on the good practice in know your domain and anticipate capacity problems so think about how the field/column can grow and if an number is correct to use instead of string type.

Prefer bigger types in doubt case.

References

https://docs.oracle.com/en/java/javase/11/docs/api/index.html. Accessed 24 June 2019.

Best regards,

Luiz

--

--

Luiz Gustavo De O. Costa
Luiz Gustavo De O. Costa

Written by Luiz Gustavo De O. Costa

Hey friend!! I’m Luiz Gustavo, a Java developer and I’m here to learn and write about Java, tests and good practices

No responses yet