Create Byte object with its constructor

These are the two constructors from Byte class. We can use them to create Byte object.

Byte(byte value)
Creates a Byte object for byte value.
Byte(String s)
Creates a Byte object for the byte value indicated by the String parameter.

public class Main {
  public static void main(String[] args) {

    Byte byteObject = new Byte("100");
    System.out.println(byteObject);

    byte b = 101;
    Byte byteObject2 = new Byte(b);
    System.out.println(byteObject2);

  }
}

The output:


100
101

You cannot pass integer literal to the constructor directly as Java think it is an int not a byte.


public class Main {
  public static void main(String[] args) {

    Byte byteObject2 = new Byte(101);
    System.out.println(byteObject2);

  }
}

When you try to compile the code above, the compiler will output the following error message:


Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The constructor Byte(int) is undefined

    at Main.main(Main.java:4)
Home 
  Java Book 
    Essential Classes  

Byte:
  1. Byte
  2. Find out byte's max value, min value and size
  3. Create Byte object with its constructor
  4. Convert Byte to byte, double, float, int, long and short
  5. Decode a string to a byte
  6. Byte class defines static methods to convert string value to byte value
  7. Convert byte value to string value
  8. Compare two byte values