- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements