In this post, we will see how to fix IllegalArgumentException: Bound must be positive
in java.
You will generally get this exception while generating random numbers using Random.nextInt() method. If you pass bound as 0
or less than 0
, then you will get the exception.
Let’s understand with the help of example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package org.arpit.java2blog; import java.util.Random; public class GenerateRandomNumberMain { public static void main(String[] args) { System.out.println("============================"); System.out.println("Generating random number"); System.out.println("============================"); Random randomGenerator=new Random(); System.out.println(randomGenerator.nextInt(0) + 1); } } |
When you run the code, you will get following exception.
1 2 3 4 5 6 7 8 |
============================ Generating random number ============================ Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive at java.base/java.util.Random.nextInt(Random.java:388) at org.arpit.java2blog.GenerateRandomNumberMain.main(GenerateRandomNumberMain.java:12) |
As we have passed bound as 0
to nextInt()
, we got above exception.
Here is source code Random’s nextInt()
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public int nextInt(int bound) { if (bound <= 0) throw new IllegalArgumentException(BadBound); int r = next(31); int m = bound - 1; if ((bound & m) == 0) // i.e., bound is a power of 2 r = (int)((bound * (long)r) >> 31); else { for (int u = r; u - (r = u % bound) + m < 0; u = next(31)) ; } return r; } |
As you can see, if bound is less than or equals to 0, we will get this exception.
To resolve the issue, pass positive number to nextInt() method.
Here is code to generate random number between 1 to 5.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package org.arpit.java2blog; import java.util.Random; public class GenerateRandomNumberMain { public static void main(String[] args) { System.out.println("============================"); System.out.println("Generating random number"); System.out.println("============================"); Random randomGenerator=new Random(); System.out.println(randomGenerator.nextInt(5)+1); } } |
When you run the code, you will get following exception.
1 2 3 4 5 6 |
============================ Generating random number ============================ 2 |
As you can see, we have passed bound as 5
to nextInt() method and it worked fine now.
Further reading:
That’s all about how to fix IllegalArgumentException: Bound must be positive
.