Math.random() : Returns a random double value between 0.0 and 1.0.
Random class : Provides more flexibility, allowing random integers, doubles, etc.
Syntax Example:
System.out.println(Math.random()); // Output: Random number between 0.0 and 1.0
Random rand = new Random();
System.out.println(rand.nextInt(100)); // Output: Random integer between 0 and 99
Program
Input:
// Java program demonstrating math functions and random number generation
import java.util.Random;
public class MathAndRandomExample {
public static void main(String[] args) {
// Math functions
System.out.println("Square root of 16: " + Math.sqrt(16));
System.out.println("2 raised to the power of 3: " + Math.pow(2, 3));
System.out.println("Max of 10 and 20: " + Math.max(10, 20));
System.out.println("Min of 10 and 20: " + Math.min(10, 20));
System.out.println("Absolute value of -5: " + Math.abs(-5));
// Random number generation
System.out.println("\nRandom number using Math.random(): " + Math.random());
Random rand = new Random();
System.out.println("Random integer between 0 and 99: " + rand.nextInt(100));
}
}