OnextDigital logo 1
Success Stories
About Us
Pricing
Contact Us
Contact Us
footer logo

ONEXT DIGITAL helps your business grow through the utilization of technology and an innovative mindset. We have a history of going over and above because we not only complete projects on time – we find ways to support our customers to achieve their specific goals.

Services

  • Ecommerce Web Development
  • AI Development Services
  • Web App Development
  • Mobile App Development

About Us

  • About Us
  • Our Pricing
  • Insights
  • Success Stories

Contact

  • Chat With Us
  • info@onextdigital.com
  • linkedin
    google
    x twitter brands solid full

Copyright © 2026. ONEXT DIGITAL - By AHT TECH

blog detail placeholder

Looking for an Outsourcing Partner

Achieve 50- 70% cost savings on web/app development projects by hiring a skilled workforce at competitive projects s

Get a quote
Back
  • Random number
  • Java Random Number Generation
  • To sum up
  • FAQs

Need a Website or Mobile App From Experts?

We are ready to work and build on-demand solution for your business.

Back
  • Random number
  • Java Random Number Generation
  • To sum up
  • FAQs

Java random number: methods to generate it

By Editorial Team/December 23, 2022

In Java programming, you often encounter the requirement to generate random numbers while developing the application. The random() method, which produces random integers, appears to be the most practical approach to creating unexpected in Java. Many apps have a random number generator feature, such as for user verification, and many use OTP codes. The dice are the greatest illustration of a random number. because a number between 1 and 6 will be chosen randomly when we throw it. In this part, we will learn what is a random number and how to generate random numbers in Java.

java random number
java random number

Random number

A random number is a number that uses a large set of numbers and selects a number using a mathematical algorithm. It meets the following two criteria:

  • Over a predetermined time period, the produced values have a uniform distribution.
  • Future values cannot be predicted based on previous or present values.

Java Random Number Generation

There are three methods in Java for producing random numbers utilizing methods and classes.

  • Making use of the random() Method
  • Using the Random Class
  • Making use of the ThreadLocalRandom Class

Making use of the random() Method

The Java Math class has many methods for different math operations. The random() function is one of them. It belongs to the Math class’ static method. It just generates a random number of double types greater than or equal to 0.0 and less than 1.0. We need to import the java.lang.Math class before we can use the random() function.

Syntax:

public static double random()

It does not accept any parameter. It returns a pseudorandom double that is greater than or equal to 0.0 and less than 1.0.

Let’s write a program that uses the random() function to produce random integers.

RandomNumberExample1.java

