OTP Generation in Java

In this tutorial, I will show you the program to generate a random OTP in java. They are a unique pattern of numbers of a defined length, used for security purposes. For instance, OTP is used to access our bank account while doing online transaction in order to verify our identity from the bank account, they send us OTP(One Time Password) on our registered number or email-id making the process quicker. The following code explains how to generate OTP easily. So let’s get started to learn OTP generation in Java using random class.

Java program to generate OTP

This program we will use Random class:

Since Java Random class is used to generate a series of random numbers.

  • java.util package contains Random class.
  • An instance of Random class is used to generate random numbers.
  • If two instances have the same seed value, then they will generate the same sequence of random numbers.

Java Code:

import java.util.*; 
public class Prog
{ 
  public static char[] generatorOTP(int length) 
  { 
    System.out.print("Your OTP is : "); 

              //Creating object of Random class
    Random obj = new Random(); 

    char[] otp = new char[length]; 

    for (int i=0; i<length; i++) 
    { 
      otp[i]= (char)(obj.nextInt(10)+48); 
    } 
    return otp; 
  } 
  public static void main(String[] args) 
  {  
    System.out.println(generatorOTP(4)); 
  } 
} 

In this program, the method generatorOTP(int) takes in the length of OTP as parameter. We have created an array of characters which will store the desired OTP.  Each execution of the program generates a unique OTP. The method nextInt() returns next int value from random number generator sequence. We add a displacement of 48 to the generated number. It converts number to its ascii value before casting it to a character. As a result, the method returns the OTP at the end of the loop.

Output:

Your OTP is : 7916

Also read,



Leave a Reply

Your email address will not be published. Required fields are marked *