Java Program to generate random numbers string


At first, create a character array −

static char num[] = { '0', '1', '2', '3', '4', '5' };

Now, let’s say you want to a string with length. Create a StringBuilder and use append() to create random numbers string out of it −

int len = 5;
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < len; i++) {
   strBuilder.append(randomNum());
}

Above, we created a randomNum() function that returns the random numbers string −

public static char randomNum() {
   return num[(int) Math.floor(Math.random() * 5)];
}

Example

 Live Demo

public class Demo {
   static char num[] = { '0', '1', '2', '3', '4', '5' };
   public static char randomNum() {
      return num[(int) Math.floor(Math.random() * 5)];
   }
   public static void main(String[] args) {
      int len = 5;
      StringBuilder strBuilder = new StringBuilder();
      for (int i = 0; i < len; i++) {
         strBuilder.append(randomNum());
      }
      System.out.println("Random numbers string = "+strBuilder.toString());
   }
}

Output

Random numbers string = 23024

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

361 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements