Search code examples
javavariablestypessize

Do you consider the size of the data type when you creating variables?


When we create a variable, do we need to think about the size of the data type? For example int myNum = 125; or byte myNum = 125; I asked this question to know your ideas according to your practical experiences. Thanks!


Solution

  • Use int unless you have good reason to do otherwise. This is the "natural" size for the implementation.

    • long if values can reasonably be expected to exceed the range of plain integers.

    • short or byte if you're matching some external requirements (protocol structures, etc) or just possibly if you're expected a large (hundreds of thousands?) quantity of them.

    As an example of the consideration I might give: let's say I need to generate an integer id for something. If I figure I might generate them once a millisecond on average, then using int I'm going to run out after about 27 days of uptime, which feels sort of low, so long seems a better choice.