Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class Main {
    public static void main(String[] args) throws Exception {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");

        if (!(engine instanceof Compilable)) {
            System.out.println("Script compilation not supported.");
            return;
        }
        Compilable comp = (Compilable) engine;

        CompiledScript cScript = comp.compile("print(n1 + n2)");

        Bindings scriptParams = engine.createBindings();
        scriptParams.put("n1", 2);
        scriptParams.put("n2", 3);
        cScript.eval(scriptParams);

        scriptParams.put("n1", 9);
        scriptParams.put("n2", 7);
        cScript.eval(scriptParams);
    }
}