Write a Java Program to Create random strings

Java Program to Create random strings

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Create random strings
Java Program to Create random strings

Write a Java Program to Create random strings

PROGRAM: Java Program to Create random strings

/*Java Program to Create random strings*/

1: Java program to generate a random string

import java.util.Random;

class Main {
public static void main(String[] args) {

// create a string of all characters
String alphabet = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;

// create random string builder
StringBuilder sb = new StringBuilder();

// create an object of Random class
Random random = new Random();

// specify length of random string
int length = 7;

for(int i = 0; i < length; i++) {

// generate random index number
int index = random.nextInt(alphabet.length());

// get character specified by index
// from the string
char randomChar = alphabet.charAt(index);

// append the character to string builder
sb.append(randomChar);
}

String randomString = sb.toString();
System.out.println(“Random String is: ” + randomString);

}
}

2: Java Program to generate a random alphanumeric string

import java.util.Random;

class Main {
public static void main(String[] args) {

// create a string of uppercase and lowercase characters and numbers
String upperAlphabet = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
String lowerAlphabet = “abcdefghijklmnopqrstuvwxyz”;
String numbers = “0123456789”;

// combine all strings
String alphaNumeric = upperAlphabet + lowerAlphabet + numbers;

// create random string builder
StringBuilder sb = new StringBuilder();

// create an object of Random class
Random random = new Random();

// specify length of random string
int length = 10;

for(int i = 0; i < length; i++) {

// generate random index number
int index = random.nextInt(alphaNumeric.length());

// get character specified by index
// from the string
char randomChar = alphaNumeric.charAt(index);

// append the character to string builder
sb.append(randomChar);
}

String randomString = sb.toString();
System.out.println(“Random String is: ” + randomString);

}
}

Leave a Reply

Your email address will not be published. Required fields are marked *