Java/J2EE and SOA (349 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (5 Blogs)
  • Java/J2EE and SOA (346 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

How To Deal With Random Number and String Generator in Java?

Last updated on Jun 17,2021 23.1K Views

28 / 29 Blog from Java Programs

This article will introduce you to Random Number And String Generator In Java and follow it up with a programmatic demonstration. Following pointers will be covered in this article,

There are three methods to generate random numbers in java using built-in methods and classes.

  • Java.util.Random class
  • Math.random method
  • ThreadLocalRandom class

So let us get started article on random number and string generator in Java,

Java.util.Random

First of all , we need to create an instance of this class in the program and then invoke the various built-in methods such as nextInt(), nextDouble() etc using the instance we created.
Random numbers of type integers, float, double, long, booleans can be created using this class.
Arguments can be passed to the methods for defining the upper bound till which the number is to generate. For Example, nextInt(4) will generate numbers in the range 0 to 3 (both inclusive).

Example1:

// A Java program to show random number generation
// using java.util.Random;
import java.util.Random;
public class Main{
public static void main(String args[])
{
// creating an instance of Random class
Random rand = new Random();
// Generating random integers in range 0 to 99
int int1 = rand.nextInt(100);
int int2 = rand.nextInt(100);
// Printing random integers
System.out.println("Random Integers:> "+int1);
System.out.println("Random Integers:> "+int2);
// Generating Random doubles
double dub1 = rand.nextDouble();
double dub2 = rand.nextDouble();
// Printing random doubles
System.out.println("Random Doubles:> "+dub1);
System.out.println("Random Doubles:> "+dub2);
}
}

Output:

Output-random number and string generator in java- Edureka

Example:

// Java program to show random number generation
// using java.util.Random;
import java.util.Random;
public class Main{
public static void main(String args[])
{
// creating an instance of Random class
Random rand = new Random();
// Generating random integers in range 0 to 9
int int1 = rand.nextInt(10);
// Printing random integer
System.out.println("Random Integer:> "+int1);
}
}

Output:

Output-random number and string generator in java- Edureka

Moving on with this article

Math.random()

The class named as Math comprises of various methods for performing a number of different numeric operations which includes logarithms , solving exponentiation etc. Among these operations there is random() which is used to generate random numbers of type doubles between the range of 0.0 and 1.0. This method returns a double value which is either greater than or equal to 0.0 and less than or equal to 1.0 along with a positive sign. The values which are being returned by random() are chosen randomly by the machine.

Example 1:

// A Java program to demonstrate working of
// Math.random() to generate random numbers
import java.util.*;
public class Main
{
public static void main(String args[])
{
// Generating random value of data type double
System.out.println("Random value: " + Math.random());
}
}

Output:

Output-random number and string generator in java- Edureka

To check the randomness lets execute the program once more.

// A Java program to demonstrate working of
// Math.random() to generate random numbers
import java.util.*;
public class Main
{
public static void main(String args[])
{
// Generating random value of data type double
System.out.println("Another Random value: " + Math.random());
}
}

Output:

Output-random number and string generator in java- Edureka

Moving on with this article on random number and string generator in java

Java.util.concurrent.ThreadLocalRandom class

This class was introduced in java 1.7 for generating random numbers of data type integers, doubles, Booleans etc.
Example 1:

// A Java program to demonstrate working of ThreadLocalRandom
// for generating random numbers.
import java.util.concurrent.ThreadLocalRandom;
public class Main
{
public static void main(String args[])
{
// Generating random integers in range 0 to 99
int int2 = ThreadLocalRandom.current().nextInt();
// Printing random integer
System.out.println("Random Integers: " + int2);
// Generating Random doubles
double dub1 = ThreadLocalRandom.current().nextDouble();
double dub2 = ThreadLocalRandom.current().nextDouble();
// Printing random doubles
System.out.println("Random Doubles: " + dub1);
System.out.println("Random Doubles: " + dub2);
}
}

Output:

Output-random number and string generator in java- Edureka

Example 2:

// Java program to demonstrate working of ThreadLocalRandom
// to generate random numbers.
import java.util.concurrent.ThreadLocalRandom;
public class Main
{
public static void main(String args[])
{
// Generating random booleans
boolean bool1 = ThreadLocalRandom.current().nextBoolean();
boolean bool2 = ThreadLocalRandom.current().nextBoolean();
// Print random Booleans
System.out.println("Random Booleans: " + bool1);
System.out.println("Random Booleans: " + bool2);
}
}

Output:

Output-Edureka

Moving on with this article on random number and string generator in java

Generating random String in Java

We can generate random alphanumeric string by using following methods:

Moving on with this article on random number and string generator in java

Using Math.random()

Below is an Example to understand the concept in a better way.

// A Java program generating a random AlphaNumeric String
// using Math.random() method
public class Main {
// define a function to generate a random string of length n
static String RequiredString(int n)
{
// chose a Character random from this String
String AlphaNumericString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "0123456789"
+ "abcdefghijklmnopqrstuvxyz";
// create StringBuffer size of AlphaNumericString
StringBuilder s = new StringBuilder(n);
int y;
for ( y = 0; y < n; y++) {
// generating a random number
int index
= (int)(AlphaNumericString.length()
* Math.random());
// add Character one by one in end of s
s.append(AlphaNumericString
.charAt(index));
}
return s.toString();
}
public static void main(String[] args)
{
// Get the size n
int n = 20;
// Get and display the alphanumeric string
System.out.println(Main.RequiredString(n));
}
}

Output:

Output-Edureka

Moving on with this article on random number and string generator in java

Using CharSet

We have to use a different package here i.e. java.nio.charset package.
Below is an illustrated Example.

// A Java program generate a random AlphaNumeric String
// using CharSet
import java.util.*;
import java.nio.charset.*;
class Main {
static String RequiredString(int n)
{
// length declaration
byte[] array = new byte[256];
new Random().nextBytes(array);
String randomString
= new String(array, Charset.forName("UTF-8"));
// Creating a StringBuffer
StringBuffer ra = new StringBuffer();
// Appending first 20 alphanumeric characters
for (int i = 0; i < randomString.length(); i++) { char ch = randomString.charAt(i); if (((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9')) && (n > 0)) {
ra.append(ch);
n--;
}
}
// returning the resultant string
return ra.toString();
}
public static void main(String[] args)
{
// size of random alphanumeric string
int n = 10;
// Get and display the alphanumeric string
System.out.println(RequiredString(n));
}
}

Output:

Output-Edureka

Moving on with this article on random number and string generator in java

Using Regular Expressions

Implementation is as following Example.

// A Java program generate a random AlphaNumeric String
// using Regular Expressions method
import java.util.*;
import java.nio.charset.*;
class Main {
static String getAlphaNumericString(int n)
{
// length declaration
byte[] array = new byte[256];
new Random().nextBytes(array);
String randomString
= new String(array, Charset.forName("UTF-8"));
// Creating a StringBuffer
StringBuffer ra = new StringBuffer();
// remove all spacial char
String AlphaNumericString
= randomString
.replaceAll("[^A-Za-z0-9]", "");
// Append first 20 alphanumeric characters
// from the generated random String into the result
for (int k = 0; k < AlphaNumericString.length(); k++) {
if (Character.isLetter(AlphaNumericString.charAt(k))
&& (n > 0)
|| Character.isDigit(AlphaNumericString.charAt(k))
&& (n > 0)) {
ra.append(AlphaNumericString.charAt(k));
n--;
}
}
// returning the resultant string
return ra.toString();
}
public static void main(String[] args)
{
// size of random alphanumeric string
int n = 15;
// Get and display the alphanumeric string
System.out.println(getAlphaNumericString(n));
}
}

Output:

Output-Edureka

Thus we have come to an end of this article. If you wish to learn more, check out the Java Certification Course by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 7th December,2024

7th December

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How To Deal With Random Number and String Generator in Java?

edureka.co