Why variable of long type is giving different answer after casting and before casting in the following code as both are of type long?

Ajit Dhdharia :
byte byteChallenge = 68;
short shortChallenge = 190;
int intChallenge = 2147483647;

long longChallenge = (50000L + 10L * (byteChallenge + shortChallenge + intChallenge));

long longChallengeX = 50000L + 10L * ((long) byteChallenge + (long) shortChallenge + (long) 
                          intChallenge);

System.out.println(longChallenge);
System.out.println(longChallengeX);

The output I'm getting is:

-21474783910
21474889050
Karol Dowbecki :

The tricky part is int intChallenge = 2147483647 constant which is the maximum value for positive int (see Integer.MAX_VALUE).

When you perform byteChallenge + shortChallenge + intChallenge it is an int arithmetic statement which results in integer overflow. In your example the integer overflow result is a negative number.

When you perform (long) byteChallenge + (long) shortChallenge + (long) intChallenge it is long arithmetic. Since long supports much larger values than int there is no overflow.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=3685&siteId=1