Random longs(long, long) in Java

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

Syntax:

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

This method takes two arguments. This method returns an effectively unlimited stream of pseudorandom long values, each conforming to the given origin (inclusive) and bound(exclusive).

Parameters: Two parameters are required for this method.

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

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

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

Throws:

IllegalArgumentException - if randomNumberOriginis greater than or equal to randomNumberBound.

Approach 1: When no exception

Java

import java.util.Random;

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

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

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

Output:

9223372036854775807


Approach 2: IllegalArgumentException 

Java

import java.util.Random;

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

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

        System.out.println(random.longs(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:864)


No comments:

Post a Comment