C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Introduction to Java

Evaluate mathematical expression with precedence - Java Program

import java.util.Scanner;

import javax.script.ScriptEngineManager;

import javax.script.ScriptEngine;

import javax.script.ScriptException;

 

public class EvaluateExpression {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

 

        System.out.print("Enter a mathematical expression: ");

        String expression = sc.nextLine();   // Example: 10 + 20 * 3 - 6 / 2

 

        // Create JavaScript engine to evaluate expression

        ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");

 

        try {

            Object result = engine.eval(expression);

            System.out.println("Result = " + result);

        }

        catch (ScriptException e) {

            System.out.println("Invalid expression!");

        }

 

        sc.close();

    }

}

Output

 
OUTPUT 1:
Enter a mathematical expression: 10 + 20 * 3
Result = 70

✅ Explanation

Multiplication happens first → 20 × 3 = 60 Then, addition → 10 + 60 = 70

OUTPUT 2: Enter a mathematical expression: (5 + 5) * 4 - 6 / 2 Result = 36

✅ Step-by-step:

Parentheses → (5 + 5) = 10 Multiplication → 10 × 4 = 40 Division → 6 ÷ 2 = 3 Subtraction → 40 – 3 = 37

(Different JavaScript engines may compute using double precision, e.g., 37 or 37.0)

Explanation of the Program

1. User enters an expression (string)

Example:

10 + 20 * 3 - 6 / 2

2. ScriptEngine evaluates the expression

Object result = engine.eval(expression);

This automatically applies operator precedence as per JavaScript rules:
Parentheses → Multiplication/Division → Addition/Subtraction

3. Result is displayed