×

Java Programs

Java Practice

Java method to generate OTP (One Time Password) string

In this program, we will learn how to generate OTP (One Time Password) string in Java?

This program will generate OTP as string (4 digits PIN) different at every run. When we run program, program will return 4 digits PIN, which will be different from last generate OTP (One Time Password).

public class GenerateOTP {
    /**
    * Method for Generate OTP String
    * @return 
    */

	public static String generateOTP() {
		int randomPin   =(int)(Math.random()*9000)+1000;
		String otp  =String.valueOf(randomPin);
		return otp;
	}
   
	public static void main(String[] args) {
		String otpSting  =generateOTP();
		System.out.println("OTP : "+otpSting);
	}
}

Output

First run:
OTP : 2517

Second run:
OTP : 1528

See the output, when I run the program first time the OTP was "2517" and second time it was "1528", both time OTP was different, we can run the program any number of times, each time method will return a different 4 digits OTP.

Java Most Popular & Searched Programs »





Comments and Discussions!

Load comments ↻





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