Android
Random Number Generation
Java
Programming
Code Duplication

How can I generate random number in specific range in Android?

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Generating random numbers is a common requirement in various Android applications, whether for gaming, simulations, or creating test data. In this article, we will explore different ways to generate random numbers within a specified range on an Android device, along with technical explanations and code examples.

Methods to Generate Random Numbers

There are several methods available in Java and Kotlin for generating random numbers:

  1. Using Java's Random Class
  2. Java's ThreadLocalRandom Class
  3. The Math.random() Method
  4. Kotlin's Random Class (Introduced in Kotlin 1.3)
  5. Secure Random Number Generation

1. Using Java's Random

Class

The java.util.Random class is a popular choice for generating random numbers. Below is how you can use this class to generate a number within a specific range.

  • Random Instance: Creates a random number generator.
  • **nextInt(bound) **: Returns a pseudorandom int value between 0 (inclusive) and the specified value (exclusive).
  • Range Logic: Adjusted to (max - min + 1) + min to ensure the generated number includes min and max values.
  • Performance: For a single-threaded context, Java's and Kotlin's Random classes are suitable. In multithreading contexts, prefer ThreadLocalRandom .
  • Security: Use SecureRandom when the quality of randomness is critical, such as in security protocols.
  • Kotlin & Java 8+: For new projects, especially those in Kotlin, prefer Kotlin's Random or ThreadLocalRandom in Java 8+.

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms