简体   繁体   中英

Why Nashorn adds two integer produces double?

I am using java nashorn to evaluate javascript, some behavior related to numbers confuses me.

ScriptEngine nashorn = new ScriptEngineManager().getEngineByName("nashorn");
Object result = nashorn.eval("3 + 3");

this gives 6 with type java.lang.Integer ,

but

ScriptEngine nashorn = new ScriptEngineManager().getEngineByName("nashorn");
nashorn.put(three, 3);
Object result = nashorn.eval("three + 3");

This gives 6.0 with type java.lang.Double .

why is this happening?

I am expecting, with nashorn.put(three, 3) should give 6 , nashorn.put(three, 3.0) should give 6.0 , is it possible? any idea?

My guess is that nashorn first compiles an expression to byte code or some intermediate code, then evaluates it. The compiler can evaluate the first expression because all values are literal whereas the second is evaluated at run time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM