Java Math Class Methods
Simple programs demonstrating 8 key methods of the Math class
Note: All methods shown below are static methods of the [Link] class. No import statement is
required — they are available by default in Java. Use [Link]() to call them.
1. abs()
Returns the absolute value of a double value. The absolute value is always non-negative — negative
numbers become positive.
public class AbsDemo {
public static void main(String[] args) {
double a = -9.5;
double b = 7.3;
[Link]([Link](a)); // 9.5
[Link]([Link](b)); // 7.3
}
}
2. cbrt()
Returns the cube root of a double value. For example, the cube root of 27 is 3, because 3 x 3 x 3 =
27.
public class CbrtDemo {
public static void main(String[] args) {
double a = 27.0;
double b = 125.0;
[Link]([Link](a)); // 3.0
[Link]([Link](b)); // 5.0
}
}
3. sqrt()
Returns the square root of a double value. For example, the square root of 64 is 8, because 8 x 8 =
64.
public class SqrtDemo {
public static void main(String[] args) {
double a = 64.0;
double b = 2.0;
[Link]([Link](a)); // 8.0
[Link]([Link](b)); // 1.4142135623730951
}
}
4. pow(x, y)
Returns the value of x raised to the power of y (x^y). Both parameters and the return value are of type
double.
public class PowDemo {
public static void main(String[] args) {
double base = 2.0;
double exp = 10.0;
[Link]([Link](base, exp)); // 1024.0
[Link]([Link](3.0, 3.0)); // 27.0
}
}
5. min(x, y)
Returns the smaller of two values. Works with int, long, float, and double types.
public class MinDemo {
public static void main(String[] args) {
int a = 15;
int b = 42;
[Link]([Link](a, b)); // 15
[Link]([Link](3.7, 3.2)); // 3.2
}
}
6. max(x, y)
Returns the larger of two values. Works with int, long, float, and double types.
public class MaxDemo {
public static void main(String[] args) {
int a = 15;
int b = 42;
[Link]([Link](a, b)); // 42
[Link]([Link](3.7, 3.2)); // 3.7
}
}
7. ceil(x)
Returns the smallest double value that is greater than or equal to the argument and equal to a
mathematical integer. In other words, it rounds UP to the nearest whole number.
public class CeilDemo {
public static void main(String[] args) {
double a = 4.3;
double b = 4.9;
double c = -4.3;
[Link]([Link](a)); // 5.0
[Link]([Link](b)); // 5.0
[Link]([Link](c)); // -4.0
}
}
8. floor(x)
Returns the largest double value that is less than or equal to the argument and equal to a
mathematical integer. In other words, it rounds DOWN to the nearest whole number.
public class FloorDemo {
public static void main(String[] args) {
double a = 4.7;
double b = 4.1;
double c = -4.7;
[Link]([Link](a)); // 4.0
[Link]([Link](b)); // 4.0
[Link]([Link](c)); // -5.0
}
}
Java Math Class Methods — Simple Programs Reference