Integers
in Java are stored in 32 bits; bytes
are stored in 8 bits.
Let's say you have an array with one million entries. Yikes! That's huge!
int[] foo = new int[1000000];
Now, for each of these integers in foo
, you use 32 bits or 4 bytes of memory. In total, that's 4 million bytes, or 4MB.
Remember that an integer
in Java is a whole number between -2,147,483,648 and 2,147,483,647 inclusively. What if your array foo
only needs to contain whole numbers between, say, 1 and 100? That's a whole lot of numbers you aren't using, by declaring foo
as an int
array.
This is when byte
becomes helpful. Bytes
store whole numbers between -128 and 127 inclusively, which is perfect for what you need! But why choose bytes
? Because they use one-fourth of the space of integers. Now your array is wasting less memory:
byte[] foo = new byte[1000000];
Now each entry in foo
takes up 8 bits or 1 byte of memory, so in total, foo
takes up only 1 million bytes or 1MB of memory.
That's a huge improvement over using int[]
- you just saved 3MB of memory.
Clearly, you wouldn't want to use this for arrays that hold numbers that would exceed 127, so another way of reading the bold line you mentioned is, Since bytes are limited in range, this lets developers know that the variable is strictly limited to these bounds. There is no reason for a developer to assume that a number stored as a byte would ever exceed 127 or be less than -128. Using appropriate data types saves space and informs other developers of the limitations imposed on the variable.