Generate Random String of Given Size in Java7 Jan 2025 | 9 min read Generating a random string in Java is a simple concept which is often required to build Ids, temporary passwords, session tokens or any other case where the alphanumeric string is most electronically required. There are several ways to achieve this using the different classes and methods. Approach 1: Using Math.random()The Math.random() method returns a random double number between 0.0 (inclusive) and 1.0 (exclusive), this value can be scaled and cast to an integer to accurately choose characters from a predefined set of characters in order to construct a random string. AlgorithmStep 1: Define the Character Set: Make a string with all the characters that can be part of the random string (for instance, uppercase letters, lowercase letters, numbers). Step 2: Initialize a StringBuilder: Use a StringBuilder to efficiently build the string, as it allows for dynamic resizing and appending. Step 3: Generate Random Characters: Use a loop to generate each character of the string by generating a random index using Math.random(). Select the character at the generated index from the character set. Step 4: Append the selected character to the StringBuilder. Convert the StringBuilder to a string and return it. Filename: MathRandomStringGenerator.java Output: Random String: S14AL6rGlO Approach 2: Using CharSetWhen generating random strings in Java using a CharSet offers flexibility and control over the characters that can appear in the string, this approach allows you to specify which characters to include, such as only uppercase letters, lowercase letters, digits, special characters, or any combination of these. AlgorithmStep 1: Initialize SecureRandom: Create an instance of SecureRandom to ensure cryptographically strong random values. Step 2: Define the Character Set: Specify a string containing all the characters that can be used in the random string. Create a StringBuilder instance to efficiently build the string of the desired length.
Step 3: Generate Random Characters: For each position in the desired length of the string, generate a random index using the SecureRandom instance. Step 4: Use the random index to pick a character from the character set. Append the selected character to the StringBuilder. Convert the StringBuilder to a string and return it. Filename: SecureCustomCharSetRandomStringGenerator.java Output: Secure Random String: jf0ip3t8LI Approach 3: Using Regular ExpressionsRegular expressions (regex) in Java provides a way to describe patterns that strings can match. To generate random strings using regex, you typically use placeholders and quantifiers to define the structure of the string (e.g., characters, digits, special characters) and then randomly replace those placeholders with actual characters. AlgorithmStep 1: Create a StringBuilder (sb) to construct the random string. Instantiate a Random object (random) to generate random numbers. Step 2: Compile the Regex Pattern: Use Pattern.compile(regexPattern) to compile the regexPattern string into a Pattern object (pattern). Step 3: Start a loop to generate characters for the string from 0 to length - 1. Generate a random integer within the ASCII range (32 to 126) using random.nextInt(126 - 32 + 1) + 32. Cast this integer to a character (char) to get a random ASCII character. Step 4: Append the generated random character (randomChar) to the StringBuilder (sb). Convert the StringBuilder to a string (sb.toString()). Create a Matcher (matcher) by calling pattern.matcher(string) to check if the generated string matches the regex pattern. Step 5: If the generated string does not match the regex pattern (!matcher.matches()), recursively call generateRandomString(regexPattern, length) until a matching string is generated. Step 6: Once a valid string matching the regex pattern is generated, return it as the output. Filename: RegexRandomStringGenerator.java Output: Random String: dhc4xKc5IA Approach 4: Using a ListGenerating random strings using lists in Java is a flexible and efficient approach. Lists provide dynamic sizing and easy manipulation, which makes them suitable for managing a custom set of characters from which you can generate random strings, this method involves storing characters in a list and randomly picking characters from this list to form the desired random string. AlgorithmStep 1: The list charList is initialized and populated with uppercase letters ('A' to 'Z'), lowercase letters ('a' to 'z'), and digits ('0' to '9'). Step 2: Random Character Selection: A Random object (random) is used to generate random indices within the bounds of charList. Step 3: For each iteration of the loop (from 0 to length - 1), a random index is generated, and the corresponding character from charList is appended to the StringBuilder (sb). Step 4: String Construction: The StringBuilder efficiently constructs the final random string by appending each selected random character. The method sb.toString() converts the StringBuilder to a string, which is then returned as the final random string. Step 5: The main method sets the desired length of the random string (10 in this example) and calls the generateRandomString method to generate and print the random string. Filename: ListRandomStringGenerator.java Output: Random String: e3fhP3zA4U Approach 5: Using a DequeUsing a Deque (Double-Ended Queue) to generate random strings offers flexibility in constructing strings with specific patterns or constraints. This approach is particularly useful when you need to control the placement of characters or create strings that follow required rules. AlgorithmStep 1: Define a string charSet containing all the characters that can be used to generate the random string (e.g., "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"). Step 2: Initialize a Deque of type Character (charDeque). Instantiate a Random object (random) to generate random numbers. Step 3: Generate Random Characters: Loop from 0 to length - 1 (where length is the desired length of the random string): Generate a random index within the bounds of charSet. Step 4: Retrieve the character at the generated index from charSet. Randomly decide to add this character to the front or the back of charDeque using random.nextBoolean(): Step 4.1: If true, add the character to the front of the deque (charDeque.addFirst(randomChar)). If false, add the character to the back of the deque (charDeque.addLast(randomChar)). Step 5: Construct Final String: Initialize a StringBuilder (sb) to construct the final string. While charDeque is not empty: Remove the character from the front of the deque (charDeque.pollFirst()) and append it to sb. Step 6: Convert StringBuilder to a string (sb.toString()) and return it as the final random string. Filename: DequeRandomStringGenerator.java Output: Random String: 9DhhXfzcBj Approach 6: Using QueueUsing a Queue to generate random strings in Java provides flexibility in controlling the order of character insertion and retrieval, this approach is particularly useful when you want to impose specific constraints or patterns on how characters are added or processed. AlgorithmStep 1: Define charSet, a string containing all possible characters for the random string (ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789). Step 2: Create a Queue<Character> named charQueue using LinkedList to store characters. Instantiate a Random object (random) to generate random numbers. Step 3: Generate Random String: Use a for loop to iterate length times (where length is the desired length of the random string). Generate a random index (random.nextInt(charSet.length())) to select a character from charSet. Step 4: Retrieve the character at the random index using charSet.charAt(). Add the character to the end of charQueue using charQueue.offer(randomChar). Step 5: Initialize a StringBuilder (sb) with the specified capacity (length) to efficiently build the final random string. Use a while loop to iterate until charQueue is empty: Remove characters from the front of charQueue using charQueue.poll() and append them to sb. Step 6: Convert StringBuilder sb to a string using sb.toString() and return it as the final random string. Step 7: In the main method, specify the desired length of the random string (e.g., 10). Call generateRandomString(length) to generate the random string and store it in randomString. Filename: QueueRandomStringGenerator.java Output: Random String: B2sRLhAMn6 |
Everyone faces errors while dealing with programming. Errors are bad for the developers because hard to handle. Some errors cause glitches that puzzled users. For an application, the two most important concessions are safety and security. It does not matter what type of application we are...
4 min read
The java.nio.DoubleBuffer contains hasArray() function. The DoubleBuffer class is utilized to verify if the provided buffer is supported by a float array that may be accessed. If a backing array for this buffer is reachable, it returns true; otherwise, it returns false. The array() and arrayOffset()...
3 min read
| Rotate Matrix in Java Clockwise and Anti-clockwise In this section, we will create a Java program to rotate a matrix by 90 degrees in a clockwise and anti-clockwise rotation. The clockwise rotation is also known as the right rotation of the matrix and the anti-clockwise...
3 min read
The Java programming language is a platform-independent language (WORA) because it does not depend on any platform type. When a Java code is compiled, it is compiled into byte code through JIT (Just-in-Time) compiler, and the byte code is independent of the platform. To execute the...
3 min read
Collections of objects can be processed using the Stream API, which was first released in Java 8. A stream is a collection of items that can be pipelined in a variety of ways to achieve distinct outcomes. Java Stream's characteristics are: As an alternative to receiving input...
8 min read
The traffic light system works as a standard mechanism that directs traffic flow together with pedestrian activity to maintain road safety and order throughout intersections. The system uses different signals that change color patterns (including red, yellow and green) for delivering instructions to drivers. In this section,...
5 min read
In this section, we will learn what is equidigital number and also create Java programs to find the equidigital numbers. It is frequently asked in Java coding interviews and academics. Equidigital Number A natural number that has the same number of digits as the number of digits present...
4 min read
The passing and returning of objects between methods is a basic feature of Java programming and is essential to creating reliable, modular programs. In this section, we will discuss passing and returning objects in Java, exploring different kinds and methods along the way and offering complete...
5 min read
The hash function is a key-value mapping function. When two or more keys are mapped to the same value using these hashing methods, there exists duplicate values. The use of chain hashing ents collisions. Each hash table cell should lead to a linked list of entries...
6 min read
Programmers may design effective and responsive programs with the help of Java's robust features, which make it a versatile and popular language. Multithreading and multiprogramming are two essential ideas in Java that are connected to concurrent execution. Although both include carrying out several activities at once,...
4 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India