askvity

How to calculate cube root in Java?

Published in Java Math Functions 2 mins read

You can calculate the cube root of a number in Java using the Math.cbrt() method.

Using the Math.cbrt() method

The Math.cbrt() method is the most straightforward way to calculate the cube root of a number in Java. It's part of the Math class, which provides numerous mathematical functions.

Syntax

double result = Math.cbrt(double num);

Where:

  • num: The number for which you want to calculate the cube root. This can be any real number (positive, negative, or zero).
  • result: A double representing the cube root of num.

Example

public class CubeRootExample {
    public static void main(String[] args) {
        double number = 27.0;
        double cubeRoot = Math.cbrt(number);
        System.out.println("The cube root of " + number + " is: " + cubeRoot); // Output: The cube root of 27.0 is: 3.0

        double negativeNumber = -8.0;
        double cubeRootNegative = Math.cbrt(negativeNumber);
        System.out.println("The cube root of " + negativeNumber + " is: " + cubeRootNegative); // Output: The cube root of -8.0 is: -2.0
    }
}

Special Cases

The Math.cbrt() method handles special cases as follows (as stated in the reference):

  • NaN (Not-a-Number): If the argument num is NaN, the return value will also be NaN.

Table Summary

Method Description Argument Type Return Type Example
Math.cbrt(num) Returns the cube root of the given number num. double double Math.cbrt(27.0)

Related Articles