
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Random Letters in Java
In this article, we will learn to write a program in Java to get the random letters in both lowercase and uppercase. We will be using Random class from java.util package.The program will first create random lowercase letters by selecting them from the alphabet, and then it will generate random uppercase letters in a similar way.
Problem Statement
Write a program in Java to get the random letters both uppercase and lower case. Below is the demostration ?
Output
Lowercase random letters...
d
l
h
j
s
Uppercase random letters...
B
K
I
Z
N
Step to get random letters
Following are the steps to get the random letter using Java ?
- Start by importing the Random class from java.util.
- Initialize Random object for this we will create a static Random object to generate random numbers.
- Generate lowercase letters by using a for loop to generate 5 random lowercase letters from the alphabet.
- Generate uppercase letters by using another loop to generate 5 random uppercase letters from the alphabet.
- Print the generated random letters.
Java program to get random letters
Below is the Java to get random letters using Random class ?
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
Code Explanation
This Java program generates random lowercase and uppercase letters using the Random class. First, the program creates a Random object, randNum, to generate random numbers. The lowercase and uppercase alphabets are represented as strings, which are then converted into character arrays using the toCharArray() method. Two for loops are used, one for lowercase letters and the other for uppercase letters. Each loop iterates 5 times to generate and print 5 random letters.
The nextInt() method of the Random class is used to randomly select an index from the character arrays, and the corresponding character is printed.