We help IT Professionals succeed at work.
Get Started

Random String generation

itsme_asif asked
Last Modified: 2013-12-22
Hi Experts,

I would you can send me Java code samples to generate a random string for password with the following requirements

Password Length = 10

One or more lowercase alphabetic characters (a-z)
One or more uppercase alphabetic characters (A-Z)
One or more numeric characters (0-9)
One or more special characters (!@#$%^&*-+= etc)

I already have the following code with generates, 1 number, 1 Upper case char, 1 Lower case char, however I dont know how to add special chars to the list.

public static String genPwd() {
    	// Generate alpha numeric password of length 10

        int length = 10;

        if (length > 0) {
            char[] pw = new char[length];
            int c ='A';
            int  r1 = 0;
            for (int i=0; i < length; i++) {
                r1 = (int)(Math.random() * 3);
                // pick a random upper case or lower case letter or a digit
                switch(r1) {
                case 0: c = '0' +  (int)(Math.random() * 10); break;
                case 1: c = 'a' +  (int)(Math.random() * 26); break;
                case 2: c = 'A' +  (int)(Math.random() * 26); break;
                pw[i] = (char)c;

            return new String(pw);

        return null;

Open in new window

Watch Question
This problem has been solved!
Unlock 1 Answer and 2 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE