Fresh batch for Java, Web development, Digital Marketing, Android Application, Network security, IT security & Ethical Hacking starting from 11th March. Register now and grab a spical discounts upto 50%.... Now we are providing online classes starting very soon

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 byte, short, int, long, float and double.

byte, short, int, long support integers while float and 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 double.

Every data type has its own range. Let us take an example with byte and int.

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
Mod 0
65 / 2 = 32
Mod 1
32 / 2 = 16
Mod 0
16 / 2 = 8
Mod 0
8 / 2 = 4
Mod 0
4 / 2 = 2
Mod 0
2 / 2 = 1
Mod 0
1 / 2 = 0
Mod 1

So 130 in binary is 1000 0010. The leftmost bit is set to 1, so the result will be negative. Now flip all the bits

0 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 -126.

Leave your Comment:-