Java Tutorial Java Advanced Java References

Java byte Keyword



The Java byte keyword is a primitive data types. The byte data type is an 8-bit signed two's complement integer. Its default value is 0 and default size is 8 bits (1 byte). The range of a byte value is -128 to 127 (inclusive).

Example: Create a byte value

In the example below, variable x and y are created to store byte values.

public class MyClass {
  public static void main(String[] args) {   
    //creating byte values
    byte x = 10;
    byte y = 20;

    //printing variables
    System.out.println("x = " + x);
    System.out.println("y = " + y);    
  }
}

The output of the above code will be:

x = 10
y = 20

Example: Narrowing Casting (larger to smaller type)

For a larger data types like double, float, long, int, and short, narrowing casting is required. The compiler explicitly typecast these data types to byte as shown in the output.

public class MyClass {
  public static void main(String[] args) {    
    double num_double = 10.5d;

    //Narrowing Casting
    float num_float = (float) num_double;
    long num_long = (long) num_float;
    int num_int = (int) num_long;
    short num_short = (short) num_int;
    byte num_byte = (byte) num_short;

    //printing variables
    System.out.println("num_double = " + num_double);
    System.out.println("num_float = " + num_float); 
    System.out.println("num_long = " + num_long);
    System.out.println("num_int = " + num_int);  
    System.out.println("num_short = " + num_short);
    System.out.println("num_byte = " + num_byte);
  }
}

The output of the above code will be:

num_double = 10.5
num_float = 10.5
num_long = 10
num_int = 10
num_short = 10
num_byte = 10

❮ Java Keywords




5