Generating OTP in Java


Generate OTP is now a requirement on most of the website now-a-days. In case of additional authentication, system generates a OTP password adhering to OTP policy of the company. Following example generates a unique OTP adhering to following conditions −

  • It should contain at least one number.
  • Length should be 4 characters.

Example

import java.util.Random;

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

      System.out.println(generateOTP(4));
   }

   private static char[] generateOTP(int length) {
      String numbers = "1234567890";
      Random random = new Random();
      char[] otp = new char[length];

      for(int i = 0; i< length ; i++) {
         otp[i] = numbers.charAt(random.nextInt(numbers.length()));
      }
      return otp;
   }
}

Output

6674

Updated on: 21-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements