EMZETT.
Login

byte

In short: The smallest primitive integer type in Java — 8 bits, value range from -128 to 127.

In more detail: Rarely used explicitly except for memory-critical applications (e.g. large arrays) or when processing raw binary data (e.g. byte streams during file access). Arithmetic operations with byte values automatically produce int as an intermediate result in Java, so a cast back is often necessary.

In Depth

Java stores integers as two’s complement — for byte that means: 1 bit for the sign, 7 bits for the value, giving 256 possible values (-128 to 127). If a calculation exceeds this range, there’s NO exception, just a silent overflow (“wraparound”):

byte b = 127;
b++; // no error! b is now -128 (overflow, wraps around)
 
byte[] rawData = {(byte) 0xFF, (byte) 0x00, (byte) 0x7F}; // typical use case: binary data

The most common practical use of byte is NOT storing small numbers in everyday code (for that, int is usually used out of habit), but handling raw binary data — file streams (InputStream/OutputStream work byte by byte), network packets, or image processing. Because arithmetic expressions with byte operands are automatically “promoted” to int in Java (integer promotion), the result has to be explicitly cast back if you want to store it in a byte variable again (see Assignment Operators for the special rule with +=).

byte in practice: reading files

try (InputStream in = new FileInputStream("image.png")) {
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = in.read(buffer)) != -1) {
        // bytesRead = number of bytes actually read (can be < 1024, especially at the end of the file)
        process(buffer, bytesRead);
    }
} catch (IOException e) {
    System.err.println("Error: " + e.getMessage());
}

InputStream.read(byte[]) returns -1 as soon as the end of the file is reached — analogous to readLine(), which returns null for character streams.

Signed — a Java quirk

Unlike some other languages (e.g. C with unsigned char), byte in Java is ALWAYS signed, there’s no unsigned integer type in Java. This leads to a well-known pitfall when processing binary data whose individual bytes are actually meant as values 0–255: Java automatically interprets a byte value above 127 as a negative number. The usual workaround is a bit mask:

byte raw = (byte) 0xFF; // -1 in Java, even though 255 was "actually" meant
int correct = raw & 0xFF; // 255 - the bit mask correctly removes the sign bit

Memory savings for large amounts of data

For very large arrays with many millions of small values (e.g. image data, sensor measurement series), deliberately using byte[] instead of int[] can be worthwhile — a byte array occupies only a quarter of the memory of an equally long int array (1 byte instead of 4 bytes per element).

See also: short, long, Type Casting, I/O Streams