Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

byte — signed 8-bit integer type

The primitive byte type stores integers from -128 to 127. Learn the limits Byte.MIN_VALUE and Byte.MAX_VALUE, the distinction between byte and Byte, promotion to int, and the effects of a narrowing cast.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

byte name = value;
Byte boxed = name;

byte is a keyword naming a primitive, signed 8-bit integer type that uses two's-complement representation. Its range is -128 through 127 inclusive. The constants Byte.MIN_VALUE and Byte.MAX_VALUE, both of type byte, specify the lower and upper limits respectively. This type is useful for representing binary data.

byte and Byte are not the same: Byte is a wrapper class in java.lang. The assignment Byte boxed = value; automatically wraps a byte value (boxing). A Byte variable can hold null, whereas a byte variable cannot. Automatically unwrapping (unboxing) null causes a NullPointerException.

The assignment byte value = 127; is valid because the constant fits the range; byte value = 128; is a compile-time error. Adding two byte values promotes the operands to int, so the result also has type int. A (byte) cast narrows an integral value by retaining only its lowest eight bits; it does not check the range. Consequently, (byte) 128 produces -128 rather than throwing an exception. When casting a float or double to byte, Java first converts the value to int under its floating-point conversion rules, then narrows that int to byte.

The example demonstrates both limits, an int addition result, narrowing, and boxing. It targets Java SE 21; the repository's production runtime version has not been attested.

Examples

public class Main {
    public static void main(String[] args) {
        byte value = Byte.MAX_VALUE;
        int sum = value + 1;
        byte wrapped = (byte) sum;
        Byte boxed = value;

        System.out.println(Byte.MIN_VALUE + ".." + Byte.MAX_VALUE);
        System.out.println(sum);
        System.out.println(wrapped);
        System.out.println(boxed);
    }
}

Result

-128..127
128
-128
127

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources