≡ Menu

Repost: Rocket Java: What type should I prefer, int or byte?

From online:

Is there any benefit of using byte intead of int? I have a case where the range of possible values is between 0..100, so an int would be way to much for this, a byte is also more than sufficent for this.

But then I think about the 32 bit architecture of today’s computers, and that 32 bit is the smallest addressable unit, so does it make any difference if you use byte or int?

Well, it does make a difference, but what those differences are depends on how you’re using this data item.

A byte in java is defined in the Java Language Specification as having a range between -128 and 127 inclusive. An integer is defined as having a range between -2147483648 to 2147483647, again, inclusive.

Therefore, the byte type is defined as being eight significant bits, and an int is defined as having 32 significant bits.

That does not mean that a byte takes one byte of heap, and an int takes four. The JVM is fully allowed to use four bytes (or eight) for both of them, but it will treat them as their base type when they’re used (allowing promotion where required by the specification.)

Here’s the quote from the JLS on integral type promotion rules:

If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6). Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.

So if you use a byte in your code, it gets treated like an int, even though the range will be constrained and assignment to a byte has to be typecast.

From a code perspective, yeesh, avoid bytes.

However, if you’re doing input/output, especially over the network, or if you’re communicating with an external program that needs bytes, well… a byte is obviously smaller than an int (or a long) so if you’re counting TCP/IP packets, and a byte is sufficient, it’s nice to have around. (If you’re communicating with an external package that needs a byte, well, obviously, you’ll need to use a byte.)

To actually work on the machine’s level with individual bytes, you’re better off thinking like Python does and using JNA or JNI, in my experience. It’s not that Java can’t do it, it’s that it’s such a pain in the rear that it’s rarely actually worth it to use in anger.

Author’s Note: Reposted as “rocket java” instead of the prior “java surgery,” because I always found the name unwieldy.

{ 0 comments… add one }

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.