Table of contents
1.
Introduction
2.
Method 1: Using Math.random()
2.1.
Example
3.
Method 2: Using CharSet
3.1.
Example
4.
Method 3: Using Regular Expressions
4.1.
Example
5.
Method 4: Generating Random String of UpperCaseLetter/LowerCaseLetter/Numbers
5.1.
Example
6.
Generate Random Unbounded String With Plain Java
6.1.
Example
7.
Generate Random Bounded String With Plain Java
7.1.
Example
8.
Generate Random Alphabetic String With Java 8
8.1.
Example
9.
Generate Random Alphanumeric String With Java 8
9.1.
Example
10.
Frequently Asked Questions
10.1.
What is the easiest way to generate a random string in Java?
10.2.
How can I generate a random alphanumeric string?
10.3.
What is the time complexity of generating a random string in Java?
11.
Conclusion
Last Updated: Mar 17, 2025
Easy

Generate Random String in Java

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Generating a random string in Java is useful for creating unique identifiers, passwords, or tokens. Java provides multiple ways to achieve this, such as using the Random class, UUID, and SecureRandom for better security. The UUID method generates universally unique identifiers, while SecureRandom ensures cryptographic strength. 

In this article, we will explore different methods to generate random strings in Java with examples.

Method 1: Using Math.random()

The simplest way to generate a random string is by using Math.random() along with characters from the ASCII table.

Example

import java.util.Random;
public class RandomStringGenerator {
    public static String generateRandomString(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder randomString = new StringBuilder();
        Random random = new Random();   
        for (int i = 0; i < length; i++) {
            int index = (int) (Math.random() * characters.length());
            randomString.append(characters.charAt(index));
        }
        return randomString.toString();
    }

    public static void main(String[] args) {
        System.out.println("Random String: " + generateRandomString(10));
    }
}
You can also try this code with Online Java Compiler
Run Code


Output:

Random String: 4GmT1hY9Xz

Method 2: Using CharSet

Another method to generate a random string is by using Charset and Random.

Example

import java.nio.charset.Charset;
import java.util.Random;
public class CharsetRandomString {
    public static String generateRandomString(int length) {
        byte[] array = new byte[length];
        new Random().nextBytes(array);
        return new String(array, Charset.forName("UTF-8"));
    }
    public static void main(String[] args) {
        System.out.println("Random String: " + generateRandomString(10));
    }
}
You can also try this code with Online Java Compiler
Run Code

Method 3: Using Regular Expressions

We can use regex patterns to define character sets and generate random strings accordingly.

Example

import java.util.UUID;

public class RegexRandomString {
    public static void main(String[] args) {
        String randomString = UUID.randomUUID().toString().replaceAll("-", "");
        System.out.println("Random String: " + randomString.substring(0, 10));
    }
}
You can also try this code with Online Java Compiler
Run Code


Output:

Random String: f47ac10bff

Method 4: Generating Random String of UpperCaseLetter/LowerCaseLetter/Numbers

If you need a specific type of string, such as uppercase, lowercase, or numbers, you can use Random.

Example

import java.util.Random;
public class SpecificRandomString {
    public static String generateRandomString(String charSet, int length) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(charSet.length());
            sb.append(charSet.charAt(index));
        }
        return sb.toString();
    }
    public static void main(String[] args) {
        String upperCaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String lowerCaseLetters = "abcdefghijklmnopqrstuvwxyz";
        String numbers = "0123456789";
        System.out.println("Uppercase Random String: " + generateRandomString(upperCaseLetters, 10));
        System.out.println("Lowercase Random String: " + generateRandomString(lowerCaseLetters, 10));
        System.out.println("Numbers Random String: " + generateRandomString(numbers, 10));
    }
}
You can also try this code with Online Java Compiler
Run Code


Time and Space Complexity

  • Time Complexity: O(n), where n is the length of the generated string.
     
  • Space Complexity: O(n), as we store the generated string in memory.

Generate Random Unbounded String With Plain Java

We can generate unbounded random strings using UUID.

Example

import java.util.UUID;
public class UnboundedRandomString {
    public static void main(String[] args) {
        System.out.println("Random UUID String: " + UUID.randomUUID().toString());
    }
}
You can also try this code with Online Java Compiler
Run Code

Generate Random Bounded String With Plain Java

To limit the generated string to a specific length, we can truncate the UUID.

Example

public class BoundedRandomString {
    public static String generateBoundedString(int length) {
        return UUID.randomUUID().toString().replace("-", "").substring(0, length);
    }
    public static void main(String[] args) {
        System.out.println("Bounded Random String: " + generateBoundedString(8));
    }
}
You can also try this code with Online Java Compiler
Run Code

Generate Random Alphabetic String With Java 8

Using Java 8 Random.ints() method, we can generate alphabetic strings.

Example

import java.util.Random;
import java.util.stream.Collectors;
public class AlphabeticRandomString {
    public static String generateRandomString(int length) {
        Random random = new Random();
        return random.ints(97, 123)
                .limit(length)
                .mapToObj(i -> String.valueOf((char) i))
                .collect(Collectors.joining());
    }
    public static void main(String[] args) {
        System.out.println("Random Alphabetic String: " + generateRandomString(10));
    }
}
You can also try this code with Online Java Compiler
Run Code

Generate Random Alphanumeric String With Java 8

Using Java 8 Random.ints() method, we can generate alphanumeric strings.

Example

import java.util.Random;
import java.util.stream.Collectors;
public class AlphanumericRandomString {
    public static String generateRandomString(int length) {
        String charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        return random.ints(0, charSet.length())
                .limit(length)
                .mapToObj(charSet::charAt)
                .map(String::valueOf)
                .collect(Collectors.joining());
    }
    public static void main(String[] args) {
        System.out.println("Random Alphanumeric String: " + generateRandomString(10));
    }
}
You can also try this code with Online Java Compiler
Run Code

Frequently Asked Questions

What is the easiest way to generate a random string in Java?

Using UUID.randomUUID().toString() is the simplest method, as it generates a unique string automatically.

How can I generate a random alphanumeric string?

Using Java 8 streams and Random.ints() allows efficient generation of alphanumeric strings.

What is the time complexity of generating a random string in Java?

The time complexity is O(n), where n is the length of the string being generated.

Conclusion

In this article, we discussed different approaches to generating random strings in Java. We discussed methods using Math.random(), Random, SecureRandom, and UUID, each offering varying levels of security and randomness. Choosing the right approach depends on the specific use case, whether it's for simple random strings or cryptographically secure ones. Understanding these techniques helps in implementing secure and efficient random string generation in Java applications.

Live masterclass