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:

JavaScript

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

JavaScript

Advertisement

Answer

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

JavaScript

(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:

JavaScript

instead of

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement