Generate Random Number Inclusive and Exclusive in Java

Random numbers can be generated using the java.util.Random class or Math.random() static method. There is no need to reinvent the random integer generation when there is a useful API within the standard Java JDK. Unless you really really care for performance then you can probably write your own amazingly super fast generator. In this tutorial I’ve chosen for the java.util.Random class because I find it more readable witch results in cleaner and more understandable code. Remember you write it once and you or someone else will read it many many many times.

The Minimum (min) value cannot be greater than the Maximum (max) value. For simplicity I did not make an assert in the methods themselves.

package com.sheting.basic.utilities;

import java.util.Random;

public class RandomRange {
    private static Random rnd = new Random();

    // Generates a random number between min (inclusive) and max (inclusive)
    public static int nextIncInc(int min, int max) {
        return rnd.nextInt(max - min + 1) + min;
    }

    // Generates a random number between min (inclusive) and max (exclusive)
    public static int nextIncExc(int min, int max) {
        return rnd.nextInt(max - min) + min;
    }

    // Generates a random number between min (exclusive) and max (inclusive)
    public static int nextExcInc(int min, int max) {
        return rnd.nextInt(max - min) + 1 + min;
    }

    // Generates a random number between min (exclusive) and max (exclusive)
    public static int nextExcExc(int min, int max) {
        return rnd.nextInt(max - min - 1) + 1 + min;
    }
}

Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may result in poor performance. Consider instead using ThreadLocalRandom in multithreaded designs.
Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值