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 |
A queue is another kind of linear data structure that is used to store elements just like any other data structure but in a particular manner. In simple words, we can say that the queue is a type of data structure in the Java programming language...
10 min read
Variables are an essential part of data storage and manipulation in the realm of programming. In addition to making values available within a programme, they offer a means of holding them temporarily. Not all variables, though, are made equally. Each variable has a scope that specifies...
3 min read
Finding the intersection of arrays with distinct elements in Java involves identifying common elements shared by two or more arrays. Since the elements are unique within each array, the task simplifies to efficiently comparing sets. This process is useful in various applications like data filtering, set...
8 min read
Using JavaBeans in the Java program allows us to encapsulate many objects into a single object called a bean. Java is an object-oriented programming language that makes the develop once, run and reuse the program everywhere most important. However, JavaBeans add reusability into the Java program by...
2 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
Problem Statement N ferocious fish are swimming along a river. Every fish has a weight and a direction of travel. Each member in the one-dimensional array that represents the river is a fish. The fish may swim upstream or downstream. Large fish will devour the smaller ones...
5 min read
It is a problem frequently asked in interviews of top IT companies like Google, Amazon, TCS, Accenture, Flipkart etc. By solving the problem, one wants to check the logical ability, critical thinking, and problem-solving skill of the interviewee. So, in this section, we are going to...
11 min read
In Java, macros are enhancements to JDK 7 compiler. It adds and supports compile time macros. Macros are Java classes that are instantiated and executed at compile-time. The macros take in a source file's parse tree and a ParserFactory that can be used to parse dynamically...
2 min read
Java 11 introduces a tool called Predicate.not() to make negating predicates easier. Predicates, which are frequently employed in filtering and conditional logic, are functional interfaces that express boolean-valued functions of a single argument. Negating a predicate in Java 11 required a significantly lengthier method. Predicate.not()...
4 min read
It is a problem frequently asked in interviews of top IT companies like Google, Amazon, TCS, Accenture, Flipkart etc. By solving the problem, one wants to check the logical ability, critical thinking, and problem-solving skill of the interviewee. So, in this section, we are going to...
5 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