java

How to generate a random string in Java

In this tutorial, we are going to see how to generate a random string in Java.
 

How to generate a random string in Java

In this example, the getRandomStr(n) function generates a random number of a given length.

public class Main { 
    public static String getRandomStr(int n) 
    {
        //choose a random character from this string
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                    + "abcdefghijklmnopqrstuvxyz"; 
  
        StringBuilder s = new StringBuilder(n); 
  
        for (int i = 0; i < n; i++) { 
            int index = (int)(str.length() * Math.random()); 
            s.append(str.charAt(index)); 
        } 
        return s.toString(); 
    } 
  
    public static void main(String[] args) 
    { 
        // String length
        int len = 25; 
        System.out.println(getRandomStr(len)); 
    } 
}

Output:

xBrcgUUuIpybtNDdmZKXSkQXy
[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *