Java Math

The Math class.

✍️ 2 exercises in this lesson

The Math class provides maths functions:

  • Math.max(a, b), Math.min(a, b)
  • Math.sqrt(), Math.pow(), Math.abs()
  • Math.round(), Math.ceil(), Math.floor()
  • Math.random(): a double from 0.0 to 1.0
  • Math.PI

Key Takeaways: Java Math

Mastering Java Math helps you write clean and reliable Java code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Java Math Code Example

Java
public class Main {
    public static void main(String[] args) {
        System.out.println(Math.max(5, 10));
        System.out.println(Math.sqrt(64));
        System.out.println(Math.pow(2, 10));
        System.out.println(Math.round(4.6));
        int dice = (int) (Math.random() * 6) + 1;
        System.out.println("Dice: " + dice);
    }
}
Output
10
8.0
1024.0
5
Dice: 4
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

Java Math Practice Exercises

Check what you learned in “Java Math”.

/ 2 solved
Fill in the blank

Get the square root of 64.

Math.(64)
✓ Correct! Not quite. Try again.
Multiple choice

What range does Math.random() return?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services