Java random

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
clz32()
cos()
cosh()
E
exp()
expm1()
floor()
fround()
LN2
LN10
log()
log10()
log1p()
log2()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sign()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

Using ThreadLocalRandom class

You can use ThreadLocalRandom class to generate random numbers.This class got introduced in Java 7.Although java.util.Random is thread safe but multiple threads tries to access same object, there will be lot of contention and performance issue.In case of ThreadLocalRandom, each thread will generate their own random numbers and there won’t be any contention.
Let’s understand with the help of example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

packageorg.arpit.java2blog;

import java.util.concurrent.ThreadLocalRandom;

publicclassThreadLocalRandomMain{

publicstaticvoidmain(Stringargs){

System.out.println(«============================»);

System.out.println(«Generating 5 random integers»);

System.out.println(«============================»);

for(inti=;i<5;i++){

System.out.println(ThreadLocalRandom.current().nextInt());

}

System.out.println(«============================»);

System.out.println(«Generating 5 random doubles»);

System.out.println(«============================»);

for(inti=;i<5;i++){

System.out.println(ThreadLocalRandom.current().nextDouble());

}

System.out.println(«============================»);

System.out.println(«Generating 5 random floats»);

System.out.println(«============================»);

for(inti=;i<5;i++){

System.out.println(ThreadLocalRandom.current().nextFloat());

}

System.out.println(«============================»);

System.out.println(«Generating 5 random booleans»);

System.out.println(«============================»);

for(inti=;i<5;i++){

System.out.println(ThreadLocalRandom.current().nextBoolean());

}

}

}
 

Output:

============================
Generating 5 random integers
============================
-315342453
-1922639586
-19084346
-615337866
-1075097641
============================
Generating 5 random doubles
============================
0.9074981945011997
0.7626761438609163
0.4439078754038527
0.8663565773294881
0.8133933685024771
============================
Generating 5 random floats
============================
0.50696343
0.4109127
0.4284398
0.37340754
0.28446126
============================
Generating 5 random booleans
============================
false
true
false
false
true

What is Randomness in Javascript?

It is impossible in computing to generate completely random numbers. This is because every calculation inside a computer has a logical basis of cause and effect, while random events don’t follow that logic.

Computers are not capable of creating something truly random. True randomness is only possible through a source of external data that a computer cannot generate, such as the movement of many lava lamps at once (which has been used as an unbreakable random encryption in the real world), meteographic noise, or nuclear decay.

The solution that Javascript, and other programming languages, use to implement randomness is “pseudo-random” number generation. Javascript random numbers start from a hidden internal value called a “seed.” The seed is a starting point for a hidden sequence of numbers that are uniformly distributed throughout their possible range.

Developers cannot change Javascript’s pseudo-random seed or the distribution of values in its generated pseudo-random sequences. Different Javascript implementations and different browsers often start with different seeds. Do not assume that different browsers, or even different computers, will always use the same seed.

Javascript random numbers are not safe for use in cryptography because deciphering the seed could lead to decryption of the hidden number sequence. Some functions exist to create cryptographically secure pseudo-random numbers in Javascript, but they are not supported by older browsers.

In this blog post, we’ll first cover the canonical methods of creating Javascript random numbers. Then we’ll move onto ways of obtaining higher-quality random data; your needs will determine the worthwhile effort.

Using random.nextInt() to generate random number between 1 and 10

We can simply use Random class’s nextInt() method to achieve this.

As the documentation says, this method call returns «a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)», so this means if you call nextInt(10), it will generate random numbers from 0 to 9 and that’s the reason you need to add 1 to it.
Here is generic formula to generate random number in the range.

randomGenerator.nextInt((maximum – minimum) + 1) + minimum
In our case,
minimum = 1
maximum = 10so it will berandomGenerator.nextInt((10 – 1) + 1) + 1randomGenerator.nextInt(10) + 1

So here is the program to generate random number between 1 and 10 in java.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

packageorg.arpit.java2blog;

import java.util.Random;

publicclassGenerateRandomInRangeMain{

publicstaticvoidmain(Stringargs){

System.out.println(«============================»);

System.out.println(«Generating 10 random integer in range of 1 to 10 using Random»);

System.out.println(«============================»);

Random randomGenerator=newRandom();

for(inti=;i<10;i++){

System.out.println(randomGenerator.nextInt(10)+1);

}

}

}
 

When you run above program, you will get below output:

==============================
Generating 10 random integer in range of 1 to 10 using Random
==============================
1
9
5
10
2
3
2
5
8
1

Read also:Java random number between 0 and 1Random number generator in java

Using Apache Common lang

You can use Apache Common lang to generate random String. It is quite easy to generate random String as you can use straight forward APIs to create random String.

Create AlphaNumericString

You can use RandomStringUtils.randomAlphanumeric method to generate alphanumeric random strn=ing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14

packageorg.arpit.java2blog;

import org.apache.commons.lang3.RandomStringUtils;

publicclassApacheRandomStringMain{

publicstaticvoidmain(Stringargs){

System.out.println(«Generating String of length 10: «+RandomStringUtils.randomAlphanumeric(10));

System.out.println(«Generating String of length 10: «+RandomStringUtils.randomAlphanumeric(10));

System.out.println(«Generating String of length 10: «+RandomStringUtils.randomAlphanumeric(10));

}

}
 

Output:

Generating String of length 10: Wvxj2x385N
Generating String of length 10: urUnMHgAq9
Generating String of length 10: 8TddXvnDOV

Create random Alphabetic String

You can use RandomStringUtils.randomAlphabetic method to generate alphanumeric random strn=ing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14

packageorg.arpit.java2blog;

import org.apache.commons.lang3.RandomStringUtils;

publicclassApacheRandomStringMain{

publicstaticvoidmain(Stringargs){

System.out.println(«Generating String of length 10: «+RandomStringUtils.randomAlphabetic(10));

System.out.println(«Generating String of length 10: «+RandomStringUtils.randomAlphabetic(10));

System.out.println(«Generating String of length 10: «+RandomStringUtils.randomAlphabetic(10));

}

}
 

Output:

Generating String of length 10: zebRkGDuNd
Generating String of length 10: RWQlXuGbTk
Generating String of length 10: mmXRopdapr

That’s all about generating Random String in java.

How to generate random numbers in Java?

We can use the  static method of the Math class to generate random numbers in Java.

1 publicstaticdoublerandom()

This method returns a double number that is greater than or equal to 0.0 and less than 1.0 (Please note that the 0.0 is inclusive while 1.0 is exclusive so that 0 <= n < 1)

a) How to generate a random number between 0 and 1?

1
2
3
4
5
6
7
8
9
10
11
12
13

packagecom.javacodeexamples.mathexamples;

publicclassGenerateRandomNumberExample{

publicstaticvoidmain(Stringargs){

System.out.println(«Random numbers between 0 and 1»);

for(inti=;i<10;i++){

System.out.println(Math.random());

}

}

}

Output (could be different for you as these are random numbers)

1
2
3
4
5
6
7
8
9
10
11
Random numbers between 0 and 1
0.12921328590853476
0.7936354242494305
0.08878870565069197
0.12470497778455492
0.1738593303254422
0.6793228890529989
0.5948655601179271
0.9910316469070309
0.1867838198026388
0.6630122474512686

b) Between 0 and 100

It is a fairly easy task to generate random numbers between 0 and 100. Since the  method returns a number between 0.0 and 1.0, multiplying it with 100 and casting the result to an integer will give us a random number between 0 and 100 (where 0 is inclusive while 100 is exclusive).

1
2

intrandomNumber=(int)(Math.random()*100);

System.out.println(«Random Number: «+randomNumber);

c) Between a specific range

Since the  method returns a double value between 0.0 and 1.0, we need to derive a formula so that we can generate numbers in the specific range.

Let’s do that step by step. Suppose you want to generate random numbers between 10 and 20. So the minimum number it should generate is 10 and the maximum number should be 20.

Step 1:

First of all, we need to multiply the  method result with the maximum number so that it returns value between 0 to max value (in this case 20) like given below.

