Home » Java programming language

Java Random nextInt() Method with Example

Random Class nextInt() method: Here, we are going to learn about the nextInt() method of Random Class with its syntax and example.
Submitted by Preeti Jain, on March 23, 2020

Random Class nextInt() method

Syntax:

    public int nextInt();
    public int nextInt(int num);
  • nextInt() method is available in java.util package.
  • nextInt() method is used to return the next pseudo-random value from this Random Value Generator.
  • nextInt(int num) method is used to return the next pseudo-random distribute integer value between 0 and the given parameter (num) from this Random Generator.
  • These methods may throw an exception at the time of returning the next integer value.
    IllegalArgumentException: This exception may throw when the given parameter (num<0) is invalid.
  • These are non-static methods and it is accessible with the class object and if we try to access these methods with the class name then also we will get any error.

Parameter(s):

  • In the first case, nextInt()
    • It does not accept any parameter.
  • In the second case, nextInt(int num)
    • int num – represents the last endpoint of this Random Value Generator.

Return value:

In both the cases, the return type of the method is int – it returns next pseudorandom distributed value between 0 and num.

Example:

// Java program to demonstrate the example 
// of nextInt() method of Random

import java.util.*;

public class NextIntOfRandom {
 public static void main(String args[]) {
  // Instantiates Random object
  Random ran = new Random();

  // By using nextInt() method is
  // to return next int pseudo-random
  // value by using Random Value Generator
  int val = ran.nextInt();

  // Display val
  System.out.println("ran.nextInt(): " + val);

  // By using nextInt(int) method is
  // to return next int pseudo-random
  // value between 0 and the given value
  // and 0 is inclusive whereas the given value 
  // is exclusive by using Random Value Generator
  val = ran.nextInt(50);

  // Display val
  System.out.println("ran.nextInt(50): " + val);
 }
}

Output

RUN 1:
ran.nextInt(): -1450643138
ran.nextInt(50): 13

RUN 2:
ran.nextInt(): 1448295644
ran.nextInt(50): 47

RUN 3:
ran.nextInt(): 397396236
ran.nextInt(50): 11



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.