Create Byte object with its constructor

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

ConstructorSummary
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)
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.