1 intrandomNumber=(int)(Math.random()*20);

The above statement will return us a random number between 0.0 and 19. That is because multiplying 0.0 – 0.99 with 20 and casting the result back to int will give us the range of 0 to 19.

Step 2:

Step 1 gives us a random number between 0 and 19. But we want a random number starting from 10, not 0. Let’s add that number to the result.

1 intrandomNumber=10+(int)(Math.random()*20);

Step 3:

Now the number starts from 10 but it goes up to 30. That is because adding 10 to 0-19 will give us 10-29. So let’s subtract 10 from 20 before the multiplication operation.

1 intrandomNumber=10+(int)(Math.random()*(20-10));

Step 4:

The random number generated by the above formula gives us a range between 10 and 19 (both inclusive). The number range we wanted was between 10 and 20 (both inclusive). So let’s add 1 to the equation.

1 intrandomNumber=10+(int)(Math.random()*((20-10)+1));

A final result is a random number in the range of 10 to 20.

Using Random class

You can use java.util.Random to generate random numbers in java.You can generate integers, float, double, boolean etc using Random class.

Let’s understand with the help of example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

packageorg.arpit.java2blog;

import java.util.Random;

publicclassRandomClassGeneratorMain{

publicstaticvoidmain(Stringargs){

Random randomGenerator=newRandom();

System.out.println(«============================»);

System.out.println(«Generating 5 random integers»);

System.out.println(«============================»);

for(inti=;i<5;i++){

System.out.println(randomGenerator.nextInt());

}

System.out.println(«============================»);

System.out.println(«Generating 5 random double»);

System.out.println(«============================»);

for(inti=;i<5;i++){

System.out.println(randomGenerator.nextDouble());

}

System.out.println(«============================»);

System.out.println(«Generating 5 random floats»);

System.out.println(«============================»);

for(inti=;i<5;i++){

System.out.println(randomGenerator.nextFloat());

}

System.out.println(«============================»);

System.out.println(«Generating 5 random booleans»);

System.out.println(«============================»);

for(inti=;i<5;i++){

System.out.println(randomGenerator.nextBoolean());

}

}

}
 

Output:

============================
Generating 5 random integers
============================
1342618771
-1849662552
1719085329
2141641685
-819134727
============================
Generating 5 random doubles
============================
0.1825454639005325
0.5331492085899436
0.830900901839756
0.8490109501015005
0.7968080535091425
============================
Generating 5 random floats
============================
0.9831014
0.24019146
0.11383718
0.42760438
0.019532561
============================
Generating 5 random booleans
============================
false
false
true
true
false

Методы

Обратите внимание, что тригонометрические функции (, , , , , и ) принимают в параметрах или возвращают углы в радианах. Для преобразования радианов в градусы, поделите их на величину ; для преобразования в обратном направлении, умножьте градусы на эту же величину

Обратите внимание, что точность большинства математических функций зависит от реализации. Это означает, что различные браузеры могут дать разные результаты, более того, даже один и тот же движок JavaScript на различных операционных системах или архитектурах может выдать разные результаты

Возвращает абсолютное значение числа.
Возвращает арккосинус числа.
Возвращает гиперболический арккосинус числа.
Возвращает арксинус числа.
Возвращает гиперболический арксинус числа.
Возвращает арктангенс числа.
Возвращает гиперболический арктангенс числа.
Возвращает арктангенс от частного своих аргументов.
Возвращает кубический корень числа.
Возвращает значение числа, округлённое к большему целому.
Возвращает количество ведущих нулей 32-битного целого числа.
Возвращает косинус числа.
Возвращает гиперболический косинус числа.
Возвращает Ex, где x — аргумент, а E — число Эйлера (2,718…), основание натурального логарифма.
Возвращает , из которого вычли единицу.
Возвращает значение числа, округлённое к меньшему целому.
Возвращает ближайшее число с плавающей запятой одинарной точности, представляющие это число.
Возвращает квадратный корень из суммы квадратов своих аргументов.
Возвращает результат умножения 32-битных целых чисел.
Возвращает натуральный логарифм числа (loge, также известен как ln).
Возвращает натуральный логарифм числа (loge, также известен как ln).
Возвращает десятичный логарифм числа.
Возвращает двоичный логарифм числа.
Возвращает наибольшее число из своих аргументов.
Возвращает наименьшее число из своих аргументов.
Возвращает основание в степени экспоненты, то есть, значение выражения .
Возвращает псевдослучайное число в диапазоне от 0 до 1.
Возвращает значение числа, округлённое до ближайшего целого.
Возвращает знак числа, указывающий, является ли число положительным, отрицательным или нулём.
Возвращает синус числа.
Возвращает гиперболический синус числа.
Возвращает положительный квадратный корень числа.
Возвращает тангенс числа.
Возвращает гиперболический тангенс числа.
Возвращает строку .
Возвращает целую часть числа, убирая дробные цифры.

