Home | Computer Science

Math & Random


Definition

Java provides several mathematical functions and ways to generate random numbers, often used in various calculations and simulations.


Math Functions in Java

Common math functions:
Syntax Example:

Random Numbers in Java

Generating random numbers: Syntax Example:

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)); } }

OUTPUT