The ScriptEngine in Java (from the javax.script package) doesn’t directly define a fixed list of functions itself — instead, it provides a standard interface for embedding and executing scripts in various languages (like JavaScript, Python via Jython, Groovy, etc.).
So, the functions supported depend on which scripting language engine you’re using.
However, here’s a breakdown of all core methods (functions) that the ScriptEngine interface itself supports (i.e., methods available in Java’s javax.script.ScriptEngine API):
🧠 Supporting Interfaces
The ScriptEngine works with several related interfaces:
ScriptEngineManager– discovers and manages multiple scripting engines.ScriptEngineFactory– provides metadata (name, version, supported MIME types, etc.).Bindings– represents a set of name-value pairs (variables).ScriptContext– defines scopes and I/O settings for execution.
⚙️ Example (JavaScript via Nashorn or GraalJS)
import javax.script.*;
public class ScriptEngineDemo {
public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
engine.put("x", 10);
engine.put("y", 5);
Object result = engine.eval("x * y + 2");
System.out.println("Result: " + result);
}
}
import java.time.Year;
...
private String getSEOutput(String script) throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
// Define variables
int currentYear = Year.now().getValue();
// Pass values to the engine
engine.put("currentYear", currentYear);
// Evaluate
Object result = engine.eval(script);
System.out.println("result = " + result);
return result.toString();
}
🧩 If You’re Using a Specific Engine
Each engine (like Nashorn, GraalJS, Groovy, Jython, etc.) adds its own set of script functions — for example:
- Nashorn (JavaScript) supports all ECMAScript functions like
Math.pow,JSON.parse, etc. - Jython supports all Python built-ins like
len(),print(), etc.
(Jython is an implementation of the Python programming language that runs on the Java Virtual Machine (JVM). Unlike CPython, the standard implementation of Python written in C, Jython is entirely written in Java.) - Groovy supports Groovy’s full syntax and library functions.
let’s go deeper and write practical Java code examples that show how to use ScriptEngine in multiple useful ways.
We’ll cover:
- 🔹 Basic script evaluation
- 🔹 Using variables and bindings
- 🔹 Executing external files
- 🔹 Invoking functions from the script
- 🔹 Using custom contexts
- 🔹 Handling return values and errors
🧩 1. Basic JavaScript Evaluation
import javax.script.*;
public class ScriptEngineExample1 {
public static void main(String[] args) throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// Basic script
String script = "var a = 10; var b = 20; a + b;";
Object result = engine.eval(script);
System.out.println("Result: " + result); // ➜ 30
}
}
🧠 2. Setting and Getting Variables
import javax.script.*;
public class ScriptEngineExample2 {
public static void main(String[] args) throws ScriptException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
// Pass Java variables into script
engine.put("x", 5);
engine.put("y", 7);
engine.put("name", "Susmit");
String script = "var sum = x + y; 'Hello ' + name + '! Sum: ' + sum;";
Object output = engine.eval(script);
System.out.println(output); // ➜ Hello Susmit! Sum: 12
}
}
📄 3. Executing a Script File
import javax.script.*;
import java.io.*;
public class ScriptEngineExample3 {
public static void main(String[] args) throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
// Load external .js file
FileReader reader = new FileReader("test.js");
engine.eval(reader);
reader.close();
}
}
📘 test.js
print("Hello from JavaScript file!");
var result = 10 * 5;
print("Result: " + result);
🔧 4. Invoking Functions from a Script
import javax.script.*;
public class ScriptEngineExample4 {
public static void main(String[] args) throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
String jsCode = """
function add(a, b) {
return a + b;
}
function greet(name) {
return "Hi, " + name + "!";
}
""";
engine.eval(jsCode);
// To call script functions, we cast the engine to Invocable
Invocable inv = (Invocable) engine;
Object sum = inv.invokeFunction("add", 4, 6);
Object greet = inv.invokeFunction("greet", "Susmit");
System.out.println("Sum: " + sum); // ➜ 10
System.out.println(greet); // ➜ Hi, Susmit!
}
}
🧱 5. Using Bindings (like local variable sets)
import javax.script.*;
public class ScriptEngineExample5 {
public static void main(String[] args) throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
// Create custom bindings (isolated variable scope)
Bindings bindings = engine.createBindings();
bindings.put("a", 3);
bindings.put("b", 8);
Object result = engine.eval("a * b", bindings);
System.out.println("Result (using bindings): " + result);
}
}
⚙️ 6. Custom Script Context
import javax.script.*;
public class ScriptEngineExample6 {
public static void main(String[] args) throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
ScriptContext context = new SimpleScriptContext();
Bindings localScope = engine.createBindings();
localScope.put("pi", Math.PI);
context.setBindings(localScope, ScriptContext.ENGINE_SCOPE);
engine.eval("radius = 5; area = pi * radius * radius;", context);
System.out.println("Area = " + context.getAttribute("area")); // ➜ Area = 78.53981633974483
}
}
🚨 7. Error Handling
import javax.script.*;
public class ScriptEngineExample7 {
public static void main(String[] args) {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
try {
engine.eval("var result = x + 10;"); // x not defined
} catch (ScriptException e) {
System.err.println("Script Error: " + e.getMessage());
}
}
}
🧩 8. Using Other Languages (Groovy, Python, etc.)
If you add other scripting engines (like Groovy or Jython) to your classpath:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("groovy");
engine.eval("println 'Hello from Groovy!'");
✅ Summary
ScriptEngine can:
- Run scripts dynamically at runtime
- Inject and read Java variables
- Call functions defined in scripts
- Handle multiple languages
- Use bindings for isolated scopes
- Integrate with files, APIs, or templates
TRAIN:
looking to train or preload your ScriptEngine with multiple useful functions and variables, so scripts can reuse them dynamically (almost like a small internal library or runtime environment).
Let’s build a Java snippet that defines several helper functions (math, date/time, string utilities, finance-like, etc.) that you can inject into the ScriptEngine at runtime.
🧩 Full Example: Training ScriptEngine with Built-In Functions
import javax.script.*;
import java.time.*;
import java.util.*;
public class ScriptEngineTrainer {
public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// -------------------------------
// 1️⃣ Define Java variables
// -------------------------------
int currentYear = Year.now().getValue();
LocalDate today = LocalDate.now();
double taxRate = 0.0825;
String userName = "Susmit";
// Pass values to the engine
engine.put("currentYear", currentYear);
engine.put("today", today.toString());
engine.put("taxRate", taxRate);
engine.put("userName", userName);
// -------------------------------
// 2️⃣ Define utility functions inside the script
// -------------------------------
String preloadFunctions = """
// ---------- Date & Time ----------
function getYear() {
return currentYear;
}
function getDate() {
return today;
}
// ---------- Math Utilities ----------
function add(a, b) { return a + b; }
function subtract(a, b) { return a - b; }
function multiply(a, b) { return a * b; }
function divide(a, b) { return b === 0 ? NaN : a / b; }
function square(n) { return n * n; }
function cube(n) { return n * n * n; }
// ---------- String Utilities ----------
function greet() {
return 'Hello, ' + userName + '!';
}
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function reverse(str) {
return str.split('').reverse().join('');
}
// ---------- Finance Utilities ----------
function addTax(amount) {
return amount + (amount * taxRate);
}
function compoundInterest(principal, rate, years) {
return principal * Math.pow((1 + rate), years);
}
// ---------- Random & Utility ----------
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
}
""";
// Preload all functions
engine.eval(preloadFunctions);
// -------------------------------
// 3️⃣ Call some functions dynamically
// -------------------------------
Invocable inv = (Invocable) engine;
System.out.println("Year: " + inv.invokeFunction("getYear"));
System.out.println("Greeting: " + inv.invokeFunction("greet"));
System.out.println("5 squared: " + inv.invokeFunction("square", 5));
System.out.println("Random 1–10: " + inv.invokeFunction("randomInt", 1, 10));
System.out.println("Compound Interest: " + inv.invokeFunction("compoundInterest", 1000, 0.05, 5));
System.out.println("Reverse of 'hello': " + inv.invokeFunction("reverse", "hello"));
System.out.println("Is 2024 leap year? " + inv.invokeFunction("isLeapYear", 2024));
}
}
🧠 Output Example
Year: 2025
Greeting: Hello, Susmit!
5 squared: 25
Random 1–10: 7
Compound Interest: 1276.2815625000003
Reverse of 'hello': olleh
Is 2024 leap year? true
🧩 How It Works
- Java variables (
engine.put) — make real Java values available in JS scope. - Function definitions (via
engine.eval) — preload reusable utilities. - Invoke dynamically (via
Invocable) — call functions directly from Java code.
🧩 Optional: Add Training Modules
You can modularize these function sets:
engine.eval(getMathFunctions());
engine.eval(getDateFunctions());
engine.eval(getFinanceFunctions());
Where:
private static String getMathFunctions() { return “”” function add(a, b) { return a + b; } function subtract(a, b) { return a – b; } function multiply(a, b) { return a * b; } function divide(a, b) { return b === 0 ? NaN : a / b; } “””; }
