How to generate random password in Java

1 Answer

0 votes
import java.util.Random;

public class MyClass {
    public static String generateRandomPassword(int len) {
		String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%&";
		
		Random rnd = new Random();
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++)
			sb.append(chars.charAt(rnd.nextInt(chars.length())));
		
		return sb.toString();
	}
    public static void main(String args[]) {
        System.out.println(generateRandomPassword(8));
    }
}



/*
run:

@%sPh5E2

*/

 



answered Mar 21, 2021 by avibootz

Related questions

1 answer 64 views
1 answer 59 views
1 answer 51 views
1 answer 56 views
3 answers 93 views
93 views asked Dec 22, 2024 by avibootz
2 answers 67 views
67 views asked Dec 21, 2024 by avibootz
1 answer 59 views
59 views asked Dec 21, 2024 by avibootz
...