Online-IDE icon indicating copy to clipboard operation
Online-IDE copied to clipboard

data types - int, short, long

Open Bruuk opened this issue 1 year ago • 1 comments

data types - int, short, long not working correct:

int i = 9223372036854775807;
short j = i;
long k = i;
println(i);
println(j);
println(k);

i = 9223372036854776000 j = 9223372036854776000 k = 9223372036854776000 but short max value is 32,767 long is 9223372036854775807 int is 2147483647

Bruuk avatar Oct 19 '23 08:10 Bruuk

The online-ide executes java code by translating it to a pseudocode and then executing this pseudocode by a interpreter written in javascript. Therefore executing java code inside the online-ide is slow compared to executing it in a Java Runtime Environment. To mitigate this the online-ide represents all java number types internally as javascript numbers (there is only one number data type in javascript!) and uses javascript's mathematical operations (+, -, *, /) on them. This leads to the behaviour you describe. Alternatively i could have inserted extra code to enforce java behaviour, but this would have slowed down program execution significantly.

Example: To add two integers, the online-ide now does this:

   return value + <number>(secondOperand.value);

(see here)

To enforce java behaviour you would have to simulate integer-wraparound:

   return (value + <number>(secondOperand.value) + 2147483648) % (2*2147483647) - 2147483648 ;

I decided not to take this approach but to opt for performance. I know that this is a dirty compromise, but given the two aforementioned alternatives i still think it's the better one.

Can you live with it?

martin-pabst avatar Oct 19 '23 12:10 martin-pabst