devxlogo

Be Aware Of The Signed Byte

Be Aware Of The Signed Byte

Java lets you cast an integer into a byte and vice versa. While this provides power and flexibility, we should be aware that Java’s byte data type is signed, meaning that the leftmost bit (the 8th bit) of a byte is reserved for the sign of the data it holds (1 to indicate negative, and 0 to indicate positive). This may cause unexpected results especially if we try to compare a byte with an integer. Looking at the following code snippet:

     byte aByte;     int anInt = 128;     aByte = (byte)anInt;     if (aByte == anInt)     {        System.out.println(""+anInt+" equals "+aByte);     }     else     {        System.out.println(""+anInt+" is not "+aByte);     } 

The output of this code will be:

         -128 is not 128 

Which may be unexpected since we cast the integer value of 128 into a byte, only to get -128.

This happened because the binary representation of 128 is 10000000, with the 8th bit being 1. Java’s byte data type takes only 8 bits. And, in Java, byte is a signed data type with its 8th bit reserved for the sign of the value it contains. So, instead of intended value of 128, we ended up with -128. This kind of mistakes can be the source of extremely hard to find bugs.

To avoid this type of bugs, we should pay attention to the range of values that data types can contain. The following may be used as a guideline:

? the integral types: * byte, whose values are 8-bit signed two’s-complement integers * short, whose values are 16-bit signed two’s-complement integers * int, whose values are 32-bit signed two’s-complement integers * long, whose values are 64-bit signed two’s-complement integers

? the floating point types * float, whose values are 32-bit IEEE 754 floating-point numbers * double, whose values are 64-bit IEEE 754 floating-point numbers

? the character type char, whose values are 16-bit Unicode characters

? the boolean type, whose values are true and false

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist