- Create random String in Java example
- How to create a random string of the specified length in Java?
- 1) Using the Random and String classes
- 2) Using the SecureRandom and BigInteger classes
- Generate Random Character in Java
- Generate Random Character Using random.nextInt() in Java
- Generate Random Character From a String Using random.nextInt() and charAt()
- Generate Random Character Using RandomStringUtils of Apache Commons
- Related Article — Java Char
- Java generate random string
Create random String in Java example
Create random String in Java example shows how to create random string of a specified length in Java. The example also shows how to create random alphanumeric string, random numeric string or random alphabetic string in Java.
How to create a random string of the specified length in Java?
There are several ways in which you can create a random string in Java as given below.
1) Using the Random and String classes
We can create a random string of specified length using the java.util.Random class as given below.
We kept all the allowed characters in a String for later reference and took one random character from it and appended it to the StringBuilder object. When we had required string length, we converted StringBuilder to String and returned it.
You can change the String containing allowed characters according to your needs. You can also change the string required length to generate a random string of specified characters.
Note: Please note that the above solution uses java.util.Random class. If you want a secure solution change the Radom with SecureRandom class.
If you are using Java 1.4 or earlier version, use the StringBuffer class instead of the StringBuilder class.
2) Using the SecureRandom and BigInteger classes
The BigInteger class can be used to generate random strings by using below given constructor.
This constructor creates randomly generated non-negative BigInteger in the range of 0 to 2^bits – 1. Here is the example program to generate random string using BigInteger and SecureRandom classes.
Generate Random Character in Java
- Generate Random Character Using random.nextInt() in Java
- Generate Random Character From a String Using random.nextInt() and charAt()
- Generate Random Character Using RandomStringUtils of Apache Commons
In this tutorial, we will introduce how we can generate a random character using several methods. We will introduce three methods with examples to understand the topic better.
Generate Random Character Using random.nextInt() in Java
Random is the most commonly used class in Java to generate a random value, but it cannot generate characters. To randomize characters using the Random class, we can use random.nextInt() to generate random integers. Every character corresponds to a number.
We can use a character as a bound in the nextInt() function. In the following example, we can see that an object of the Random class is created and then (random.nextInt(26) + ‘a’) is used. Here, the character ‘a’ corresponds to the number 97, using which we can generate 26 random integers that correspond to the lower-case alphabet.
At last, we have to cast the generated integer to a char.
import java.util.Random; public class RandomChar public static void main(String[] args) Random random = new Random(); char randomizedCharacter = (char) (random.nextInt(26) + 'a'); System.out.println("Generated Random Character: " + randomizedCharacter); > >
Generated Random Character: p
Generate Random Character From a String Using random.nextInt() and charAt()
In the next example, we will again use the Random class, and its nextInt() method but generate a random character from an already defined set of characters.
Below we can see that setOfCharacters is a string with several characters, including alphabets, numbers, and symbols. To generate a random character from this string, we will use the length of setOfCharacters as the argument of random.nextInt() . Once a random integer is generated, we use it to get a character at a random index or position using charAt() . It will return a random char from setOfCharacters .
import java.util.Random; public class RandomChar public static void main(String[] args) Random random = new Random(); String setOfCharacters = "abcdefghxyz1234567-/@"; int randomInt = random.nextInt(setOfCharacters.length()); char randomChar = setOfCharacters.charAt(randomInt); System.out.println("Random character from string: " + randomChar); > >
Random character from string: 4
Generate Random Character Using RandomStringUtils of Apache Commons
In the last example, we use a class RandomStringUtils from the Apache Commons library. RandomStringUtils class has a function randomAlphanumeric() to generate random alphanumeric strings. randomAlphanumeric(count) takes a single argument, that is the length of the randomized string that we want.
In the example below, we have passed only 1 to the randomAlphanumeric() method as we only want a single character. But this function returns the result as a string. This is why we have to convert it to a char . So, we use charAt() to get the character from the string.
import org.apache.commons.lang3.RandomStringUtils; public class RandomChar public static void main(String[] args) String randomizedString = RandomStringUtils.randomAlphanumeric(1); char randomizedCharacter = randomizedString.charAt(0); System.out.println("Generated Random Character: " + randomizedCharacter); > >
Generated Random Character: L
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
Related Article — Java Char
Copyright © 2023. All right reserved
Java generate random string
Method 1 : Using UUID
java.util.UUID class can be used to get a random string. Its static randomUUID method acts as a random alphanumeric generator and returns a String of 32 characters.
If you want a string of a fixed length or shorter than 32 characters, you can use substring method of java.lang.String .
Example,
import java.util.UUID; public class RandomStringGenerator < public static void main(String[] args) < String randomString = usingUUID(); System.out.println("Random string is: " + randomString); System.out.println("Random string of 8 characters is: " + randomString.substring(0, 8)); >static String usingUUID() < UUID randomUUID = UUID.randomUUID(); return randomUUID.toString().replaceAll("-", ""); >>
Note that the string generated by randomUUID method contains “–“. Above example removes those by replacing them with empty string.
Output of above program will be
Random string is: 923ed6ec4d04452eaf258ec8a4391a0f
Random string of 8 characters is: 923ed6ec
Method 2 : Using Math class
Following algorithm can be used to generate a random alphanumeric string of fixed length using this method.
- Initialize an empty string to hold the result.
- Create a combination of upper and lower case alphabets and numerals to create a super set of characters.
- Initiate a loop for with count equal to the length of random string required.
- In every iteration, generate a random number between 0 and the length of super set.
- Extract the character from the string in Step 2 at the index of number generated in Step 4 and add it to the string in Step 1.
After the loop completes, string in Step 1 will be a random string.
import java.util.Math; public class RandomStringGenerator < public static void main(String[] args) < String randomString = usingMath(); System.out.println("Random string is: " + randomString); >static String usingMath() < String alphabetsInUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String alphabetsInLowerCase = "abcdefghijklmnopqrstuvwxyz"; String numbers = "0123456789"; // create a super set of all characters String allCharacters = alphabetsInLowerCase + alphabetsInUpperCase + numbers; // initialize a string to hold result StringBuffer randomString = new StringBuffer(); // loop for 10 times for (int i = 0; i < 10; i++) < // generate a random number between 0 and length of all characters int randomIndex = (int)(Math.random() * allCharacters.length()); // retrieve character at index and add it to result randomString.append(allCharacters.charAt(randomIndex)); >return randomString.toString(); > >
Output of above program executed thrice is
Random string is: kqNG2SYHeF
Random string is: lCppqqUg8P
Random string is: GGiFiEP5Dz
This approach gives you more control over the characters that need to be included in the random string.
For example, if you do not want numbers, then remove them from the super set. If you want special characters, then add a set of special characters in the super set.
Method 3 : Using Random class
This method follows a similar approach as the above method in that a super set of all the characters is created, a random index is generated and character at that index is used to create the final string.
But this approach uses java.util.Random class to generate a random index. Example,
import java.util.Random; public class RandomStringGenerator < public static void main(String[] args) < String randomString = usingRandom(); System.out.println("Random string is: " + randomString); >static String usingRandom() < String alphabetsInUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String alphabetsInLowerCase = "abcdefghijklmnopqrstuvwxyz"; String numbers = "0123456789"; // create a super set of all characters String allCharacters = alphabetsInLowerCase + alphabetsInUpperCase + numbers; // initialize a string to hold result StringBuffer randomString = new StringBuffer(); // loop for 10 times for (int i = 0; i < 10; i++) < // generate a random number between 0 and length of all characters int randomIndex = random.nextInt(allCharacters.length()); // retrieve character at index and add it to result randomString.append(allCharacters.charAt(randomIndex)); >return randomString.toString(); > >
You can also use java.util.SecureRandom class to generate a random integer. It is a subclass of java.util.Random .
Output of three executions of above program is
Random string is: TycOBOxITs
Random string is: 7LLWVbg0ps
Random string is: p6VyqdO6bT
Method 4 : Using RandomStringUtils
Apache Commons Lang library has an org.apache.commons.lang.RandomStringUtils class with methods to generate random string of a fixed length.
It has methods that can generate a random string of only alphabets( randomAlphabetic ), numbers( randomNumeric ) or both( randomAlphanumeric ).
All these methods accept an integer argument which represents the length of the string that they will generate.
Below is an example.
import org.apache.commons.lang.RandomStringUtils; public class RandomStringGenerator < public static void main(String[] args) < // generate a random string of 10 alphabets String randomString = RandomStringUtils.randomAlphabetic(10); System.out.println("Random string of 10 alphabets: " + randomString); randomString = RandomStringUtils.randomNumeric(10); System.out.println("Random string of 10 numbers: " + randomString); randomString = RandomStringUtils.randomAlphanumeric(10); System.out.println("Random string of 10 alphanumeric characters: " + randomString); >>
Output of above program is
Random string of 10 alphabets: OEfadIYfFm
Random string of 10 numbers: 1639479195
Random string of 10 alphanumeric characters: wTQRMXrNY9
This class also has a method random() that takes an integer which is the length of the string to be generated and a char array. Random string generated consists of only characters from this array.
Apache Commons Lang can be included into your project by adding the below dependency as per the build tool.
org.apache.commons commons-lang3 3.9
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
Method 5 : Using java 8 Stream
With Java 8 streams , we can generate a random alphanumeric string of fixed length.
The idea is to generate a stream of random numbers between ASCII values of 0-9, a-z and A-Z, convert each integer generated into corresponding character and append this character to a StringBuffer.
Example code is given below
import java.util.Random; public class RandomStringGenerator < public static void main(String[] args) throws IOException < Random r = new Random(); String s = r.ints(48, 123) .filter(num ->(num < 58 || num >64) && (num < 91 || num >96)) .limit(10) .mapToObj(c -> (char) c).collect(StringBuffer::new, StringBuffer::append, StringBuffer::append) .toString(); System.out.println('Random alphanumeric string is: " + s); > >
java.util.Random class has a new method ints() added in java 8.
ints() takes two integer arguments and generates a stream of integers between those two integers with start inclusive and end exclusive.
This stream is filtered with filter() method to include ASCII values of only 0-9, a-z and A-Z.
If you want other characters as well, then filter() is not required.
limit() is required to generate a random string of 10 characters. Without limit() , the stream will keep on generating integers infinitely.
mapToObj() converts integer value to corresponding character.
Both filter() and mapToObj() accept a functional interface as argument and so we can pass a Lambda expression .
Finally, collect() is used to collect the values generated by the stream into a StringBuffer using its append() method.
This StringBuffer is converted to a string with toString() method.
Range of integers provided to ints() is chosen according to ASCII values of numbers and alphabets. You can choose these according to the characters that need to be included in the string to generate.
Multiple executions of this program generate following output
Random alphanumeric string is: tCh5OTWY4v
Random alphanumeric string is: pHLjsd0ts4
Random alphanumeric string is: L82EvKMfsm
That is all on different ways to generate a random string in java. Hope the article was helpful !!