Program 1 to generate random Integers in given specific range before java 7
Program 2 to generate random Integers in given specific range in java 7 using ThreadLocalRandom
import java.util.concurrent.ThreadLocalRandom;
/*
* Generate random Integers in given specific range in java
* In this program we will generate random numbers between 5 and 10
*/
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class GenerateRandomIntegers2 {
public static void main(String[] args) {
int min = 5;
int max = 10;
System.out.println("print 3 random numbers between "+ min+ " and "+max);
for (int i = 0; i < 3; i++)
System.out.println(ThreadLocalRandom.current().nextInt(min, max + 1));
}
}
/* Output
print 3 random numbers between 5 and 10
7
10
9
*/
|
Program 3 to generate random Integers between range before java 7
import java.util.Random;
/*
* Generate random numbers between 0 and 5
*/
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class GenerateRandomIntegers3 {
public static void main(String[] args) {
Random rand = new Random();
System.out.println("print 3 random numbers between 0 to 5");
for (int i = 0; i < 3; i++)
System.out.println(rand.nextInt(5 + 1));
}
}
/* Output
print 3 random numbers between 0 to 5
2
5
4
*/
|
Program 4 to generate random Integers in given specific range in java 8
import java.util.Random;
/*
* Generate random numbers between 0 and 5
*/
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class GenerateRandomIntegersInJava8_ {
public static void main(String[] args) {
int min = 5;
int max = 10;
System.out.println("print 3 random numbers between " + min + " and "
+ max+" in java 8");
Random rand = new Random();
for (int i = 0; i < 3; i++)
System.out.println(rand.ints(1, min, max + 1).findFirst().getAsInt());
}
}
/* Output
print 3 random numbers between 5 and 10 in java 8
8
5
9
*/
|
Program 5 to generate random Integers in given specific range in java 8
import java.util.Random;
/*
* Generate random numbers between 0 and 5
*/
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class GenerateRandomIntegersInJava8 {
public static void main(String[] args) {
int min = 5;
int max = 10;
System.out.println("print 3 random numbers between " + min + " and "+ max+
" in java 8");
Random rand = new Random();
//randomNumbersArray will store random numbers
int[] randomNumbersArray = rand.ints(3, min, max + 1).toArray();
//iterate on randomNumbersArray
for (int i : randomNumbersArray)
System.out.println(i);
}
}
/* Output
print 3 random numbers between 5 and 10 in java 8
6
5
7
*/
|
Often I have seen interviewers ask about writing your own logic to generate random Integers in given specific range. Interviewees tend to confuse but logic is damn simple you just need to find something which keeps on changing regularly, you may pick date or Runtime.getRuntime().freeMemory() etc.