import java.lang.Math; public class RandomNumberExample1 { public static void main(String args[]) { // Generating random numbers System.out.println("1st Random Number: " + Math.random()); System.out.println("2nd Random Number: " + Math.random()); System.out.println("3rd Random Number: " + Math.random()); System.out.println("4th Random Number: " + Math.random()); } }

Output:

1st Random Number: 0.17434160924512265 2nd Random Number: 0.4297410090709448 3rd Random Number: 0.4828656381344487 4th Random Number: 0.13267917059488898

Keep in mind: Every time we run the program, we obtain a different result. Your results might be different from those seen above.

If want to generate random numbers within a certain range, we can also use the below formula.

Math.random() * (max - min + 1) + min

In the above formula, the min value is inclusive while the max value is exclusive.

Let’s program a generator to produce random numbers between 200 and 400.

RandomNumberExample2.java

public class RandomNumberExample2 { public static void main( String args[] ) { int min = 200; int max = 400; //Generate random double value from 200 to 400 System.out.println("Random value of type double between "+min+" to "+max+ ":"); double a = Math.random()*(max-min+1)+min; System.out.println(a); //Generate random int value from 200 to 400 System.out.println("Random value of type int between "+min+" to "+max+ ":"); int b = (int)(Math.random()*(max-min+1)+min); System.out.println(b); } }

Output 1:

Random value of type double between 200 to 400: 233.88329802655377 Random value of type int between 200 to 400: 329

Output 2:

Random value of type double between 200 to 400: 254.8419979875385 Random value of type int between 200 to 400: 284

Using the Random Class

The java.util.Random.ints() method can return an infinite integer stream of randomly generated numbers. All the random numbers will be created inside the range that we choose. We can also specify the stream size so that we get only a limited number of integers.

The following code never ends because we did not provide the ints() function a stream size argument. Only a handful of the output numbers have been displayed.

import java.util.Random; import java.util.stream.IntStream; public class RandomRangeDemo { public static void main(String[] args) { Random r = new Random(); IntStream stream = r.ints(10, 20); stream.forEach(s -> System.out.println(s)); } }

Output:

11 16 16 14 12 13

Generate only 5 random integers by setting the stream size.

import java.util.Random; import java.util.stream.IntStream; public class RandomRangeDemo { public static void main(String[] args) { Random r = new Random(); IntStream stream = r.ints(5, 100, 120); stream.forEach(s -> System.out.println(s)); } }

Output:

103 106 114 117 109

We can use the findFirst() and getAsInt() methods to get only the first random number from the stream.

import java.util.Random; import java.util.stream.IntStream; public class RandomRangeDemo { public static void main(String[] args) { int min = 150, max = 2000;//defining the range Random r = new Random(); IntStream stream = r.ints(1, min, max); int randomNum = stream.findFirst().getAsInt(); System.out.print("The random number is: " + randomNum); } }

Output:

The random number is: 1193

Making use of the ThreadLocalRandom Class

The ThreadLocalRandom class is defined in java.util.concurrent package. It is initialized with an internally generated seed, the same as the random generator of the Math class. It can’t be changed. This class can be applied in the following ways:

ThreadLocalRandom.current().nextX(...)

Where X is Int, Long, etc.

Note: It is impossible to share a ThreadLocalRandom with multiple threads accidentally.

We can generate a random number of any data type, such as integer, float, double, Boolean, long. Follow the instructions below if you plan to use this class to create random numbers:

  • First, import the class by using java.util.concurrent.ThreadLocalRandom.
  • Call the matching method that you wish to use to create random numbers.
  • nextInt()
  • nextDouble()
  • nextLong()
  • nextFloat()
  • nextBoolean()

All the above methods override the corresponding method of the Random class and return the corresponding value.

  • nextInt(int bound)
  • nextDouble(int bound)
  • nextLong(int bound)

The above methods parse a parameter bound (upper) that must be positive. It returns a matching randomly generated value between 0 (inclusive) and the specified bound (exclusive). If the bound is negative, IllegalArgumentExcetion will be thrown.

  • nextInt(int origin, int bound)
  • nextDouble(int origin, int bound)
  • nextLong(int origin, int bound)

The above methods parse two parameters origin and bound. The origin specifies the least value returned and the bound specifies the upper bound. It gives back a value created randomly between the bound (exclusive) and the specified origin (inclusive). Additionally, if the origin is greater than or equal to the bound, IllegalArgumentExcetion will be thrown.

Let’s write a program that uses the ThreadLocalRandom class to generate random integers.

RandomNumberExample.java

import java.util.concurrent.ThreadLocalRandom; public class RandomNumberExample4 { public static void main(String args[]) { // Generate random integers between 0 to 999 int a = ThreadLocalRandom.current().nextInt(); int b = ThreadLocalRandom.current().nextInt(); // Print random integer values System.out.println("Randomly Generated Integer Values:"); System.out.println(a); System.out.println(b); // Generate Random double values double c = ThreadLocalRandom.current().nextDouble(); double d = ThreadLocalRandom.current().nextDouble(); // Print random doubles System.out.println("Randomly Generated Double Values:"); System.out.println(c); System.out.println(d); // Generate random boolean values boolean e = ThreadLocalRandom.current().nextBoolean(); boolean f = ThreadLocalRandom.current().nextBoolean(); // Print random Booleans System.out.println("Randomly Generated Boolean Values:"); System.out.println(e); System.out.println(f); } }

Output 1:

Randomly Generated Integer Values: 348534891 -1887936727 Randomly Generated Double Values: 0.15644440033119833 0.5242730752133399 Randomly Generated Boolean Values: true true

Output 2:

Output 2: Randomly Generated Integer Values: 402755574 295398333 Randomly Generated Double Values: 0.4856461791062565 0.5148677091077654 Randomly Generated Boolean Values: false true

To sum up

In this tutorial, we have implemented our methods using the inbuilt Random() method of the Math class and the nextInt() of the Random class. You can learn different ways to generate a random number within a specified range. Alternatively, you can also directly use the ints() method to generate a stream of random numbers within a given range.

If you have problems with this experience or would like to learn more, please contact ONEXT DIGITAL, and we will assist you. Also, if you are looking for economic growth for your eCommerce business, check out Onext digital. We also offer cost-effective Shopify Development, Mass Commerce Development, and Magento Development services alongside a team of knowledgeable professionals and developers who collaborate directly with designers.

>>Read more

Sorting Algorithms Java: Everything You Need To Know

FAQs

Yes. An offshore ClickFunnels agency can work effectively with Australian businesses when it has clear communication processes, suitable working hour overlap, reliable project management and relevant technical experience. The agency's location is less important than its ability to communicate clearly, meet deadlines and take responsibility for the work.

A ClickFunnels expert is usually suitable for straightforward work such as building a landing page, fixing an existing funnel or making specific changes. An agency is generally a better fit when the project involves funnel strategy, multiple systems, complex integrations, ongoing optimisation or a funnel that plays an important role in generating revenue.

Not necessarily. If the problem is conversion, landing pages or marketing automation, improve those areas first. Consider migration only when your business model has changed enough that your current ecommerce architecture no longer fits.

Yes, especially for a small product range where sales depend on paid traffic, offers, upsells or other funnel tactics. As catalog and operational complexity grow, Shopify usually becomes a better fit.

Need a Website or Mobile App From Experts?

We are ready to work and build on-demand solution for your business.