Why do we get data inconsistency while typecasting numbers with bigger value to integral data types with smaller range in Java?
Debashis Maharana, Aug 10/2019
The integral data types deal with numbers in Java. The integral data types supported by Java are
long support integers while
double support numbers with decimal point.
When we place an integer number in our program, it is by default taken as
int type. If we place a floating-point number, it is by default taken as
Every data type has its own range. Let us take an example with
byte can hold 1 byte while
int can hold 4 bytes. We can convert data of one data type to another data type. This is called type casting. When data is type casted without our concern it is called implicit type casting else explicit.
Here 10 is assigned to a variable of data type byte.
Here the value 10 is taken as int and implicitly type casted to byte. Since 10 falls within the range of byte so it is possible. But if we write:-
The compiler shows error. It’s because bigger data type (int) cannot be stored in smaller data type (byte). Thus we need to typecast it explicitly.
Here the output is -126 and not 130. Why?
Here is the answer for this inconsistency. Since byte data type is 1 byte, it has a range of -128 to 127. Here 130 is greater than 127 and is out of the range of byte data type. Here we can have the following calculation:-130 / 2 = 65
65 / 2 = 32
32 / 2 = 16
16 / 2 = 8
8 / 2 = 4
4 / 2 = 2
2 / 2 = 1
1 / 2 = 0
So 130 in binary is 1000 0010. The leftmost bit is set to 1, so the result will be negative. Now flip all the bits0 1 1 1 1 1 0 1
Now add 1
0 1 1 1 1 1 1 0
In decimal it is 126 but remember that the leftmost bit was 1 then the number is negative so the result is