Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Random next() method in Java with Examples
Next article icon

Java.util.Random.nextInt() in Java

Last Updated : 21 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Generating random numbers themselves has a good utility. Java provides a method Random.nextInt() which is the part of Random Class present in the util package. The nextInt() method is used to get the random integer values in the range of int.

Syntax

int nextInt()

int nextInt(int bound)

int nextInt(int origin, int bound)

Parameters:

  • bound(Optional): It takes an integer number of type int and returns a random value between 0 (inclusive) and bound (exclusive) value.
  • origin(Optional): Origin is the starting parameter and returns random numbers from origin (inclusive) and bound (exclusive).

Return Type:

  • This method returns random integer values.

Exception:

  • IllegalArgumentException: Throw this exception when the argument passed is not positive or the origin is greater than or equal to bound.

Example 1: Generating random numbers without any bound using the nextInt() method of Random Class.

Java
// Java Program to generate random numbers // using nextInt() method of Random class  import java.util.Random;  public class Geeks  {     public static void main(String[] args)      {         // create an object of Random class         Random r = new Random();          // Generate random integers without any bounds         System.out.println("Random number: " + r.nextInt());     } } 

Output
Random number: 599611746 

Explanation: This method gives random numbers which could be either negative or positive integers from range Integer.MIN_VALUE to Integer.MAX_VALUE, whenever we run the program we get a different output.

Example 2: Generating random numbers using int nextInt(int bound).

Java
// Java code to demonstrate the usage of Random.nextInt(int bound)  import java.util.*;  public class Geeks {      public static void main(String[] args) {          // create random object          Random r = new Random();          // generating number between 0 (inclusive) and 10 (exclusive)         int nxt = r.nextInt(10);          System.out.println("Generated Random number is : " + nxt);     } } 

Output
Random number between 0 and 10 is : 4 

Explanation: In the above code example we use the Random.nextInt(int bound) method and pass an int value 10 as an argument as bound and it returns a value from 0 to 10

Example 3: Creating a dice game logic using the nextInt() method to show real-life uses of random numbers.

Java
import java.util.Random;  public class Geeks {      public static void main(String[] args) {          // Player Score variables         int p1 = 0, p2 = 0;          // Game variable to count the number of turns         int turns = 0;          // Score to win the game         int Win = 5;         Random random = new Random();          // Game loop, players alternate turns         while (p1 < Win && p2 < Win) {             turns++;              // Player 1's turn (even turns)             if (turns % 2 == 1) {                  // Dice roll between 1 and 6                 int p1Roll = random.nextInt(6) + 1;                 p1 += p1Roll;                 System.out.printf("Player 1 after turn %d: Roll = %d, Total Score = %d\n", turns, p1Roll, p1);             } // Player 2's turn (odd turns)             else {                  // Dice roll between 1 and 6                 int p2Roll = random.nextInt(6) + 1;                 p2 += p2Roll;                 System.out.printf("Player 2 after turn %d: Roll = %d, Total Score = %d\n", turns, p2Roll, p2);             }         }          // Calculating the winner of the game         if (p1 >= Win) {             System.out.println("\nPlayer 1 WON!!");         } else {             System.out.println("\nPlayer 2 WON!!");         }     } } 

Output
Player 1 after turn 1: Roll = 1, Total Score = 1 Player 2 after turn 2: Roll = 4, Total Score = 4 Player 1 after turn 3: Roll = 6, Total Score = 7  Player 1 WON!! 

Explanation: In the above example we use the Random.nextInt() method to create a real-world example of random numbers in this example we set a winning score and the two players can roll a die one by one if any of the player’s total count is equal or greater than the max than that player wins the game.

Example 4: illustrate the Exception generated in Random.nextInt(int bound) when bound is not a positive number

Java
// Java code to demonstrate the Exception  // in Random.nextInt(int bound )   import java.util.*;  public class Geeks  {     public static void main(String[] args)      {         // create random object          Random r = new Random();          // generating number between 0 and -12345          // Raises Runtime error, as bound is negative.          int nxt = r.nextInt(-12345);          System.out.println("Generated Random number is : " + nxt);     } } 

Output:

Exception

Explanation: In this program, we try to generate the random numbers but we pass a negative bound which will throw the exception as shown in the image output.

Important Points

  • Range: This method returns an integer value in the range of in which is from -2^31 to 2^31 – 1.
  • ThreadLocalRandom: For multithreaded environments, it’s better to use the ThreadLocalRandom class which is thread-safe.
  • java.security.SecureRandom: Although this method gives the random integer values for better security we can use the alternative SecureRandom which returns the cryptographically secure random numbers.




Next Article
Random next() method in Java with Examples

S

Suman Singh Rajput
Improve
Article Tags :
  • Java
  • Java - util package
Practice Tags :
  • Java

Similar Reads

  • Java.util.Random class in Java
    Random class is used to generate pseudo-random numbers in java. An instance of this class is thread-safe. The instance of this class is however cryptographically insecure. This class provides various method calls to generate different random data types such as float, double, int. Constructors: Rando
    4 min read
  • StrictMath random() Method in Java
    The random() is an inbuilt method of StrictMath class in java which is used to get a double value with a positive sign that is greater than or equal to 0.0 and less than 1.0. random() method is accurately organized to acquiesce appropriate use by more than one thread. The values which are returned a
    2 min read
  • Random next() method in Java with Examples
    The next() method of Random class returns the next pseudorandom value from the random number generator's sequence. Syntax: protected int next(int bits) Parameters: The function accepts a single parameter bits which are the random bits. Return Value: This method returns the next pseudorandom number.
    1 min read
  • Random nextLong() method in Java with Examples
    The nextGaussian() method of Random class returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence. Syntax: public long nextLong() Parameters: The function does not accepts any parameter. Return Value: This method returns the next pseudorandom, uni
    1 min read
  • Random nextFloat() method in Java with Examples
    The nextFloat() method of Random class returns the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from the random number generator's sequence. Syntax: public float nextFloat() Parameters: The function does not accepts any parameter. Return Value: This method returns the nex
    1 min read
  • Random nextBytes() method in Java with Examples
    The nextBytes() method of Random class places the generated random bytes into an user-supplied byte array. Syntax: public void nextBytes(byte[] bytes) Parameters: The function accepts a single parameter bytes which is the non-null byte array in which to put the random bytes. Return Value: This metho
    2 min read
  • Random nextGaussian() method in Java with Examples
    The nextGaussian() method of Random class returns the next pseudorandom, Gaussian(normally) distributed double value with mean 0.0 and standard deviation 1.0 from the random number generator's sequence. Syntax: public double nextGaussian() Parameters: The function does not accepts any parameter. Ret
    1 min read
  • Random nextBoolean() method in Java with Examples
    The nextBoolean() method of Random class returns the next pseudorandom, uniformly distributed boolean value from the random number generator's sequence. Syntax: public boolean nextBoolean() Parameters: The function does not accepts any parameter. Return Value: This method returns the next pseudorand
    1 min read
  • Random nextDouble() method in Java with Examples
    The nextDouble() method of Random class returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence. Syntax: public double nextDouble() Parameters: The function does not accepts any parameter. Return Value: This method returns th
    1 min read
  • Random vs Secure Random numbers in Java
    Prerequisite: Generating Random numbers in Javajava.security.SecureRandom class: This class provides a cryptographically strong random number generator (RNG). A cryptographically strong random number minimally complies with the statistical random number generator tests specified in FIPS 140-2, Secur
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences