Home page

Sunday, June 4, 2023

Generate Random Number in JAVA

import java.util.Random;

public class RandomNumberExample {

    public static void main(String[] args) {

        Random random = new Random();

        int randomNumber = random.nextInt(); // Generates a random integer

        System.out.println("Random number: " + randomNumber);

    }

}

In this example, the Random class from the java.util package is used to generate random numbers. The Random object is created using the new Random() constructor. To generate a random integer, the nextInt() method is called on the Random object. The generated random number is then assigned to the randomNumber variable. Finally, the random number is printed to the console using System.out.println().

No comments:

Post a Comment