In Java does anyone use short or byte?
They are used when programming for embedded devices that are short on memory or disk space. Such as appliances and other electronic devices.
Byte is also used in low level web programming, where you send requests to web servers using headers, etc.
The byte
datatype is frequently used when dealing with raw data from a file or network connection, though it is mostly used as byte[]
. The short
and short[]
types are often used in connection with GUIs and image processing (for pixel locations & image sizes), and in sound processing.
The primary reason for using byte
or short
is one of clarity. The program code states uncategorically that only 8 or 16 bits are to be used, and when you accidentally use a larger type (without an appropriate typecast) you get a compilation error. (Admittedly, this could also be viewed as a nuisance when writing the code ... but once again the presence of the typecasts flags the fact that there is truncation happening to the reader.)
You don't achieve any space saving by using byte
or short
in simple variables instead of int
, because most Java implementations align stack variables and object members on word boundaries. However, primitive array types are handled differently; i.e. elements of boolean
, byte
, char
and short
arrays are byte aligned. But unless the arrays are large in size or large in number, they doesn't make any significant contribution to the app's overall memory usage.
So I guess that the main reason that developers don't use byte
or short
as much as you (a C developer?) might expect is that it really doesn't make much (or often any) difference. Java developers tend not to obsess over memory usage like old-school C developers did :-).
In a 64-bit processor, the registers are all 64-bit so if your local variable is assigned to a register and is a boolean, byte, short, char, int, float, double or long it doesn't use memory and doesn't save any resources. Objects are 8-byte aligned so they always take up a multiple of 8-byte in memory. This means Boolean, Byte, Short, Character, Integer, Long , Float and Double, AtomicBoolean, AtomicInteger, AtomicLong, AtomicReference all use the same amount of memory.
As has been noted, short types are used for arrays and reading/writing data formats. Even then short is not used very often IMHO.
Its also worth noting that a GB cost about £80 in a server, so a MB is about 8 pence and a KB is about 0.008 pence. The difference between byte and long is about 0.00006 pence. Your time is worth more than that. esp if you ever have a bug which resulted from having a data type which was too small.