askvity

How to get a random number between 1 and 100 in Java?

Published in Java Random Numbers 2 mins read

To get a random number between 1 and 100 in Java, you can use the java.util.Random class.

Generating a Random Number Between 1 and 100

Here's a breakdown of how to do it, including code and explanation based on the provided reference:

import java.util.Random;

public class Main {
  public static void main(String[] args) {
    // Create an instance of the Random class.
    Random randomNum = new Random();

    // Generate a random number between 0 (inclusive) and 100 (exclusive), and then add 1.
    int showMe = randomNum.nextInt(100) + 1;

    // Print the random number.
    System.out.println("Random number between 1 and 100: " + showMe);
  }
}

Explanation:

  1. Import the Random class: The code starts by importing the java.util.Random class, which is necessary for generating random numbers.
  2. Create a Random object: An instance of the Random class is created using Random randomNum = new Random();. This object will be used to generate random numbers.
  3. Generate a random number: The nextInt(100) method generates a random integer between 0 (inclusive) and 100 (exclusive). To get a number between 1 and 100 (inclusive), we add 1 to the result: randomNum.nextInt(100) + 1.
  4. Print the result: The generated random number is then printed to the console using System.out.println().

Example

The code above will output a random number between 1 and 100 each time it is run. For example:

Random number between 1 and 100: 42
Random number between 1 and 100: 87

And so on.

Related Articles