1

I have been trying to write a simple java program to display random alphanumeric numbers every time. However I am getting the same result as [C@a3a380

import java.util.*;
import java.security.*;

public class NumericOTPGenerator 
{
    public static void main(String args[])
    {
        int length=5;
        System.out.println("OTP : "+generateOTP(length));
    }
    static char[] generateOTP(int length)
    {
        String capitalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String smallChars = "abcdefghijklmnopqrstuvwxyz";
        String numbers = "0123456789";
        String symbols = "!@#$%^&*_=+-/.?<>)";
        String values = capitalChars + smallChars + numbers + symbols;
        char[] generatedOTP = new char[length];
        SecureRandom rand = new SecureRandom();
        for (int i = 0; i < length; i++)
        {
            generatedOTP[i] = values.charAt(rand.nextInt(values.length()));

        }
        return generatedOTP;
    }
}

Please suggest how do I resolve this issue.

Arnab
  • 195
  • 2
  • 14
  • 4
    `return Arrays.toString(generatedOTP);` instead – jmj Oct 16 '17 at 05:56
  • I don't think so your program is fine, It's returning new OTP every time. May be your are making `toString()` somewhere in your program – Lokesh Pandey Oct 16 '17 at 05:59
  • Arrays,toString() has solved the issue. These urls have helped to understand. https://stackoverflow.com/questions/13505274/java-println-with-char-array-gives-gibberish https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array – Arnab Oct 16 '17 at 06:20
  • It is not smart to create PRNG object every time when you call the function. First of all its slows the program and the numbers are not so secure random. – Todor Balabanov Oct 16 '17 at 06:27
  • I have modified the code accordingly. Also instead of toString, I have used String generatedOTPString = new String(generatedOTP) so that I get the output in the desired manner (not in array format). – Arnab Oct 16 '17 at 16:57

0 Answers0