Random longs(long, long, long) in Java

longs(long, long, long): This method is available in java.util.Random class of Java.

Syntax:

LongStream java.util.Random.longs(long streamSize, long randomNumberOrigin, long randomNumberBound)

This method takes three arguments. This method returns a stream producing the given streamSize number of pseudorandom long, each conforming to the given origin(inclusive) and bound (exclusive).

Parameters: Three parameters are required for this method.

streamSize: the number of values to generate.

randomNumberOrigin: the origin (inclusive) of each random value.

randomNumberBound: the bound (exclusive) of each random value.

Returns: a stream of pseudorandom long values, each with the given origin (inclusive) and bound (exclusive).

Throws:

IllegalArgumentException - if streamSize isless than zero, or randomNumberOriginis greater than or equal to randomNumberBound.

Approach 1: When no exception

Java

import java.util.Random;

public class Randomlongs4 {
    public static void main(String[] args) {

        Random random = new Random();
        long streamSize = 100100L;
        long randomNumberOrigin = 10277,
randomNumberBound = 28199;

        System.out.println(random.longs(streamSize,
randomNumberOrigin, randomNumberBound).count());
    }
}

Output:

100100


Approach 2: IllegalArgumentException 

Java

import java.util.Random;

public class Randomlongs4 {
    public static void main(String[] args) {

        Random random = new Random();
        long streamSize = 100100L;
        long randomNumberOrigin = 100277,
randomNumberBound = 28199;

        System.out.println(random.longs(streamSize,
randomNumberOrigin, randomNumberBound).count());
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: bound must be greater than origin at java.base/java.util.Random.longs(Random.java:817)


No comments:

Post a Comment