"byte FOO = 0xFE;"
Doesn't work in java.
"Cannot convert from into to byte" but it works on C++.
How to solve this?
"byte FOO = 0xFE;"
Doesn't work in java.
"Cannot convert from into to byte" but it works on C++.
How to solve this?
Value 0xFE is equivalent to 254 in int, and is not in the range of byte, so no implicit typecasting would be done, if you try to store it in a byte.
Your RHS value must be in range [-128 to 127] to get accommodated in byte.
Or, you can tell the compiler explicitly to store it, by explicit typecasting:
byte FOO = (byte)0xFE;
However, if you store a value that can fit in range of byte then no explicit typecasting would be needed.
byte FOO = 0x20; // OK, can accommodate in byte.
See JLS - Section # 5.1 for more details about type conversions.
And JLS - Section # 5.2 which specifically discusses Assignment Conversion
To quote a statement from JLS: -
A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
Either:
long FOO = 0xFE; //Use long as type
or
byte FOO = (byte)0xFE; //Typecast to byte.
By using hexadecimal numbers, The compiler will identify if the value fits between the range for byte [-128, 127]. Since, 0xFE is greater than 127, you will have to use an int or long since it's out of range for byte.
Your example is called Narrowing conversion.