- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to evaluate mathematical expressions in String
To evaluate mathematical expression in String, use Nashorn JavaScript in Java i.e. scripting. Nashorn invoke dynamics feature, introduced in Java 7 to improve performance.
For scripting, use the ScriptEngineManager class for the engine −
ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
Now for JavaScript code from string, use eval i.e. execute the script. Here, we are evaluating mathematical expressions in a string −
Object ob = scriptEngine.eval("9 + 15 + 30"); System.out.println("Result of evaluating mathematical expressions in String = "+ob);
Example
import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; public class Main { public static void main(String[] args) throws Exception { ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript"); // JavaScript code from String Object ob = scriptEngine.eval("9 + 15 + 30"); System.out.println("Result of evaluating mathematical expressions in String = "+ob); } }
Output
Result of evaluating mathematical expressions in String = 54
- Related Articles
- Java Program to convert mathematical string to int
- Program to evaluate one mathematical expression without built-in functions in python
- Removing parentheses from mathematical expressions in JavaScript
- Java Program to parse a mathematical expression and operators
- Program to evaluate s-expression as string in Python
- Mathematical Functions in Java
- Program to evaluate Boolean expression from a string in Python?
- How MySQL virtual GENERATED COLUMNS can work with mathematical expressions?
- How MySQL stored GENERATED COLUMNS can work with mathematical expressions?
- Replace one string with another string with Java Regular Expressions
- How to remove consonants from a string using regular expressions in Java?
- How to remove vowels from a string using regular expressions in Java?
- Java Program to initialize a HashMap with Lambda Expressions
- Print all possible expressions that evaluate to a target in C++
- Program to check valid mobile number using Java regular expressions

Advertisements