Generate a random string in Java

Java 8Object Oriented ProgrammingProgramming

Let us first declare a string array and initialize −

String[] strArr = { "P", "Q", "R", "S","T", "U", "V", "W" };

Now, create a Random object −

Random rand = new Random();

Generate random string −

int res = rand.nextInt(strArr.length);

Example

 Live Demo

import java.util.Random;
public class Demo {
   public static void main(String[] args) {
      String[] strArr = { "P", "Q", "R", "S","T", "U", "V", "W" };
      Random rand = new Random();
      int res = rand.nextInt(strArr.length);
      System.out.println("Displaying a random string = " + strArr[res]);
   }
}

Output

Displaying a random string = R

Let us run it again to get distinct random string −

Displaying a random string = Q
raja
Published on 23-Apr-2019 09:10:30
Advertisements