What is the SecureRandom.getInstance() method in Java?

Overview

In Java, the getInstance() method is used to get the instance of the SecureRandom class. If we create an instance of the SecureRandom class using a new operator, it will use the SHA1PRNG algorithm. We can provide an algorithm name to the getInstance() method. The SecureRandom class offers this method, which consists of methods to generate substantial random numbers.

Syntax

SecureRandom.getInstance("algorithm name", "algorithm provider")

Parameters

  • algorithm name: This is the name of the algorithm. A NoSuchAlgorithmException is thrown if the algorithm is not found.
  • algorithm provider: This is the name of the algorithm provider. A NoSuchProviderException is thrown if the provider is not found in the list of registered security providers.

Return value

This method returns a SecuredRandom object.

Example

import java.security.*;
import java.util.*;
public class main {
public static void main(String[] argv)
{
try{
//create instance of securerandom with new operator
SecureRandom rndm = new SecureRandom();
//create instance of securerandom with getInstance method
SecureRandom rndm1 = SecureRandom.getInstance("NativePRNG", "SUN");
//get random integer
System.out.println(rndm1.nextInt());
}
catch(Exception e){
System.out.println("Exception is thrown");
}
}
}

Explanation

  • Line 7: We implement a try/catch block, since the getInstance() method throws an exception.
  • Line 9: We get the SecureRandom object, rndm, using the new operator.
  • Line 12: We get the SecureRandom object, rndm1, using the getInstance() method. Next, we pass the algorithm name as NativePRNG and provider as SUN.
  • Line 15: We get the random integer using the nextInt() method on rndm1 object.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved