• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1512
  • Last Modified:

How to generate random characters and letters in JAVA


I have the following function

which generates alphabetic letter + dot so output looks like this B.

I need it to generate 5 random letters + 2 random numbers + dot

how can i achieve this without altering the code too much?
private String fnam1 = (char)((int)'A'+Math.random()*((int)'Z'-(int)'A'+1))+ ".";

Open in new window

1 Solution
You need to get random characters five times and get random number of 2 digit length and then the 5 random characters with 2 digit number and dot.
if the the number of character and number and the order is not mandatory, you can try below one

UUID uuid = UUID.randomUUID();
String myRandom = uuid.toString();
Try this:

            Random rnd = new Random();
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < 8; i++) {
                  buffer.append(Character.toString(i < 5 ? ((char) ('A' + rnd.nextInt('Z' - 'A' + 1))) : ((i < 7) ? (char) ('0' + rnd.nextInt(9)) : '.')));

            String fnam1 = buffer.toString();
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now