Java has implicit type conversions in built for most of the convertable types, such as conversion from int to long, and byte to short, int and long, float to double and even char to int.
But never from a short to byte, doing so would cause a compilation error.
Conversion at the computational level is rather different. Though we would implicitly understand a conversion of short 127 to byte 127, the compiler has a warning built in. This is because of potential loss of information when converting from a high bit type to a lower one.
short shorty = 127;
byte bitty = shorty;
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from short to byte
at typeConversion.Demo01.main(Demo01.java:7)
Of course, we can force Java to convert things with "strong conversion", thereby absolving the compiler of all responsibility.
short shorty = 127;
byte bitty = (byte) shorty;
System.out.println(bitty);
And as expected, it can run perfectly fine.
But what happens if you try to convert something larger?
short shorty = 128;
byte bitty = (byte) shorty;
System.out.println(bitty);
Unexpectedly, it can still compile even though the Byte type in Java has a valid range of -128 ~ 127. The printed result is not 128 as expected, but rather -128.
-128
So what happened? When you convert something what happens at the computational level is that bits of information (0s and 1s) are moved over into that type, like below.
In technical terms, the leftmost bit is the signed. All Java number types are signed, meaning that one of the bit is used to check if the value is positive or negative. When converting from Short, the value 128 is stored as a 1 in the same place as the sign for Byte, causing that to shift over and resulting in:
Type | sign | 16384 | 8192 | 4096 | 2048 | 1024 | 512 | 256 | 128/sign | 64 | 32 | 16 | 8 | 4 | 2 | 1 | Result | |
Short | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 128 | |
Byte | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 127 | |||||||||
Convert | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -128 |
This is also behind what happens in an overflow bug, where going over the value's valid representations will cause it to overflow into the negatives.