How can I generate random number in specific range in Android?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
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:
- Using Java's
RandomClass - Java's
ThreadLocalRandomClass - The
Math.random()Method - Kotlin's
RandomClass (Introduced in Kotlin 1.3) - 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.
RandomInstance: Creates a random number generator.- **
nextInt(bound)**: Returns a pseudorandomintvalue between 0 (inclusive) and the specified value (exclusive). - Range Logic: Adjusted to
(max - min + 1) + minto ensure the generated number includesminandmaxvalues. - Performance: For a single-threaded context, Java's and Kotlin's
Randomclasses are suitable. In multithreading contexts, preferThreadLocalRandom. - Security: Use
SecureRandomwhen the quality of randomness is critical, such as in security protocols. - Kotlin & Java 8+: For new projects, especially those in Kotlin, prefer Kotlin's
RandomorThreadLocalRandomin Java 8+.
Related reading
- How can I get a List from some class properties with Java 8 Stream?
- How can I get a resource content from a static context?
- How can I get current date in Android?
- How can I get screen resolution in java?
- How can I get a view's current width and height when using autolayout constraints?
- How can I get color-int from color resource?
- How can I get session from a common class in Spring Boot?
- How can I get System variable value in Java?

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.