Daniel Kvist
Daniel Kvist

Reputation: 3042

How to use square brackets for math in Java?

While converting a mathematical formula to Java, I encountered square brackets (I found them in the formula). I don't know what they mean in mathematics, because I'm no math expert, just a 14-year old hobby-programmer (so I've not reached to these "difficulty-levels" in math in school).

It's obvious that I can't write something like this:

double x = [5 / 2] * (3 + 5 * 2);

because [ and ] are used for arrays.

Therefore, I wonder what to replace them with in order to make Java accept it and interpret it correctly.

Upvotes: 0

Views: 5385

Answers (2)

codechefvaibhavkashyap
codechefvaibhavkashyap

Reputation: 1015

Square brackets can replaced by parenthesis. I assume you're aware about BODMAS used for mathematics problem resolution, hence brackets are used for separation and prioritizing operators .

double x = (5 / 2) * (3 + 5 * 2);
System.out.println(x);
double y = 5 / 2 * 3 + 5 * 2;
System.out.println(y);

above code snippet gives output:-

26.0

16.0

Upvotes: 0

Am_I_Helpful
Am_I_Helpful

Reputation: 19168

You can remove those square brackets and replace them with normal parentheses ().

double x = (5 / 2) * (3 + 5 * 2);

Based on the priority, the first statement to be evaluated will be the square-bracket statement because of highest-precedence and left-to-right associativity in solving this particular expression.

Upvotes: 4

Related Questions