Generate a random string in Java


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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

804 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements