Math in Java
Math In Java
Java Math Class helps you to perform mathematical calculations efficiently. If you want to perform math calculations like finding a square root, power of a certain number, or round a specific number, we can use java math.
public class Main {
public static void main(String[] args) {
System.out.println("Maximum Value "+ Math.max(10, 20)); // output 20
System.out.println("Min Value "+ Math.min(10, 30)); // output 10
System.out.println("Round Value "+Math.round(10.99)); // output 11
System.out.println("Floor Value "+Math.floor(10.99)); // output 10.0
System.out.println("Ceil Value "+Math.ceil(10.1)); // output 11.0
System.out.println("Square Root "+Math.sqrt(25)); // output 5.0
System.out.println("Cube "+Math.pow(5,3)); // output 125.0
}
}
- Math.max(10, 20) prints maximum value between 10 and 20.
- Math.min(10, 20) prints minimum value between 10 and 20.
- Math.round(10.99) prints round value between 10.99.
- Math.floor(10.99) prints floor value between 10.99.
Bottom Value
- Math.ceil(10.1) prints ceil value between 10.99.
Top Value
- Math.sqrt(25) prints square root of 25.
- Math.pow(5,3) prints 5 to the power 3.
How To Generate Random Number In Java
You can use this formula to generate a random number between any numbers.
Math.random() * (max - min + 1) + min
Example
This program will generate a random number between 10 - 100.
public class Main {
public static void main(String[] args) {
double randomnumber = Math.random() * (100 - 10 + 1) + 10;
int num = (int) Math.ceil(randomnumber);
System.out.println("Random number is "+num);
}
}