C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Operators & Expressions

Java Program: Parse Mathematical Expression using Math functions

Expression Evaluated

Java Programs

import java.util.Scanner;

 

public class MathExpressionParser {

    public static void main(String[] args) {

 

        Scanner sc = new Scanner(System.in);

 

        System.out.print("Enter value of a: ");

        double a = sc.nextDouble();

 

        System.out.print("Enter value of b: ");

        double b = sc.nextDouble();

 

        System.out.print("Enter value of c: ");

        double c = sc.nextDouble();

 

        System.out.print("Enter angle in degrees: ");

        double angle = sc.nextDouble();

 

        // Convert degrees to radians for trigonometric functions

        double radians = Math.toRadians(angle);

 

        // Parsing mathematical expression

        double result = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2))

                        + Math.log(c)

                        + Math.sin(radians);

 

        System.out.printf("\nResult of the expression = %.4f\n", result);

 

        sc.close();

    }

}

Output

 
INPUT :
Enter value of a: 3
Enter value of b: 4
Enter value of c: 10
Enter angle in degrees: 30
 
OUTPUT :
Result of the expression = 6.3026

Explanation

1. Mathematical Expression

Java Programs

 

  • √(a² + b²) → Pythagorean expression
  • log(c) → Natural logarithm (base e)
  • sin(θ) → Trigonometric sine function

2. Using Math Functions in Java

Function

Purpose

Math.pow(x, y)

Calculates xy

Math.sqrt(x)

Square root

Math.log(x)

Natural log

Math.sin(x)

Sine (radians only)

Math.toRadians(x)

Converts degrees to radians

3. Parsing the Expression

double result = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2))

                + Math.log(c)

                + Math.sin(radians);

  • Java evaluates the expression step by step using Math library functions.

4. Output Formatting

System.out.printf("%.4f", result);

  • Displays result up to 4 decimal places for accuracy.

Key Concepts Used

Mathematical expressions
Math class functions
Order of operations
Degree-to-radian conversion
Formatted output

📌 Short Exam Answer

This program evaluates a mathematical expression by parsing it into Java Math functions such as sqrt, pow, log, and sin. It demonstrates accurate computation using built-in mathematical methods.