Sai Sankalp - 1 year ago 53

Java Question

Recently,while I was going through typecasting concept in java, I have seen that type casting of larger variable to smaller variable results in the modulo of larger variable by the range of smaller variable.Can anyone please explain this in detail why this is the case and is it true for any explicit type conversion?.

`class conversion {`

public static void main(String args[])

{

double a = 295.04;

int b = 300;

byte c = (byte) a;

byte d = (byte) b;

System.out.println(c + " " + d);

}

}

The above code gives the answer of d as 44 since 300 modulo 256 is 44.Please explain why this is the case and also what happens to the value of c?

Answer Source

It is a design decision that goes all the way back the the C programming language and possiblty to C's antecedents too.

What happens when you convert from a larger integer type to a smaller integer type is that the top bits are lopped off.

Why? Originally (and currently) because that is what hardware integer instructions support.

The "other way" to do this would be to convert to that largest (or smallest) value representable in the smaller type; e.g.

```
int i = 300;
byte b = (byte) i;
```

would give +127 as the value of `b`

. Incidentally, this is what happens when you convert a floating-point value to an integer value, and the value is too large. That is what is happening in your `c`

example.

You also said:

The above code gives the answer of d as 44 since 300 modulo 256 is 44.

In fact, the correct calculation would be:

```
int d = ((b + 128) % 256) - 128;
```

That is because the range of the Java `byte`

type is -128 to +127.