Java Data Type Tutorial - Java byte Data Type








The byte data type is an 8-bit signed Java primitive integer data type.

Its range is -128 to 127 (-27 to 27 - 1).

byte type is the smallest integer data type available in Java.

byte variables are used when a program uses a large number of variables whose values fall in the range -128 to 127 or when dealing with binary data in a file or over the network.

There are no byte literals. We can assign any int literal that falls in the range of byte to a byte variable.

For example,

byte b1 = 125;
byte b2 = -11;

If we assign an int literal to a byte variable and the value is outside the range of the byte data type, Java generates a compiler error.

We can only assign an int literal between -128 and 127 to a byte variable. But we can assign the value stored in an int variable, which is in the range of -128 to 127, to a byte variable.

In Java we cannot assign the value of a variable of a higher range data type to the variable of a lower range data type because there is a possible loss of precision in making such an assignment.

To make such an assignment from int to byte, we must use a cast.

The assignment of num1 to b1 can be rewritten as follows:

int num1 = 1;
byte b1  = (byte)num1; // Ok

Java has a class Byte, which defines two constants to represent maximum and minimum values of the byte data type, Byte.MAX_VALUE and Byte.MIN_VALUE.

byte   max = Byte.MAX_VALUE;
byte   min = Byte.MIN_VALUE;