Is it possible to generate a random character in Java?

Does Java have any functions for generating random characters or strings? Or just need to pick a random integer and convert that integer ascii code to a character?

+50
java random
Apr 13 '10 at 3:45
source share
17 answers

There are many ways to do this, but yes, this involves creating a random int (using, for example, java.util.Random.nextInt ), and then using this to map to char . If you have a specific alphabet, then something like this is great:

  import java.util.Random; //... Random r = new Random(); String alphabet = "123xyz"; for (int i = 0; i < 50; i++) { System.out.println(alphabet.charAt(r.nextInt(alphabet.length()))); } // prints 50 random characters from alphabet 



Note that java.util.Random is actually a pseudo-random number generator based on a rather weak linear congruent formula . You mentioned the need for cryptography; you can explore the use of a stronger cryptographically secure pseudo random number generator in this case (e.g. java.security.SecureRandom ).

+73
Apr 13 '10 at 4:32
source share

To create a random char in az:

 Random r = new Random(); char c = (char)(r.nextInt(26) + 'a'); 
+112
Apr 13 '10 at 7:45
source share

You can also use RandomStringUtils from the Apache Commons project:

 RandomStringUtils.randomAlphabetic(stringLength); 
+65
Jan 25 2018-12-17T00:
source share
 private static char rndChar () { int rnd = (int) (Math.random() * 52); // or use Random or whatever char base = (rnd < 26) ? 'A' : 'a'; return (char) (base + rnd % 26); } 

Generates values ​​in the ranges az, AZ.

+8
Apr 13 2018-10-10T00:
source share

According to 97, the ascii value is small "a".

 public static char randomSeriesForThreeCharacter() { Random r = new Random(); char random_3_Char = (char) (97 + r.nextInt(3)); return random_3_Char; } 

in the above 3 numbers for a, b, c or d, and if u wants all characters like az, you replace 3 numbers with 25.

+3
Dec 24 '12 at 12:25
source share
 String abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char letter = abc.charAt(rd.nextInt(abc.length())); 

This also works.

+3
Dec 29 '13 at 15:32
source share

You can use generators from a validation framework based on the Quickcheck specification .

To create a random string, use the anyString method.

 String x = anyString(); 

You can create strings from a more limited character set or with minimum / maximum size restrictions.

Usually you run tests with several values:

 @Test public void myTest() { for (List<Integer> any : someLists(integers())) { //A test executed with integer lists } } 
+1
Apr 13 '10 at 7:14
source share

using dollar :

 Iterable<Character> chars = $('a', 'z'); // 'a', 'b', c, d .. z 

given chars you can create a "shuffled" range of characters:

 Iterable<Character> shuffledChars = $('a', 'z').shuffle(); 

then taking the first characters of n , you get a random string of length n . The final code is simple:

 public String randomString(int n) { return $('a', 'z').shuffle().slice(n).toString(); } 

NB : condition n > 0 crossed out slice

EDIT

as Steve correctly pointed out, randomString uses no more than once each letter. As a workaround, you can repeat the alphabet m times before calling shuffle :

 public String randomStringWithRepetitions(int n) { return $('a', 'z').repeat(10).shuffle().slice(n).toString(); } 

or just specify your alphabet as String :

 public String randomStringFromAlphabet(String alphabet, int n) { return $(alphabet).shuffle().slice(n).toString(); } String s = randomStringFromAlphabet("00001111", 4); 
+1
Apr 13 2018-10-10T00:
source share

Try it.

 public static String generateCode() { String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String fullalphabet = alphabet + alphabet.toLowerCase() + "123456789"; Random random = new Random(); char code = fullalphabet.charAt(random.nextInt(9)); return Character.toString(code); } 
+1
Dec 03 '17 at 2:42 on
source share

You have it. Just create random ASCII codes yourself. Why do you need this?

0
Apr 13 2018-10-10T00:
source share

Take a look at the Java Randomizer class. I think you can randomize a character using the randomize (char []) method.

0
Apr 13 '10 at 4:00
source share

Polygenelubricants answer is also a good solution if you want to generate only hexadecimal values:

 /** A list of all valid hexadecimal characters. */ private static char[] HEX_VALUES = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'A', 'B', 'C', 'D', 'E', 'F' }; /** Random number generator to be used to create random chars. */ private static Random RANDOM = new SecureRandom(); /** * Creates a number of random hexadecimal characters. * * @param nValues the amount of characters to generate * * @return an array containing <code>nValues</code> hex chars */ public static char[] createRandomHexValues(int nValues) { char[] ret = new char[nValues]; for (int i = 0; i < nValues; i++) { ret[i] = HEX_VALUES[RANDOM.nextInt(HEX_VALUES.length)]; } return ret; } 
0
Dec 03 '13 at 7:57
source share

My suggestion is to generate a random string with a mixed case like: "DthJwMvsTyu" .
This algorithm is based on ASCII codes of letters, when its codes az (from 97 to 122) and AZ (from 65 to 90) differ in the 5th bit (2 ^ 5 or 1 << 5 or 32).

random.nextInt(2) : the result is 0 or 1.

random.nextInt(2) << 5 : the result is 0 or 32.

The top A is 65, and the bottom a is 97. The difference is only on the 5th bit (32), so to generate a random character we make the binary code OR '|' random charCaseBit (0 or 32) and random code from A to Z (from 65 to 90).

 public String fastestRandomStringWithMixedCase(int length) { Random random = new Random(); final int alphabetLength = 'Z' - 'A' + 1; StringBuilder result = new StringBuilder(length); while (result.length() < length) { final char charCaseBit = (char) (random.nextInt(2) << 5); result.append((char) (charCaseBit | ('A' + random.nextInt(alphabetLength)))); } return result.toString(); } 
0
Dec 28 '17 at 10:02
source share

Here is the code for generating a random alphanumeric code. First you must declare a string of allowed characters that you want to include in a random number, and also determine the maximum length of the string.

  SecureRandom secureRandom = new SecureRandom(); String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"; StringBuilder generatedString= new StringBuilder(); for (int i = 0; i < MAXIMUM_LENGTH; i++) { int randonSequence = secureRandom .nextInt(CHARACTERS.length()); generatedString.append(CHARACTERS.charAt(randonSequence)); } 

Use toString () method to get String from StringBuilder

0
Dec 07 '18 at 7:55
source share

This is a simple but useful discovery. It defines a class called RandomCharacter with 5 overloaded methods to randomly obtain a specific type of character. You can use these methods in your future projects.

  public class RandomCharacter { /** Generate a random character between ch1 and ch2 */ public static char getRandomCharacter(char ch1, char ch2) { return (char) (ch1 + Math.random() * (ch2 - ch1 + 1)); } /** Generate a random lowercase letter */ public static char getRandomLowerCaseLetter() { return getRandomCharacter('a', 'z'); } /** Generate a random uppercase letter */ public static char getRandomUpperCaseLetter() { return getRandomCharacter('A', 'Z'); } /** Generate a random digit character */ public static char getRandomDigitCharacter() { return getRandomCharacter('0', '9'); } /** Generate a random character */ public static char getRandomCharacter() { return getRandomCharacter('\u0000', '\uFFFF'); } } 

To demonstrate how this works, let's take a look at the next test program, which displays 175 random lowercase letters.

 public class TestRandomCharacter { /** Main method */ public static void main(String[] args) { final int NUMBER_OF_CHARS = 175; final int CHARS_PER_LINE = 25; // Print random characters between 'a' and 'z', 25 chars per line for (int i = 0; i < NUMBER_OF_CHARS; i++) { char ch = RandomCharacter.getRandomLowerCaseLetter(); if ((i + 1) % CHARS_PER_LINE == 0) System.out.println(ch); else System.out.print(ch); } } } 

and conclusion:

enter image description here

if you run again:

enter image description here

I commend Yu. Daniel Liang for his book, Introduction to Java Programming, Full Version, 10th edition, where I introduced this knowledge.

0
Apr 14 '19 at 7:02
source share

If you don't mind adding a new library to your code, you can generate characters using MockNeat (disclaimer: I am one of the authors).

 MockNeat mock = MockNeat.threadLocal(); Character chr = mock.chars().val(); Character lowerLetter = mock.chars().lowerLetters().val(); Character upperLetter = mock.chars().upperLetters().val(); Character digit = mock.chars().digits().val(); Character hex = mock.chars().hex().val(); 
-one
Mar 05 '17 at 19:34
source share
  Random randomGenerator = new Random(); int i = randomGenerator.nextInt(256); System.out.println((char)i); 

Take care of what you want, considering that you count "0", "1", "2" .. as symbols.

-2
Apr 13 '10 at 4:52
source share



All Articles