Random Number Generator Function

Now let’s use the method to create a function that will return a random integer between two values (inclusive).

Let’s break down the logic here.

The method will return a floating-point number between 0 and 1 (exclusive).

So the intervals would be as follows:

To factor the second interval, subtract min from both ends. So that would give you an interval between 0 and .

So now, to get a random value you would do the following:

Here is the random value.

Currently, is excluded from the interval. To make it inclusive, add 1. Also, you need to add the back that was subtracted earlier to get a value between .

Alright, so now the last step remaining is to make sure that is always an integer.

You could use the method instead of , but that would give you a non-uniform distribution. This means that both and will have half a chance to come out as an outcome. Using will give you perfectly even distribution.

So now that you have a fair understanding of how a random generation works, let’s use this function to simulate rolling dice.

Generating Javascript Random Numbers More Easily

is a useful function, but on its own it doesn’t give programmers an easy way to generate pseudo-random numbers for specific conditions. There may be a need to generate random numbers in a specific range that doesn’t start with 0, for example.

Fortunately, there are simple functions that programmers can create to make pseudo-random numbers more manageable. The rest of this section will show you how to create those functions, then put them all together into a single pseudo-random number generator.

Integer Pseudo-Random Numbers Across A Range

In the previous examples, could never create a number at the very top of a specified range. If you wanted a number between 0 and 5, for example, you could get 0-4, but never 5. The solution to this problem, if you’re creating an integer, is adding 1 to the result.

Since floating point numbers in Javascript go out to many decimal places, there isn’t a simple one-number solution to include the maximum possible floating point number in your range unless you want to make shaky assumptions and type a lot of zeroes. Instead, you can use some simple math that also works with integers to get pseudo-random numbers all across your range.

Floating-Point Pseudo-Random Numbers Across A Range

A function that does this for floating point numbers would look almost identical, except that it wouldn’t use :

Floating point numbers remain a little tricky here because by default generates the maximum number of decimal places the Javascript implementation allows. In most circumstances, you probably want to cap your decimal places at 3 or 4 instead of reading the 10 or more that usually creates.

Floating-Point Pseudo-Random Numbers With Specific Decimal Places

The function formats a number with the number of decimal places you specify. To make sure that you don’t accidentally create a string in some Javascript implementations, it’s best to always chain with the function.

Putting It All Together

Putting all of this together, a Javascript pseudo-random number generator that can create integers or floating point numbers with any number of decimal places could look like this. (Note that this implementation also includes error checking for the parameters.)

How Math.random() is implemented

The Math.random() method internally creating a single new pseudorandom-number generator, exactly as if by the expression new java.util.Random(). This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else. The nextDouble() method of Random class is called on this pseudorandom-number generator object.

This method is properly synchronized to allow correct use by more than one thread. However, if many threads need to generate pseudorandom numbers at a great rate, it may reduce contention for each thread to have its own pseudorandom-number generator.

As the largest double value less than 1.0 is Math.nextDown(1.0), a value x in the closed range where x1<=x2 may be defined by the statements.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

❮ Math.round()
Java Tutorial ❯

Git Essentials

Ознакомьтесь с этим практическим руководством по изучению Git, содержащим лучшие практики и принятые в отрасли стандарты. Прекратите гуглить команды Git и на самом деле изучите это!

95

И если вы хотите генерировать последовательности, можно создать вспомогательный метод:

public static List intsInRange(int size, int lowerBound, int upperBound) {
    SecureRandom random = new SecureRandom();
    List result = new ArrayList<>();
    for (int i = 0; i < size; i++) {
        result.add(random.nextInt(upperBound - lowerBound) + lowerBound);
    }
    return result;
}

Которые вы можете использовать в качестве:

List integerList =  intsInRange3(5, 0, 10);
System.out.println(integerList);

И что приводит к:

Математика.случайная()

Класс предоставляет нам отличные вспомогательные методы, связанные с математикой. Одним из них является метод , который возвращает случайное значение в диапазоне . Как правило, он используется для генерации случайных значений процентиля.

Тем не менее, аналогично взлом – вы можете использовать эту функцию для генерации любого целого числа в определенном диапазоне:

int min = 10;
int max = 100;

int randomNumber = (int)(Math.random() * (max + 1 - min) + min);
System.out.println(randomNumber);

Хотя этот подход еще менее интуитивен, чем предыдущий. Выполнение этого кода приводит к чему-то вроде:

43

Если вы хотите работать с последовательностью, мы создадим вспомогательный метод для добавления каждого сгенерированного значения в список:

public static List intsInRange(int size, int lowerBound, int upperBound) {
    List result = new ArrayList<>();
    for (int i = 0; i < size; i++) {
        result.add((int)(Math.random() * (upperBound + 1 - lowerBound) + lowerBound));
    }
    return result;
}

И тогда мы можем назвать это так:

List integerList =  intsInRange(5, 0, 10);
System.out.println(integerList);

Который производит:

ThreadLocalRandom.nextInt()

Если вы работаете в многопоточной среде, класс предназначен для использования в качестве потокобезопасного эквивалента . К счастью, он предлагает метод nextInt () как верхней, так и нижней границей:

int randomInt = ThreadLocalRandom.current().nextInt(0, 10);
System.out.println(randomInt);

Как обычно, нижняя граница включена, в то время как верхняя граница отсутствует:

3

Аналогично, вы можете создать вспомогательную функцию для создания последовательности этих:

public static List intsInRange(int size, int lowerBound, int upperBound) {
    List result = new ArrayList<>();
    for (int i = 0; i < size; i++) {
        result.add(ThreadLocalRandom.current().nextInt(lowerBound, upperBound));
    }
    return result;
}

Которые вы можете использовать в качестве:

List integerList = intsInRange4(5, 0, 10);
System.out.println(integerList);

SplittableRandom.ints()

Менее известным классом в Java API является класс , который используется в качестве генератора псевдослучайных значений. Как следует из названия, он разбивается и работает параллельно, и на самом деле используется только тогда, когда у вас есть задачи, которые можно снова разделить на более мелкие подзадачи.

Стоит отметить, что этот класс также основан на небезопасной генерации семян-если вы ищете безопасную генерацию семян, используйте .

Класс предлагает метод , который, с нашей точки зрения, работает так же, как :

List intList = new SplittableRandom().ints(5, 1, 11)
        .boxed()
        .collect(Collectors.toList());

System.out.println(intList);

Что приводит к:

И, если вы хотите сгенерировать только одно случайное число, вы можете отказаться от коллектора и использовать с :

int randomInt = new SplittableRandom().ints(1, 1, 11).findFirst().getAsInt();
System.out.println(randomInt);

Что приводит к:

4

Вывод

В этом уроке мы подробно рассмотрели как генерировать случайные целые числа в диапазоне в Java .

Мы рассмотрели новейший и наиболее полезный метод, а также некоторые другие популярные методы выполнения этой задачи. Большинство подходов основаны на или эквивалентных классах, используемых для более конкретных контекстов.

Using Math.random method

You can use Math.random’s method to generate random doubles.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

packageorg.arpit.java2blog;

publicclassMathRandomMain{

publicstaticvoidmain(Stringargs){

System.out.println(«============================»);

System.out.println(«Generating 5 random doubles»);

System.out.println(«============================»);

for(inti=;i<5;i++){

System.out.println(Math.random());

}

}

}
 

Output:

============================
Generating 5 random doubles
============================
0.3644159931296438
0.07011727069753859
0.7602271011682066
0.914594143579762
0.6506514073704143

Read also:Java random number between 0 and 1Java random number between 1 and 10

Generate random numbers between range

If you want to generate random numbers between certain range, you can use Random and ThreadLocalRandom to do it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

packageorg.arpit.java2blog;

import java.util.Random;

import java.util.concurrent.ThreadLocalRandom;

publicclassGenerateRandomInRangeMain{

publicstaticvoidmain(Stringargs){

intminimum=10;

intmaximum=20;

System.out.println(«============================»);

System.out.println(«Generating 5 random integer in range of 10 to 20 using Random»);

System.out.println(«============================»);

Random randomGenerator=newRandom();

for(inti=;i<5;i++){

System.out.println(randomGenerator.nextInt((maximum-minimum)+1)+minimum);

}

System.out.println(«============================»);

System.out.println(«Generating 5 random integer in range of 10 to 20 using ThreadLocalRandom»);

System.out.println(«============================»);

for(inti=;i<5;i++){

System.out.println(ThreadLocalRandom.current().nextInt(minimum,maximum+1));

}

System.out.println(«============================»);

System.out.println(«Generating 5 random integer in range of 10 to 20 using Math.random»);

System.out.println(«============================»);

for(inti=;i<5;i++){

System.out.println(minimum+(int)(Math.random()*((maximum-minimum)+1)));

}

}

}
 

Output:

============================
Generating 5 random integer in range of 10 to 20 using Random
============================
11
18
14
13
15
============================
Generating 5 random integer in range of 10 to 20 using ThreadLocalRandom
============================
10
12
13
13
16
============================
Generating 5 random integer in range of 10 to 20 using Math.random
============================
14
10
16
20
15

That’s all about generating random numbers in java.

Random Number Generator in Java

There are many ways to generate a random number in java.

  1. java.util.Random class can be used to create random numbers. It provides several methods to generate random integer, long, double etc.
  2. We can also use Math.random() to generate a double. This method internally uses Java Random class.
  3. class should be used to generate random number in multithreaded environment. This class is part of Java Concurrent package and introduced in Java 1.7. This class has methods similar to Java Random class.
  4. can be used to generate random number with strong security. This class provides a cryptographically strong random number generator. However, it’s slow in processing. So depending on your application requirements, you should decide whether to use it or not.

Java Random Number Generator

Let’s look at some examples to generate a random number in Java. Later on, we will also look at ThreadLocalRandom and SecureRandom example program.

1. Generate Random integer

Yes, it’s that simple to generate a random integer in java. When we create the Random instance, it generates a long seed value that is used in all the method calls. We can set this seed value in the program, however, it’s not required in most of the cases.

2. Java Random number between 1 and 10

Sometimes we have to generate a random number between a range. For example, in a dice game possible values can be between 1 to 6 only. Below is the code showing how to generate a random number between 1 and 10 inclusive.

The argument in the is excluded, so we have to provide argument as 11. Also, 0 is included in the generated random number, so we have to keep calling nextInt method until we get a value between 1 and 10. You can extend the above code to generate the random number within any given range.

7. Generate Random byte array

We can generate random bytes and place them into a user-supplied byte array using Random class. The number of random bytes produced is equal to the length of the byte array.

8. ThreadLocalRandom in multithreaded environment

Here is a simple example showing ThreadLocalRandom usage in a multithreaded environment.

Below is a sample output of my execution of the above program.

We can’t set seed value for ThreadLocalRandom instance, it will throw .

ThreadLocalRandom class also has some extra utility methods to generate a random number within a range. For example, to generate a random number between 1 and 10, we can do it like below.

ThreadLocalRandom has similar methods for generating random long and double values.

9. SecureRandom Example

You can use SecureRandom class to generate more secure random numbers using any of the listed providers. A quick SecureRandom example code is given below.

That’s all about generating a random number in Java program.

You can download the example code from our GitHub Repository.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector