Java math random string

Java Program to Create random strings

To understand this example, you should have the knowledge of the following Java programming topics:

Example 1: Java program to generate a random string

import java.util.Random; class Main < public static void main(String[] args) < // create a string of all characters String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // create random string builder StringBuilder sb = new StringBuilder(); // create an object of Random class Random random = new Random(); // specify length of random string int length = 7; for(int i = 0; i < length; i++) < // generate random index number int index = random.nextInt(alphabet.length()); // get character specified by index // from the string char randomChar = alphabet.charAt(index); // append the character to string builder sb.append(randomChar); >String randomString = sb.toString(); System.out.println("Random String is: " + randomString); > >

In the above example, we have first created a string containing all the alphabets. Next, we have generated a random index number using the nextInt() method of the Random class.

Using the random index number, we have generated the random character from the string alphabet. We then used the StringBuilder class to append all the characters together.

If we want to change the random string into lower case, we can use the toLowerCase() method of the String .

Читайте также:  Распознавание лиц python facenet

Note: The output will be different every time you run the program.

Example 2: Java Program to generate a random alphanumeric string

import java.util.Random; class Main < public static void main(String[] args) < // create a string of uppercase and lowercase characters and numbers String upperAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String lowerAlphabet = "abcdefghijklmnopqrstuvwxyz"; String numbers = "0123456789"; // combine all strings String alphaNumeric = upperAlphabet + lowerAlphabet + numbers; // create random string builder StringBuilder sb = new StringBuilder(); // create an object of Random class Random random = new Random(); // specify length of random string int length = 10; for(int i = 0; i < length; i++) < // generate random index number int index = random.nextInt(alphaNumeric.length()); // get character specified by index // from the string char randomChar = alphaNumeric.charAt(index); // append the character to string builder sb.append(randomChar); >String randomString = sb.toString(); System.out.println("Random String is: " + randomString); > >
Random Alphanumeric String is: pxg1Uzz9Ju

Here, we have created a string that contains numbers from 0 to 9 and the alphabets in uppercase and lowercase.

From the string, we have randomly generated an alphanumeric string of length 10.

Источник

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.

  1. Initialize an empty string to hold the result.
  2. Create a combination of upper and lower case alphabets and numerals to create a super set of characters.
  3. Initiate a loop for with count equal to the length of random string required.
  4. In every iteration, generate a random number between 0 and the length of super set.
  5. 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 !!

Источник

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.

Источник

Оцените статью