- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to randomize and shuffle array of numbers in Java?
At first, create an integer array −
int[] arr = { 20, 40, 60, 80,100, 120, 140, 160, 180, 200};
Now, create a Random class object −
Random rand = new Random();
Loop until the length of the array and shuffle the elements −
for (int i = 0; i < arr.length; ++i) { int index = rand.nextInt(arr.length - i); int tmp = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = arr[index]; arr[index] = tmp; }
Example
import java.util.Arrays; import java.util.Random; public class Demo { public static void main(String[] args) { int[] arr = { 20, 40, 60, 80,100, 120, 140, 160, 180, 200}; System.out.println("The integer array = "+Arrays.toString(arr)); Random rand = new Random(); for(int i = 0; i < arr.length; ++i) { int index = rand.nextInt(arr.length - i); int tmp = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = arr[index]; arr[index] = tmp; } System.out.println("Shuffle integer array = "+Arrays.toString(arr)); } }
Output
The integer array = [20, 40, 60, 80, 100, 120, 140, 160, 180, 200] Shuffle integer array = [160, 100, 20, 60, 140, 200, 120, 40, 80, 180]
- Related Articles
- How to randomize (shuffle) a JavaScript array?
- Shuffle or Randomize a list in Java
- How to shuffle an array in Java?
- how to shuffle a 2D array in java correctly?
- Java Program to shuffle an array using list
- How to shuffle a List in Java
- Shuffle Array Contents
- Shuffle an Array in Python
- How to shuffle an array in a random manner in JavaScript?
- Golang program to shuffle the elements of an array
- How to randomize rows of a matrix in R?
- How to Remove Even Numbers from Array in Java?
- How to Remove Odd Numbers from Array in Java?
- How to find the Odd and Even numbers in an Array in java?
- Java Program to Shuffle the Elements of a Collection

Advertisements