Skip to content
Advertisement

How do you get absolute values and square roots

How do you get a square root and an absolute value in Java?

Here is what I have:

if (variable < 0) {
    variable = variable + variable2;
}

But is there an easier way to get the absolute value in Java?

variable = |variable|

Advertisement

Answer

Use the static methods in the Math class for both – there are no operators for this in the language:

double root = Math.sqrt(value);
double absolute = Math.abs(value);

(Likewise there’s no operator for raising a value to a particular power – use Math.pow for that.)

If you use these a lot, you might want to use static imports to make your code more readable:

import static java.lang.Math.sqrt;
import static java.lang.Math.abs;

...

double x = sqrt(abs(x) + abs(y));

instead of

double x = Math.sqrt(Math.abs(x) + Math.abs(y));
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement