Home » Java ThreadLocalRandom nextInt() Method with Examples

Java ThreadLocalRandom nextInt() Method with Examples

by Online Tutorials Library

Java ThreadLocalRandom nextInt() method

The nextInt() method of Java ThreadLocalRandom class returns a pseudorandom int value. This method overrides the nextInt in class Random.

Syntax:

Parameter:

NA

Returns:

This method returns a pseudorandom int value.

Example 1

Test it Now

Output:

Random int value is: -2035038202  

Java ThreadLocalRandom nextInt(int bound) method

The nextInt(int bound) method of Java ThreadLocalRandom class returns a pseudorandom int value between zero and the specified bound. This method overrides the nextInt in class Random.

Syntax:

Parameter:

bound: It is the upper bound. It must be positive.

Returns:

This method returns a pseudorandom int value between zero and the specified bound.

Exception:

IllegalArgumentException: This exception will throw if bound is not positive

Example 1

Test it Now

Output:

Random int value is: 1566  

Example 2

Test it Now

Output:

Random int value is: 25266  

Example 3

Test it Now

Output:

Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive  at java.base/java.util.concurrent.ThreadLocalRandom.nextInt(Unknown Source)  at tests.JavaNextIntExample3.main(ThreadLocalRandomNextIntExample3.java:7)  

Java ThreadLocalRandom nextInt(int least, int bound) method

The nextInt(int least, int bound) method of Java ThreadLocalRandom class returns a pseudorandom. It returns the uniformly distributed value between the given least value and bound.

Syntax:

Parameter:

least – It is the least value.

bound – It is the upper bound (exclusive).

Returns:

This method returns the next value.

Exception:

IllegalArgumentException – This exception will throw if the least is greater than or equal to bound.

Example 1

Test it Now

Output:

Random int value is: 11  

Example 2

Test it Now

Output:

Exception in thread "main" java.lang.IllegalArgumentException: bound must be greater than origin  at java.base/java.util.concurrent.ThreadLocalRandom.nextInt(Unknown Source)  at tests.JavaNextIntExample2.main(ThreadLocalRandomNextIntExample2.java:7)  

You may also like