byte

The byte type is an 8-bit, signed, two's-complement quantity. The reasons for using byte are to hold a generic 8-bit value, to match a value in existing data files, or to economize on storage space where you have a large number of such values. Despite popular belief, there is no speed advantage in arithmetic on shorter types like bytes, shorts, or chars—modern CPUs take the same amount of time to load or multiply 8 bits as they take for 32 bits.

example declaration:

byte heightOfTide;

range of values: –128 to 127

literals: There are no byte literals. You can use, without a cast, int literals provided their values fit in 8 bits. You can use char, long, and floating-point literals if you cast them.

You always have to cast a (non-literal) value of a larger type if you want to put it into a variable of a smaller type. Since arithmetic is always performed at least at 32-bit precision, this means that assignments to a byte variable must always be cast into the result if they involve any arithmetic, like this:

byte b1=1, b2=2;
byte b3 = b2 + b1; // NO! NO! NO! compilation error
byte b3 = (byte) (b2 + b1); // correct, uses a cast

People often find this surprising. If I have an expression involving only bytes, why should I need to cast it into a byte result? The right way to think about it is that most modern computers do all integral arithmetic at 32-bit or 64-bit precision (there is no “8-bit add” instruction on modern CPUs). Java follows this model of the underlying hardware.

An arithmetic operation on two bytes potentially yields a bigger result than can be stored in one byte. The philosophy for numeric casts is that they are required whenever you assign from a more capacious type to a less capacious type. This is termed a narrowing primitive conversion, and it may lose information about the overall magnitude of a numeric value. It may also lose some digits of precision, and sign information (when converting to char, because chars are always interpreted as positive values).

The cast tells the compiler that you, the programmer understand the information that may be lost, and have programmed accordingly. You might check the data before the conversion to ensure it is within a range where no information will be lost, for example.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.93.141