
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
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
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
Advertisements