public static void main(String args[]) {
int a = 2147483647;
System.out.println(a + 5);
}
Outputs
-2147483644
const Integer = Java.type("java.lang.Integer");
const w = new Integer(2147483647)
console.log(w + 5)
console.log(w + new Integer(5));
GraalJS with node –jvm .\ex.js outputs
2147483652
2147483652
Which is wrong. I thought GraalJS was supposed to simulate Java? How do I make it handle the overflow correctly?
>Solution :
The GraalVM JavaScript engine is designed to be compatible with standard JavaScript and to offer improved performance through its integration with the Java Virtual Machine (JVM). It is not intended to simulate Java behavior exactly, but rather to provide a way to access the capabilities of the JVM from JavaScript.
To handle integer overflow correctly in GraalJS, you can use the BigInt type, which was introduced in JavaScript in 2020. You can create a BigInt value by appending n to the end of an integer literal, like this:
const a = BigInt(2147483647);
console.log(a + BigInt(5)); // prints 2147483652n