Search code examples
javarandom

Creating a random string with A-Z and 0-9 in Java


As the title suggest I need to create a random, 17 characters long, ID. Something like "AJB53JHS232ERO0H1". The order of letters and numbers is also random. I thought of creating an array with letters A-Z and a 'check' variable that randoms to 1-2. And in a loop;

Randomize 'check' to 1-2.
If (check == 1) then the character is a letter.
Pick a random index from the letters array.
else
Pick a random number.

But I feel like there is an easier way of doing this. Is there?


Solution

  • Here you can use my method for generating Random String

    protected String getSaltString() {
            String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            StringBuilder salt = new StringBuilder();
            Random rnd = new Random();
            while (salt.length() < 18) { // length of the random string.
                int index = (int) (rnd.nextFloat() * SALTCHARS.length());
                salt.append(SALTCHARS.charAt(index));
            }
            String saltStr = salt.toString();
            return saltStr;
    
        }
    

    The above method from my bag using to generate a salt string for login purpose.