Java Program to generate random string


We can make use of the String that holds all the characters that can be a part of the random string to be generated and make use of the java.util.Random class to generate the random string based on the length required.

Program:
import java.util.Random;

/**
 * Code2care Java Examples
 *
 * Generate Random String
 *
 */
public class JavaRandomStringExample {

    public static void main(String[] args) {
       JavaRandomStringExample jrs = new JavaRandomStringExample();
        System.out.println(jrs.generateRamdonString(15));
        System.out.println(jrs.generateRamdonString(25));
        System.out.println(jrs.generateRamdonString(35));
        System.out.println(jrs.generateRamdonString(45));
    }

    public String generateRamdonString(int size) {
        String digits = "ABCDEFGHIJKLMNOPQRSTUVWZYZabcdefghijklmnopqrstuvwxyz0123456789";
        int sizeOfRandomString = size;
        StringBuilder randomString = new StringBuilder();

        for(int i=1;i<=sizeOfRandomString;i++) {
            Random random = new Random();
            int position = random.nextInt(digits.length());
            randomString = randomString.append(digits.charAt(position));
        }

        return  randomString.toString();
    }
}
Output:

7pgxqwiR1TEhZJB
kJexTSwpP6pt6kbTY22LhFxFC
m2kySQF7QLx1JGLR9Kz3CCPHkBFircEE9Jt
esMtxgqWd31UbokPwWqAwqu8sak5aJYTpYyoKdPZYH5q6

Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.


echo('');