- 3,724,396 Users
- 2,244,746 Discussions
- 7,850,991 Comments
Forum Stats
Discussions
Categories
- 16 Data
- 362.2K Big Data Appliance
- 7 Data Science
- 2.1K Databases
- 623 General Database Discussions
- 3.7K Java and JavaScript in the Database
- 32 Multilingual Engine
- 497 MySQL Community Space
- 7 NoSQL Database
- 7.7K Oracle Database Express Edition (XE)
- 2.8K ORDS, SODA & JSON in the Database
- 422 SQLcl
- 62 SQL Developer Data Modeler
- 185.1K SQL & PL/SQL
- 21.1K SQL Developer
- 2.5K Development
- 3 Developer Projects
- 32 Programming Languages
- 135.7K Development Tools
- 14 DevOps
- 3K QA/Testing
- 338 Java
- 10 Java Learning Subscription
- 12 Database Connectivity
- 72 Java Community Process
- 2 Java 25
- 12 Java APIs
- 141.2K Java Development Tools
- 8 Java EE (Java Enterprise Edition)
- 153K Java Essentials
- 135 Java 8 Questions
- 86.2K Java Programming
- 270 Java Lambda MOOC
- 65.1K New To Java
- 1.7K Training / Learning / Certification
- 13.8K Java HotSpot Virtual Machine
- 16 Java SE
- 13.8K Java Security
- 4 Java User Groups
- 22 JavaScript - Nashorn
- 18 Programs
- 147 LiveLabs
- 34 Workshops
- 10 Software
- 4 Berkeley DB Family
- 3.5K JHeadstart
- 5.7K Other Languages
- 2.3K Chinese
- 4 Deutsche Oracle Community
- 16 Español
- 1.9K Japanese
- 3 Portuguese
What is the difference between eval and compile methods

jdalecki-JavaNet
Member Posts: 8
Hi,
I am pretty new to Java Script in javax.script package. I am just wondering and scratching my head off to understand the difference between
Compilable.compile(String script) and ScriptEngine.eval(String script).
Let’s assume I get somehow the “engine” object:
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
Let’s say I have a script string like this: string = “function raiseAlarm()
{
var now = new java.util.Date();
print("major " + now);
}”
If I evaluate it and call it this way:
engine.eval(string);
Invocable inv = (Invocable) engine;
inv.invokeFunction("raiseAlarm”);
… Well it works (no compilation involved)
However if I compile it and then not evaluate it and then try to call a method (“raiseAlarm”) I get an exception java.lang.NoSuchMethodException: No such function raiseAlarm. (Something like this):
Compilable compEngine = (Compilable) engine;
script = compEngine.compile(string);
Invocable inv = (Invocable) engine;
inv.invokeFunction("raiseAlarm”);
So my question is what is the point of compiling that script string if I still have to evaluate it to get a result without an error? What have I achieved by compiling it?
Kind Regards,
Janusz
Answers
-
In the compile mode any number of statements can be compiled into bytecode that implicitly always returns None. whereas in 'eval' mode it a single expression into bytecode is compiled that returns the value of that expression.