Java - Data Types byte type

What is byte type?

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

The range of byte type is -128 to 127 (-2^7 to 2^7 - 1).

You can use byte type to deal with binary data in a file or over the network.

There are no byte literals. You can assign any int literal within the range of byte to a byte variable.

You can only assign an int literal between -128 and 127 to a byte variable.

For example,

byte b1 = 125; 
byte b2 = -11; 
  

If you tries to assign an int literal value outside the range of the byte data type, Java generates a compiler error.

The following piece of code will produce a compiler error:

byte b3 = 333; 

The following code will generate a compiler error, since it assigns the value of an int variable, num1, to a byte variable, b1:

int num1 = 15; 
// OK. Assignment of int literal (-128 to 127) to byte. 
byte b1 = 15; 
// A compile-time error. Even though num1 has a value of 15, which is in the range -128 and 127. 
b1 = num1; 
  

To assign from int to byte, use a cast. The assignment of num1 to b1 can be rewritten as follows:

b1 = (byte)num1; // Ok 
  

The following code shows how to cast long type to byte.

Demo

public class Main {
  public static void main(String[] args) {
    byte b = 10; 
    long num3 = 19L; 
      //  www.  j  av  a  2 s .  c o m
    b = (byte)num3;  // OK because of cast 
    System.out.println(b);
    //b = 19L;         // Error. Cannot assign long literal to byte 
    b = (byte)19L;   // OK because of cast 
    
    System.out.println(b);
  }
}

Result

Byte type

Java has a class Byte.

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

Demo

public class Main {
  public static void main(String[] args) {
    byte max = Byte.MAX_VALUE; 
    byte min = Byte.MIN_VALUE; 

    System.out.println(max);//  ww  w . j a  v a  2 s .c  o m
    System.out.println(min);
  }
}

Result

Exercise