[Fixed] IllegalArgumentException: Bound must be positive

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:

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.

============================
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.

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.

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.

============================
Generating random number
============================
2

As you can see, we have passed bound as 5 to nextInt() method and it worked fine now.

That's all about how to fix IllegalArgumentException: Bound must be positive.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.