Random number generation is one of the most common programming tasks. We will look at how to use java random number between 1 and 10. We will look at three Java classes or packages that can generate random numbers between 1 and 10 and determine which one is the best to use.

We frequently need to generate random numbers in programming and software development. Fortunately, generating random numbers in Java is very simple because the Java API, along with more loved features like Strings in Switch and ARM blocks, provides good support for random numbers through the java class. .util.random, the Math.random() utility, and most recently the ThreadLocalRandom class in Java 7. Even if Java’s random() method seems to be the most practical method for generating randoms, it just generates random double numbers; however, using Random you can generate pseudo-random integers and floating point values.

Using Random.nextInt() in java random number from 1 to 10

Java.util.Random is a package that comes with Java, and we can use it to generate a random number between a range. The range in our situation is 1 to 10. This package contains a class called Random that enables us to produce many sorts of numbers, including int and float.

For example:

import java.util.Random;

public class Main {
    public static void main(String[] args) {
int min = 1;
int max = 10;

Random random = new Random();

int value = random.nextInt(max + min) + min;
System.out.println(value);
    }
}

Output:

 6

To pageant that the above technique works and generates random numbers every time, we can use a loop to generate a new random number until its end. As we do not have a large range of numbers, the random numbers may be repeated.

import java.util.Random;

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

        Random random = new Random();

        for(int i = 1; i <=10; i++) {
            int value = random.nextInt((10 - 1) + 1) + 1;
            System.out.println(value);
        }
    }

Output:

10
7
2
9
2
7
6
4
9

Math.random() to Generate Random Numbers Between 1 to 10

double d = Math.random();

Calling Math.random() is one of the earliest ways to create a random double number (it has been there since Java 1.0). The random() technique is employed. It gives back a float value at random. Because of this, we must cast it as an integer.

public class Main {
    public static void main(String[] args) {
int min = 1;
int max = 10;
for(int i = min; i <=max; i++) {
int getRandomValue = (int) (Math.random()*(max-min)) + min;
System.out.println(getRandomValue);
  
}
    }

Output:

5
5
2
1
6
9
3
6
5
7

ThreadLocalRandom.current.nextInt() to Generate Random Numbers Between 1 to 10

The class java.util.concurrent.ThreadLocalRandom was first introduced in Java 7. Each thread has access to a separate random number generator using the static function ThreadLocalRandom.current(). This prevents thread contention from happening and eliminates the synchronization overhead mentioned in the preceding section.

The ThreadLocalRandom object is returned by ThreadLocalRandom.current(); this object derives from Random and offers the same methods, such as nextInt():

Random random = ThreadLocalRandom.current();
int randomNumber = random.nextInt();
import java.util.concurrent.ThreadLocalRandom;

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

        int min = 1;
        int max = 10;
      
        for(int i = 1; i <=10; i++) {
        int getRandomValue = ThreadLocalRandom.current().nextInt(min, max) + min;

        System.out.println(getRandomValue);
        }
    }

}

Output:

3
4
5
8
6
2
6
10
6
2

How to Generate a Random String in Java

Sometimes we need a random string – that is, a string filled with a random or specific number of random characters. We can do this by progressively adding random lowercase characters to a StringBuilder.

public static String randomLowerCaseString(int length) {
StringBuilder sb = new StringBuilder();
Random r = ThreadLocalRandom.current();
for (int i = 0; i < length; i++) {
char c = (char) ('a' + r.nextInt(26));
sb.append(c);
}
return sb.toString();
}

If we wish to expand the character range to include things like upper case letters, digits, and the space character, it becomes a little more challenging. Then we have to define an alphabet and pick a random character from it:

private static final String ALPHANUMERIC_WITH_SPACE_ALPHABET =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

public static String randomAlphanumericalWithSpaceString(int length) {
return randomString(length, ALPHANUMERIC_WITH_SPACE_ALPHABET);
}

public static String randomString(int length, String alphabet) {
StringBuilder sb = new StringBuilder();
Random r = ThreadLocalRandom.current();
for (int i = 0; i < length; i++) {
int pos = r.nextInt(alphabet.length());
char c = alphabet.charAt(pos);
sb.append(c);
}
return sb.toString();
}

Since Java 8, uses streams we can also implement RandomString() method:

public static String randomStringWithStream(int length, String alphabet) {
return ThreadLocalRandom.current()
.ints(length, 0, alphabet.length())
.map(alphabet::charAt)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
}

Java SecureRandom Class

This predictability is unacceptable for some needs (like cryptography). We require a “safe” random number generator in such circumstances. The class java.security.SecureRandom has been available since Java 1.1. It generates “cryptographically strong” random numbers as defined in RFC 1750 “Randomness Recommendations for Security”.

“Cryptographically strong” can be implemented in one of the following two ways (or a combination of both):

  • A deterministic sequence similar to Random but with far more “noise” (the bits from the seed not included in the produced random number), making it very difficult to reverse-engineer the seed from a particular sequence with current hardware.
  • Truly random numbers are generated by special hardware that measures, for example, radioactive decay processes.

SecureRandom’s constructor offers a default implementation. Because SecureRandom derives from Random, it offers the same techniques. The example that follows demonstrates how to create a safe random floating-point integer:

SecureRandom secureRandom = new SecureRandom(); 
double strongRandomNumber = secureRandom.nextDouble();

Conclusion

There are many ways to generate random numbers in Java, for example, utility function Math.random(), class java.util.random… Each has its own pros and cons but if your requirement is simple, you can generate random numbers in Java using Math.random() method. In this Java tutorial, we have shown ways of generating random strings in Java, and examples of generating random numbers in a range. Hope to help you make the most suitable choices and get the most useful information for you.

ONEXT DIGITAL has a team of experts and experienced developers who use cutting-edge technology to provide high-quality Mobile Application Development services. If you have not found the answer for yourself, do not hesitate to contact us, Onext Digital will provide the best solutions for you.

>> Read more

Java Stop Program: How To Do It