Java
Math constants
Learn built-in constants like Math.PI.
Math constants
Java's Math class provides mathematical constants and methods. The best-known constants are Math.PI (the number pi) and Math.E (the number e). These constants are static final and can be used directly.
Example: double area = Math.PI * radius * radius;. Here Math.PI gives the number pi; approximately 3.14159. It is used to calculate a circle's area. Math.E is the natural logarithm base; approximately 2.71828. You do not need to define these constants yourself; the Math class provides them ready. Math also contains methods like abs, max and sqrt; these are static and called through the class name.
Math methods
The Math class also provides mathematical methods: Math.abs for absolute value, Math.max for the largest, Math.sqrt for square root. All are static and called through the class name.
Example: int absVal = Math.abs(-5); returns five. int big = Math.max(3, 7); returns seven. double root = Math.sqrt(16); returns four. These methods are called as Math.methodName(...) without an instance. The Math class's constructor is hidden; new Math() cannot be written. All members are static. This is the typical design of utility classes.
Exercise Use Math constants and methods
In a main method calculate a circle's area. Write double radius = 5.0. Calculate the area with double area = Math.PI * radius * radius;. Get the absolute value with int absVal = Math.abs(-10);. Print the area and absVal values on separate lines.
Show example solution
public class Main {
public static void main(String[] args) {
double radius = 5.0;
double area = Math.PI * radius * radius;
int absVal = Math.abs(-10);
System.out.println(area);
System.out.println(absVal);
}
}
Test yourself
-
Which constant is used for a circle's area?
- Math.PI
- Math.E
- Math.AREA
- Math.RADIUS
Show answer
Math.PI — Math.PI gives the number pi; it is used in circle area.
-
Complete the Math.abs call
int result = ____;
Show answer
int result = Math.abs(-5);
-
Match Math members
- Math.abs
- Absolute value
- Math.max
- Largest
- Math.sqrt
- Square root
- Math.PI
- Pi number
Next lesson: Summary - Constants