Google News
logo
Generate Random Number in Java Program
In Java, we can generate random numbers using the java.util.Random class. Here's an example program that generates a random integer between 1 and 100 :
Program :
import java.util.Random;

public class RandomNumberGenerator {
    public static void main(String[] args) {
        Random random = new Random();
        int randomNumber = random.nextInt(100) + 1;
        System.out.println("Random number between 1 and 100: " + randomNumber);
    }
}
Output :
Random number between 1 and 100: 81
In this program, we first create a Random object using the java.util.Random class. We then use the nextInt() method to generate a random integer between 0 (inclusive) and 100 (exclusive). We add 1 to the result to generate a random integer between 1 and 100.

Finally, we print the random number to the console using System.out.println().