Java Data Type How to - Create a random password








Question

We would like to know how to create a random password.

Answer

import java.util.Random;
/*  ww  w  . j a  va 2 s. c  o m*/
public class Main {
  public static void main(String[] argv) {
    for (int i = 0; i <= 10; i++) {
      printPassword();
    }
  }
  private static void printPassword() {
    String UPPER = "ABCDEFGHIJKLMNPQRSTUVWXYZ";
    String LOWER = "abcdefghijklmnpqrstuvwxyz";
    String NUMBER = "123456789";
    String SPECIAL = "!@#$%&*+?";
    Random randGen = new Random();

    StringBuffer buf = new StringBuffer();
    buf.append(LOWER.charAt(Math.abs(randGen.nextInt()) % LOWER.length()));
    buf.append(LOWER.charAt(Math.abs(randGen.nextInt()) % LOWER.length()));
    buf.append(NUMBER.charAt(Math.abs(randGen.nextInt()) % NUMBER.length()));
    for (int i = 0; i <= 4; i++) {
      buf.append(LOWER.charAt(Math.abs(randGen.nextInt()) % LOWER.length()));
    }
    buf.append(UPPER.charAt(Math.abs(randGen.nextInt()) % UPPER.length()));
    buf.append(LOWER.charAt(Math.abs(randGen.nextInt()) % LOWER.length()));
    System.out.println(buf.toString());
  }
}