The Math.random()
Java method generates a pseudorandom number between 0.0 and 1.0. The resulting random number can be multiplied to get a range outside 0-1, and the result can be 0 but is always less than 1.
When you’re programming, there are often situations where you need to generate a random number. For instance, say that you are operating a cruise line. You may want to generate a random number that is added to the end of a customer’s order and used as their booking reference. Or you may want to generate a random number for a guessing game.
In Java, there are a number of methods that can be used to generate a random number.
In this tutorial, we are going to walk through the most common method used to generate a random number in Java: Math.random().
We’ll also discuss a step-by-step example of how to use the Math.random()
method.
Java Math Library
The Java Math class includes a number of features used to perform mathematical functions on numbers. For instance, the Math library includes the round()
method that is used to round a number and the pow()
method that is used to calculate the power of a number.
In order to use the Java Math library, we must first import it into our code. We can do so using an import statement like this:
import java.lang.Math;
For this tutorial, we are going to use one method from the Math library: Math.random().
Math.random Java Method
The Java Math.random()
method is used to generate a pseudorandom number, which is a number created with a formula that simulates randomness. The pseudorandom number will be greater than or equal to 0.0 and less than 1.0. In other words, the number generated by Math.random
is always between 0 and 1, and is a floating-point number.
The random method returns a random double, which is the data type used to store floating-point values.
Math.Random() Example
Here’s an example of the Math.random()
method in action:
import java.lang.Math; class Main { public static void main(String[] args) { double number = Math.random(); System.out.println("Random number: " + number); } }
Our code returns:
Random number: 0.4728164736886452
As you can see, our program has returned a random number between 0 and 1. However, this number is not very useful in its current form. If we want to generate a random number for a guessing game, for instance, we would not want to have a decimal number.
In order to produce a whole number with our pseudorandom number generator, we can multiply our random number by another number and round it to the nearest whole number. For instance, suppose we wanted to generate a random number between 1 and 10. We could do so using this code:
class Main { public static void main(String[] args) { int number = (int)(Math.random() * 10); System.out.println("Random number: " + number); } }
Here is the result of our program after running it three times:
4
6
2
As you can see, our program returns a random integer, or whole number.
Let’s break down our code. First, we declared a class called Main which stores the code for our program.
Then we used the Math.random()
method to generate a random number, and we multiplied that number by 10. After we multiplied the result by 10, we converted it to an integer, which rounds it to the nearest decimal place and gives us a whole number.
Then, on the final line, we print out the message “Random number: “ to the console, followed by the random number our program generated.
If we wanted to generate a larger number, we could replace the * 10 parts of our code with another number. For instance, say we wanted to generate a number between 1 and 1000. We could do so by replacing * 10 with * 1000 like this:
class Main { public static void main(String[] args) { int number = (int)(Math.random() * 1000); System.out.println("Random number: " + number); } }
After executing our program three times, the following response was returned:
181
914
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
939
Java Math.random Between Two Numbers
The Math.random()
method does not accept any arguments, which means that there is no way to influence the number generated by the method. However, we can create our own method which allows us to generate numbers between a particular range.
For instance, suppose we are building an app that generates the random numbers which will be used to distinguish a customer’s order at a cruise line. These numbers will be added onto the end of a customer’s name.
The number we want to generate should be between 200 and 500. In order to generate this number and prepare the customer’s order reference, we could use this code:
class Main { public static int generateTicketNumber(int min, int max) { int range = (max - min) + 1; return (int)(Math.random() * range) + min; } public static void main(String args[]) { String customerName = "JohnMcIver"; int randomNumber = generateTicketNumber(200, 500); System.out.println(customerName + randomNumber); } }
Our code returns:
JohnMcIver321
In our program, we generate a random number between the range of 200 and 500. Then we append that number to the customer’s name and print out the result to the console.
Let’s break down how our code works:
- We declare a method called
generateTicketNumber()
which accepts two parameters: min and max. generateTicketNumber()
uses the min and max parameters to generate a random number within the range of those two numbers withMath.random().
- When the main program runs, a variable called
customerName
is declared and is assigned the valueJohn McIver
. - Then the
generateTicketNumber()
method is called and the parameters 200 and 500 are specified, which correspond to the min and max values in the range our result should fall in, respectively. The result of this method is assigned to the variablerandomNumber
. - The customer’s name and the random number generated are concatenated—or merged together—and printed to the console.
Conclusion
The Java Math.random()
method is used to generate pseudo-random numbers. Math.random()
generates a number between 0 and 1, which can then be manipulated to be within a certain range.
This tutorial discussed the basics of the Math library in Java and how you can use the Math.random()
method to generate random numbers. Additionally, this tutorial explored how to generate a random number between a range of two numbers using Math.random()
and a custom method.
You’re now ready to start generating random numbers in Java like a pro!
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.