In this blog tutorials, we will see how to implement using java dice roll program.
Code Java Dice Roll Program
package com.slb.java;
import java.util.Random;
public class DiceRollSLB {
public static void main(String[] args) {
Random random = new Random();
int dice1 = random.nextInt(6) + 1;
int dice2 = random.nextInt(6) + 1;
System.out.println("Dice 1: " + dice1);
System.out.println("Dice 2: " + dice2);
}
}
OP: 1
Dice 1: 3
Dice 2: 5
OP: 2
Dice 1: 3
Dice 2: 6
OP: 3
Dice 1: 1
Dice 2:
Code Explanation
The above program calculates rolling of a specified number of dice with a specified number of sides on each die, and prints out the results of each roll. In above example we have rolled it 3 times that means we ran this above program 3 times.
What is dice roll ?

Rolling dices is a form of chance that involves rolling at least one die. Once rolled, the face value of the die will determine its outcome; and depending on how many sides there are on it, values ranging from 1 to 6 inclusive can be produced from that roll. Dice rolls are board games or gambling games in order to add an element of chance and uncertainty into gameplays.
Advanced Java Dice Roll Program
Code advance dice roll program
package com.slb.java;
import java.util.Random;
import java.util.Scanner;
public class AdvancedDiceRollSLB {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random random = new Random();
int numDice, numSides;
boolean isValid = false;
// get number of dice and sides and then operate on the inputs
while (!isValid) {
System.out.print("Enter number of dice: ");
numDice = input.nextInt();
System.out.print("Enter number of sides on each die: ");
numSides = input.nextInt();
// check if inputs are proper valid ones
if (numDice > 0 && numSides > 0) {
isValid = true;
int sum = 0;
// roll each die and print the result on console
for (int i = 1; i <= numDice; i++) {
int roll = random.nextInt(numSides) + 1;
System.out.println("Die " + i + ": " + roll);
sum += roll;
}
// print the sum of dice
System.out.println("Total: " + sum);
} else {
System.out.println("Invalid input. Please enter positive integers.");
}
}
}
}
Output:
Enter number of dice: 6
Enter number of sides on each die: 2
Die 1: 2
Die 2: 1
Die 3: 1
Die 4: 2
Die 5: 1
Die 6: 1
Total: 8
Process finished with exit code 0
Run #2
Enter number of dice: 2
Enter number of sides on each die: 2
Die 1: 1
Die 2: 1
Total: 2
Process finished with exit code 0
Code Explanation
This program called AdvancedDiceRoll AdvancedDiceRoll is an upgraded code version of a DiceRoll application which is there above at the start. This program lets you roll a certain number of dice, with an exact amount of faces on every die and then prints the outcomes from each roll, as well as the total of the rolls.
The program makes use of its random class to create random numbers for each die roll, and also the scanner class (used to scan data from the user) is used to obtain feedback from the person who is using it. Then, it asks the user to input numbers for the dice they want to roll as well as how many sides for the die. It it checks whether the input is valid (both inputs have to be integers that are positive).
When the inputs are valid, The program rolls the dies and outputs the result along with the total sum of all dies. In the event that inputs are incorrect, the program displays an error warning and asks the user to input valid data.
The program makes use of an endless loop to prompt the user to input data until input that is valid and ensures that this program can provide a an output that is valid.
Overall, Advanced Dice Roll program, a good program. AdvancedDiceRoll program is an sophisticated and flexible variation of DiceRoll code which allows users to choose the number of sides and dice of each die, and providing more detailed output.
More Tech Details:
Creating a simple dice roll program is a classic introductory exercise in Java. It demonstrates fundamental concepts like generating random numbers, user input, and basic control flow.
The Core Concept: Random Number Generation
The central component of any dice roll program in Java is the ability to generate a pseudo-random integer within a specified range (typically 1 to 6). Java offers two primary classes for this:
1. The Math.random() Method
This static method is part of the java.lang.Math class. It returns a double value between $0.0$ (inclusive) and $1.0$ (exclusive). To convert this into an integer roll for an N-sided die, you use a simple formula:
$$\text{Roll} = (\text{int})(\text{Math.random}() \times \text{Number of Sides}) + 1$$
2. The java.util.Random Class (Recommended)
This class offers more flexibility and better control over the random number generation process, including the ability to provide a specific seed. The nextInt(n) method returns a pseudo-random integer between $0$ (inclusive) and $n$ (exclusive).
To roll a standard 6-sided die, you call nextInt(6) (which gives 0 to 5) and add 1.
$$\text{Roll} = \text{random.nextInt}(\text{Number of Sides}) + 1$$
💻 Java Implementation: Rolling a Single Die
This example uses the preferred Random class to simulate a single roll of a standard 6-sided die.
Java
import java.util.Random;
import java.util.Scanner;
public class SingleDiceRoller {
public static void main(String[] args) {
// 1. Initialize the Random object once
Random random = new Random();
Scanner scanner = new Scanner(System.in);
final int SIDES = 6;
System.out.println("Welcome to the 6-Sided Dice Roller!");
System.out.println("Press Enter to roll the die...");
// Wait for user input (Enter key)
scanner.nextLine();
// 2. Generate the random number (0 to 5) and add 1 (1 to 6)
int rollResult = random.nextInt(SIDES) + 1;
System.out.println("--------------------------------");
System.out.println("| Your roll is: " + rollResult + " |");
System.out.println("--------------------------------");
scanner.close();
}
}
📈 Advanced Program: Rolling Multiple Dice
A more robust program allows the user to specify the number of dice and the number of sides, demonstrating better parameter handling and looping.
Java
import java.util.Random;
import java.util.Scanner;
public class MultiDiceRoller {
// Global Random instance for efficiency
private static final Random RANDOM = new Random();
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("--- Advanced Dice Roller ---");
// Get user input for number of dice
System.out.print("Enter number of dice to roll (e.g., 2): ");
int numDice = scanner.nextInt();
// Get user input for number of sides
System.out.print("Enter number of sides per die (e.g., 6 or 20): ");
int numSides = scanner.nextInt();
int totalSum = 0;
System.out.println("\nRolling " + numDice + " D" + numSides + " dice...");
// Loop to roll each die individually
for (int i = 1; i <= numDice; i++) {
// Generate roll: nextInt(N) returns 0 to N-1, so we add 1
int roll = RANDOM.nextInt(numSides) + 1;
totalSum += roll;
System.out.println("Die " + i + ": " + roll);
}
System.out.println("\n==================================");
System.out.println("Total Sum of " + numDice + " dice: " + totalSum);
System.out.println("==================================");
} catch (java.util.InputMismatchException e) {
System.err.println("Invalid input. Please enter only whole numbers.");
}
}
}
Java Dice Roll Program FAQs
1. What is the difference between Random and Math.random()?
| Feature | java.util.Random | Math.random() |
| Type | Class (requires object instantiation) | Static method |
| Return Type | nextInt(n) returns int | Returns double (0.0 to 1.0) |
| Control | Allows seeding (e.g., for reproducible results) | Always uses a fixed, system-dependent seed |
| Recommendation | Preferred for production code and multi-threaded environments. | Suitable for quick, single-use random numbers. |
2. Why do we always add + 1 to the result of random.nextInt(N)?
The method random.nextInt(N) returns a pseudo-random integer in the range $0$ (inclusive) up to $N$ (exclusive).
For a standard die with $N=6$ sides, the results are $0, 1, 2, 3, 4, 5$. Since a die roll must start at 1, adding 1 to the result shifts the range to $1, 2, 3, 4, 5, 6$.
3. What is “seeding” a random number generator and why would I use it?
Seeding is the process of setting the initial value used by the random number algorithm. If you initialize the Random object with the same seed value every time, the sequence of generated “random” numbers will be exactly the same.
- Syntax:
Random random = new Random(seedValue); - Use Case: Seeding is essential for testing (to reproduce bugs) and in simulations or competitive programming where the randomness must be predictable and verifiable.
4. How can I ensure the random numbers are thread-safe in a multi-threaded application?
While a single java.util.Random instance is generally safe for concurrent use, its performance can degrade under heavy contention. For high-performance multi-threaded applications, use java.util.concurrent.ThreadLocalRandom.current() instead.
ThreadLocalRandom provides a separate, optimized Random instance for each thread, avoiding resource contention and offering superior performance compared to a globally shared or synchronized Random object.
5. How would I simulate weighted dice (i.e., making 6 more likely to appear)?
You cannot simulate weighted probability directly using nextInt(). You must modify the range and mapping:
- Create a weighted range: Generate a random number across a larger range (e.g., 1 to 100).
- Map the results: Define segments of that range to correspond to the die faces. Give larger segments to the faces you want to be more probable.
| Range (1-100) | Die Face | Probability |
| 1 – 10 | 1 | 10% |
| 11 – 20 | 2 | 10% |
| 21 – 35 | 3 | 15% |
| 36 – 60 | 4 | 25% |
| 61 – 80 | 5 | 20% |
| 81 – 100 | 6 | 20% |
Conclusion
In this blog, we have seen that we can use this Dice Roll program to calculate the dice roll chances that can be used as base logic in creating java based board games.
Checkout Java Tutorials here

For over 15 years, I have worked as a hands-on Java Architect and Senior Engineer, specializing in building and scaling high-performance, enterprise-level applications. My career has been focused primarily within the FinTech, Telecommunications, or E-commerce sector, where I’ve led teams in designing systems that handle millions of transactions per day.
Checkout my profile here : AUTHOR https://simplifiedlearningblog.com/author/