I was learning wrapper class, here I learned how to convert int to Interger wrapper class.
But I want to convert int to Byte using Byte wrapper class.
I have tried
int a =10;
Byte c = Byte; //(Not getting suggestion in eclipse)
for example, I know how to convert int to Interger refer code below.
int a =10;
Integer b = Integer.valueOf(a);
You could add an additional cast to the integer like this:
int a = 10;
Byte c = Byte.valueOf((byte)a);
Btw, going from a primitive to an Boxed value is done implicitly by the compiler. So the code above doesn't necessary need the .valueOf
:
int a = 10;
Byte c = (byte)a;
But, when you're explicitly casting values, always keep in mind that it can hold unexpected results when doing it wrong. In this case for example, the size of a a byte is smaller than an integer (the range of a byte is [-128, 127]
and of an int is [-2147483648, 2147483647]
), so something like this wouldn't give the expected result:
int a = 200;
Byte c = Byte.valueOf((byte)a); // Results in -56
This is also the reason why you usually can't go to a smaller type, since it might not fit, but you can go to a larger one without needing the cast:
byte a = 10;
Integer c = Integer.valueOf(a);