byte

The primitive type "byte" represents an integer number between -128 and 127. It requires 1 byte of memory, that is 8 bits.

This data type is typically used to represent pieces of data in file system, for example for file input/output operations, or storing media objects in memory. (It is usually not used for calculations, because Java will automatically convert it to "int". Therefore, even if you want to store a very small integer number, use type "int". Unless you need thousands of them, in which case "byte[]" will help you reduce memory usage, but the program will be slower.)

This is how values are stored in the memory: Each bit has a specified value. Value of the whole "byte" is the sum of the values of active bits. Note the negative value for the highest bit.

BitValue
7.-128
6.64
5.32
4.16
3.8
2.4
1.2
0.1

Class java.lang.Byte

The class "Byte" wraps the value of one "byte". That means, if you want to use a "byte" value in a context where an object is required, you can use a corresponding "Byte" object instead. (For example, collections and maps can only use objects, so if you want to have a collection of "byte" values, you have to declare it as a collection of "Byte" objects.)

Useful constants:

System.out.println(Byte.MAX_VALUE);  // -128
System.out.println(Byte.MIN_VALUE);  // 127

Converting "byte" and "Byte" to and from various data types:

From typeTo typeCode
byteByte
Byte objB = Byte.valueOf(b);
Byte objB = b;
Bytebyte
byte b = objB.byteValue();
byte b = objB;
Stringbyte
byte b = Byte.parseByte(s);
StringByte
Byte objB = Byte.valueOf(s);
Byte objB = Byte.decode(s);
byteString
String s = Byte.toString(b);
String s = "" + b;

viliam@bur.sk