Java Program to get random letters

Java 8Object Oriented ProgrammingProgramming

To generate random letters, set letters as a strong and use the toCharArray() to convert it into character array −

"abcdefghijklmnopqrstuvwxyz".toCharArray()

Now, use the nextInt() to generate random letters from it −

System.out.println("" + "abcdefghijklmnopqrstuvwxyz".toCharArray()[randNum.nextInt("abcdefghijklmnopqrstuvwxyz".toCharArray().length)]);

Above, initially we have created a Random object −

static Random randNum = new Random();

Example

 Live Demo

import java.util.Random;
public class Demo {
   static Random randNum = new Random();
   public static void main(String args[]) {
      System.out.println("Lowercase random letters...");
      for (int i = 0; i < 5; i++) {
         System.out.println("" + "abcdefghijklmnopqrstuvwxyz".toCharArray()[randNum.nextInt("abcdefghijklmnopqrstuvwxyz".toCharArray().length)]);
      }
      System.out.println("Uppercase random letters...");
      for (int i = 0; i < 5; i++) {
         System.out.println("" + "ABCDEFGHIJKLMNOPQRSTUVWZYZ".toCharArray()[randNum.nextInt("ABCDEFGHIJKLMNOPQRSTUVWZYZ".toCharArray().length)]);
      }
   }
}

Output

Lowercase random letters...
d
l
h
j
s
Uppercase random letters...
B
K
I
Z
N
raja
Published on 24-Apr-2019 10:59:35
Advertisements