Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

GraallJS simulating integer overflow

   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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading