Overview
byte is the smallest integer data type in Java. It stores whole numbers
in 1 byte (8 bits) of memory, and its range is -128 to 127.
It's useful when you need to save memory, for example in large arrays or when working with files and network data.
Unlike float, a byte needs no suffix. Java accepts byte a = 100; because 100 is a constant that fits within the byte range.
Step-by-Step Explanation
1
Declare and Initialise byte Variables
Values must be between -128 and 127.
byte a = 100;
byte b = -50;
byte is the data type, and a and b are the variable names. Both values fit within the byte range, so they're stored without any problem.
2
Print the Values
Text and values joined with +.
System.out.println("a = " + a);
System.out.println("b = " + b);
The + operator joins the label and the value, so the output is a = 100 and b = -50.
3
Range of byte
The largest and smallest values.
System.out.println("Max byte value = " + Byte.MAX_VALUE);
System.out.println("Min byte value = " + Byte.MIN_VALUE);
Byte is the wrapper class for byte. Byte.MAX_VALUE is 127 and Byte.MIN_VALUE is -128.
With 8 bits, a byte can store $$2^8 = 256$$ different values, from $$-2^7$$ to $$2^7 - 1$$.
4
byte + byte Gives an int
Type promotion in arithmetic.
int sum = a + b;
System.out.println("sum = " + sum);
Before doing arithmetic, Java converts byte values to int. So a + b is an int, and the result 50 is stored in an int variable.
Writing byte sum = a + b; gives a compile error.
5
Overflow with a Cast
Values outside the range wrap around.
byte overflow = (byte) 130;
System.out.println("(byte) 130 = " + overflow);
130 is larger than 127, so byte overflow = 130; won't compile. The (byte) cast forces it, and the value wraps around:
$$130 - 256 = -126$$
byte at a Glance
| Property |
Value |
| Size |
1 byte (8 bits) |
| Range |
-128 to 127 |
| Default value (fields) |
0 |
| Literal suffix |
None |
| Wrapper class |
Byte |
Java Integer Types Compared
| Type |
Size |
Range |
byte |
1 byte |
-128 to 127 |
short |
2 bytes |
-32,768 to 32,767 |
int |
4 bytes |
-2,147,483,648 to 2,147,483,647 |
long |
8 bytes |
About ±9.22 × 1018 |
Output
a = 100
b = -50
Max byte value = 127
Min byte value = -128
sum = 50
(byte) 130 = -126
Common Mistakes
Assigning a value outside the range
byte a = 200; gives the error incompatible types: possible lossy conversion from int to byte.
Storing byte arithmetic in a byte
byte sum = a + b; doesn't compile because a + b is an int. Use an int variable or cast the result with (byte).
Casting without checking the range
A cast hides the error but doesn't fix it. (byte) 130 silently becomes -126.
Good practice
Use int for everyday whole numbers. Use byte only when memory matters, such as large arrays or raw file and network data.
Key Takeaway
byte stores whole numbers from -128 to 127 in 1 byte.
Arithmetic on bytes gives an int, and casting a value outside the range makes it wrap around.