Java Random.nextLong() – Examples

In this tutorial, we will learn about the Java Random.nextLong() method, and learn how to use this method to generate a random long value, with the help of examples.

nextLong()

Random.nextLong() returns the next pseudorandom, uniformly distributed long value from this random number generator’s sequence.

ADVERTISEMENT

Syntax

The syntax of nextLong() method is

Random.nextLong()

Returns

The method returns long value.

Example 1 – nextLong()

In this example, we will create an object random of Random class type. We will call nextLong() on this Random object to get the next long value. We shall print this long value to console.

Java Program

import java.util.Random;

public class Example{ 
    public static void main(String[] args) {
    	Random random = new Random();
    	long l = random.nextLong();
    	System.out.println("Next random long value is : " + l);
    }
}

Output

Next random long value is : 5015315584966125576

Output may vary, since the long value is generated randomly.

Example 2 – nextLong()

In this example, we will generate random long values in a for loop using nextLong().

Java Program

import java.util.Random;

public class Example{ 
    public static void main(String[] args) {
    	Random random = new Random();
    	for (int i=0; i < 10; i++) {
    		System.out.println(random.nextLong());
    	}
    }
}

Output

3697628055853821710
3518501742944499700
6568893102887420578
-182089578053327222
-8217330180285651389
-5006204463189382147
-2128146498410395251
-5670315491622791709
-1784447121146279190
-8502179422746111454

Output may vary, since the long value is generated randomly.

Conclusion

In this Java Tutorial, we have learnt the syntax of Java Random.nextLong() method, and also learnt how to use this method with the help of examples.