Can we convert int to Byte using wrapper class, without type casting?

Vinay Pandey :

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);
Kevin Cruijssen :

You could add an additional cast to the integer like this:

int a = 10;
Byte c = Byte.valueOf((byte)a);

Try it online.

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;

Try it online.

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

Try it online.

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);

Try it online.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=132486&siteId=1