Random

Math Class

Random

🙋 Need help? Ask an expert now!

The random() method in the Math class returns a random number between 0.0 and 1.0, including 0.0 and not including 1.0, at random with uniform distribution from this range. This method is written like Math.random() and does not take in any parameters. The returns a double value. Run the program below to see the function. As you may suspect, you will get different numbers every time you run the program.

RandomMethodExample.java
package exlcode;

public class RandomMethodExample {

  // Returns double value greater than or equal to 0.0 and less than 1.0
  public static double exampleVariableOne = Math.random();
  // Returns an integer value between 1 and 100
  public static int exampleVariableTwo = (int) (Math.random() * 101);

  public static void main(String[] args) {
    System.out.println(exampleVariableOne);
    System.out.println(exampleVariableTwo);
  }
}

In order to increase our range from 0.0 to 100.0, we have to multiply the whole expression by 101 since the function's range is only 0.0 to 1.0. We then use casting to change the double to an int datatype value, which in turn truncates the decimal and gives us a whole number. There are different methods within the Random class which may be useful to you for various projects in the future.

Edit Me on GitHub!

Application Question

Assume that the following variable declarations have been made.

double varOne = Math.random();
double varTwo;

Which of the following assigns a value to varTwo with the uniform distribution over the range 0.5 <= varTwo < 5.5?




...

You've Reached the End of this Course! 🎓🎉

Great work, are you ready to learn more?

View More Courses