Hi folks!
I hope you all are fine! Today, I want to show you how to generate a random password.
First of all, we need to create the class and define the valid characters for our password.
Well, lets consider characters 0 to 9, A to Z, capital and lower cases.
We can call the class PasswordGenerator.
public class PasswordGenerator {
public static void main(String[] args) {
String validChars = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
char[] chars = validChars.split(",");
}
}
Now, lets create the method that will generate the password. And this, is going to return a String. And we can call it with an int parameter, and lets call it length.
This method will look like this:
public static String generatePassword(int length) {
//code here
}
Now, inside this method, lets write the real code that generates it for us!
public static String generatePassword(int passLength) {
//Setting the valid charaters for the generated password
String validChars = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
//Creating an array by splitting the above String by the comma
String[] chars = validChars.split(",");
//Create the String that will store each charater that will be chosen
StringBuilder password = new StringBuilder();
//This object will be the random that will "bounce" between the chars array.
//Don't forget to import the Random class from util package (java.util.Random).
Random r = new Random();
//This loop will make the Random object (r) bounce between the array many times
//The quantity of times is called "passLength"
for (int i = 0; i < passLength; i++){
password.append(chars[r.nextInt(chars.length)]);
}
return password.toString();
}
And now, we have to call this method inside the main method. Lets do it.
public static void main(String[] args) {
//In this example, we generate a 20 lengthened password
//But you can set the length you want
System.out.println(generatePassword(20));
}
Well, heres is the full code:
import java.util.Random;
public class PasswordGenerator {
public static void main(String[] args) {
//In this example, we generate a 20 lengthened password
//But you can set the length you want
System.out.println(generatePassword(20));
}
public static String generatePassword(int length) {
String validChars = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
String[] chars = validChars.split(",");
StringBuilder password = new StringBuilder();
Random r = new Random();
for (int i = 0; i < length; i++){
password.append(chars[r.nextInt(chars.length)]);
}
return password.toString();
}
}
Lets compile the code.
Great! No errors!
Lets execute.
Lets execute again!
You see? Different results!
We did it!
Top comments (1)
amazing useful post