Byte data type and class in Java explained


The byte type is the smallest primitive integer type available in Java. The type is based on an 8-bit signed two’s complement integer, which means it can store an integer value between -128 and 127.

Here’s how you declare a variable of byte type in Java:

class Example {
  public static void main(String[] args) {
    byte n = 8;
    System.out.println(n); // 8
  }
}

When you put an integer higher than 127 or lower than -128, Java will throw an incompatible types error:

class Example {
  public static void main(String[] args) {
    byte n = 128; // incompatible types: possible lossy conversion from int to byte
    System.out.println(n);
  }
}

Because byte is an integer type, you can do the usual arithmetic operations on byte type variables as follows:

class Example {
  public static void main(String[] args) {
    byte n = 27;
    byte b = 2;
    System.out.println(n+b); // 29
  }
}

The byte type also has the Byte class, which wraps the primitive type in an object, providing useful methods and constants to manipulate the byte type data.

Byte class in Java

The Byte class allows you to create a Byte object, allowing you to manipulate a byte data using the following available methods:

  • byteValue() - Returns the byte value from the current Byte instance
  • compareTo(Byte anotherByte) - Compare two Byte objects numerically. Returns int value of 0 when they are equal, less than 0 when anotherByte is larger, and greater than 0 when anotherByte is smaller
  • decode(String nm) - Decodes a String into a Byte
  • doubleValue() - Returns the value of this Byte as a double type
  • equals(Object obj) - Compares the Byte instance to another Object. Returns boolean value of true or false
  • floatValue() - Returns the value of this Byte as a float type
  • intValue() - Returns the value of this Byte as an int type
  • longValue() - Returns the value of this Byte as a long type
  • parseByte(String s) - Parses the string argument as a signed decimal byte
  • toString() - Returns a String object representing the specified byte

For example, you can turn a byte type into a String object by using the toString() method as follows:

class Example {
  public static void main(String[] args) {
    Byte n = new Byte("102");
    String str = n.toString();
    System.out.println(str); // 102
  }
}

And that’s how both byte type and Byte class work in Java.

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.