In Java does anyone use short or byte?

前端 未结 11 902
挽巷
挽巷 2020-12-14 15:44

Apart from using (byte[]) in streaming I don\'t really see byte and short used much. On the other hand I have seen long used where the actual value is |100| and byte would b

11条回答
  •  再見小時候
    2020-12-14 16:11

    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 :-).

提交回复
热议问题