Java.util.Random.nextInt() in Java
Last Updated :
21 Mar, 2025
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());
}
}
OutputRandom 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);
}
}
OutputRandom 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!!");
}
}
}
OutputPlayer 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:
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.
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
TCP/IP Model The TCP/IP model is a framework that is used to model the communication in a network. It is mainly a collection of network protocols and organization of these protocols in different layers for modeling the network.It has four layers, Application, Transport, Network/Internet and Network Access.While
7 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Basics of Computer Networking A computer network is a collection of interconnected devices that share resources and information. These devices can include computers, servers, printers, and other hardware. Networks allow for the efficient exchange of data, enabling various applications such as email, file sharing, and internet br
14 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read