

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Questions & Answers
- 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
- Program to evaluate s-expression as string in Python
- Mathematical Functions in Java
- Java Program to parse a mathematical expression and operators
- How MySQL virtual GENERATED COLUMNS can work with mathematical expressions?
- How MySQL stored GENERATED COLUMNS can work with mathematical expressions?
- Program to evaluate Boolean expression from a string in Python?
- Print all possible expressions that evaluate to a target in C++
- Replace one string with another string with Java Regular Expressions
- Java Program to initialize a HashMap with Lambda 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?
- Program to check valid mobile number using Java regular expressions
Advertisements