Purpose of byte type in Java

Hải Phong picture Hải Phong · Apr 24, 2013 · Viewed 17k times · Source

I read this line in the Java tutorial:

byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

I don't clearly understand the bold line. Can somebody explain it for me?

Answer

Mr. Adobo picture Mr. Adobo · Apr 24, 2013

Byte has a (signed) range from -128 to 127, where as int has a (also signed) range of −2,147,483,648 to 2,147,483,647.

What it means is that since the values you're going to use will always be between that range, by using the byte type you're telling anyone reading your code this value will be at most between -128 to 127 always without having to document about it.

Still, proper documentation is always key and you should only use it in the case specified for readability purposes, not as a replacement for documentation.