Menu
Topics Index
...
`

Math class demo - Java Example Program


Math class demo
import java.lang.Math;                    

class MathDemo
{
    public static void main(String arg[])
    {
        int num = 9;
        if (Math.sqrt(num) * Math.sqrt(num) == num) // LINE A
            System.out.println(num + " is a perfect square");
        else
            System.out.println(num + " is not a perfect square");
        num = -2;
        System.out.println("Value of num : " + Math.abs(num)); // LINE B
        System.out.println("value when Math.ceil is used : " + Math.ceil(Math.PI)); // LINE C
        System.out.println("Value when Math.floor is used : " + Math.floor(Math.PI)); // LINE D
        num = (int) (Math.random() * 10); // LINE E
        System.out.println("Random number between 0 and 10 : " + num);    
    }
}
OUTPUT

9 is a perfect square
Value of num : 2
value when used Math.ceil : 4.0
Value when used Math.floor : 3.0
Random number between 0 and 10 : 5

DESCRIPTION

At LINE A, using sqrt() method the square root of the number is found and is squared to check whether it is a perfect square or not.
At LINE B, the absolute value of a number is returned by abs() method.
At LINE C, the number is rounded off to ceil.
At LINE D, the number is rounded off to floor.
At LINE E, a random number is returned by random() method.

THINGS TO TRY
  • Find angle between two points using the Math.cos() method and check whether the angle is acute, right angled or obtuse.
  • Find the greater of two numbers, using Math.max
  • Convert an angle in radians to degrees using Math.toDegree()

© meritcampus 2019

All Rights Reserved.

Open In App