import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class GlobalvariableTest { public static void main(String[] args) { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine1 = manager.getEngineByName("nashorn"); try { engine1.eval("var sum = 0;"); } catch (ScriptException e) { // TODO Auto-generated catch block e.printStackTrace(); } // set global variable manager.setBindings(engine1.getBindings(ScriptContext.ENGINE_SCOPE)); ScriptEngine engine2 = manager.getEngineByName("nashorn"); try { engine2.eval("sum = 150;", engine2.createBindings()); engine2.eval("print(sum);", engine2.createBindings()); } catch (ScriptException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }