Random longs(long) in Java

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

Syntax:

LongStream java.util.Random.longs(long streamSize)

This method takes one argument. This method returns a stream producing the given streamSize number of pseudorandom long values.

Parameters: One parameter is required for this method.

streamSize: the number of values to generate.

Returns: a stream of pseudorandom long values.

Throws:

IllegalArgumentException - if streamSize is less than zero.

Approach 1: When no exception

Java

import java.util.Random;

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

        Random random = new Random();

        long streamSize = 1010010L;

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

Output:

1010010


Approach 2: IllegalArgumentException

Java

import java.util.Random;

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

        Random random = new Random();

        long streamSize = -1010010L;

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

Output:

Exception in thread "main" java.lang.IllegalArgumentException: size must be non-negative at java.base/java.util.Random.longs(Random.java:748)


No comments:

Post a Comment