Random – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Sat, 25 Nov 2023 08:32:56 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Random – Java2Blog https://java2blog.com 32 32 Fill Array With Random Numbers in Java https://java2blog.com/fill-array-with-random-numbers-java/?utm_source=rss&utm_medium=rss&utm_campaign=fill-array-with-random-numbers-java https://java2blog.com/fill-array-with-random-numbers-java/#respond Wed, 18 May 2022 08:35:26 +0000 https://java2blog.com/?p=19612 The arrays are a commonly used data structure that stores the data in contiguous memory. In this article, you will understand different methods to fill the array with random numbers in Java.

We will generate the random numbers using different library methods such as the Java Utility library’s Random class, the Java’s Math class, and the Apache Commons library.

Fill the Array With Random Numbers in Java With the Random Class

The Random class in Java’s Utility library provides a bunch of methods that can generate random numbers.

Different methods can generate random numbers with different data types. If you want to generate random numbers within a range, you can use different polymorphic forms.

However, in this article, we will fill an integer array with the numbers within the range of the integer data type. Therefore, we will not put any restrictions on the random numbers.

Fill the Array With Random Numbers Using the nextInt() Method

The nextInt() method in the Random class returns a pseudo-random integer number within the range of the int data type. The numbers are generated with a nearly uniform distribution.

The nextInt() method is defined in the Random class as given below.

public int nextInt()

To fill the array with random numbers with the nextInt() method,

  • Declare and instantiate an integer array of any size.
  • Declare and instantiate an object of the Random class.
  • Iterate the array and invoke the nextInt() method.
    • Assign the value returned to the current array position.

Let us see the code.

package java2blog;

import java.util.Random;

public class FillArrayExample {

    public static void main(String[] args) 
    {
        int [] rArr = new int[6];

        Random rClass = new Random();

        for(int i=0;i

Output:

Randomly filled array elements are:
384255672 -174688078 483929535 731995201 254320427 1094589344

Note that there are very large numbers as well as negative numbers in the array. If you want to produce numbers within a range you can check other polymorphic forms of the nextInt() method and other methods here.

Fill the Array With Random Numbers Using the ints() Method

Unlike the nextInt() method that produces a single number at a time, the ints() method produces a stream of pseudo-random numbers. The numbers are uniformly distributed.

The ints() method is defined in the random class as given below.

public IntStream ints()

Note that the method returns an IntStream object rather than an integer.

You can fill the array using this method by following the given steps.

  • Declare and instantiate an integer array of any size.
  • Declare and instantiate an object of the Random class.
  • Invoke the ints() method using the Random class instance, it will return an IntStream class object.
    • Invoke the limit() method of the IntStream class to extract the numbers equal to the size of the array from the infinite stream.
    • Invoke the toArray() method to convert the stream to the array.

Let us see the code.

package java2blog;

import java.util.Random;

public class FillArrayExample {

    public static void main(String[] args) 
    {
        int [] rArr = new int[6];

        Random rClass = new Random();

        rArr = rClass.ints().limit(rArr.length).toArray();

        System.out.println("Randomly filled array elements are:");
        for(int i=0;i

Output:

Randomly filled array elements are:
2062421650 -2049005340 -1399535828 -425229654 190823518 55983318

You can check the other polymorphs of the ints() method here.

Fill the Array With Random Numbers in Java Using the Apache Commons Library

The Apache Commons library is a third-party open-source Java library. It has the RandomUtils class that you can use to produce pseudo-random numbers.
You need to add below dependency to get Apache commons jar in pom.xml.

<dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.9</version>
</dependency>

Different methods can be used to generate numbers of different data types. You can use the nextInt() method to produce the random integer numbers.

The definition of the nextInt() method of Apache Commons library is given below.

public static int nextInt()

The method returns a positive integer number including zero within the range of int data type.

This method works similar to the Random class’ nextInt() method except that you do not need to instantiate the class object. It is a static method so it can be called using the class name.

Let us see the code.

package java2blog;

import org.apache.commons.lang3.RandomUtils;

public class FillArrayExample {

    public static void main(String[] args) 
    {
        int [] rArr = new int[6];

        for(int i=0;i

Output:

Randomly filled array elements are:
1653009679 1873237419 1198525296 1224407261 1608351756 612826226

For other polymorphic forms of the nextInt() method that can produce numbers within a given range and other methods to produce random numbers, you can visit this page.

Fill the Array With Random Numbers in Java Using the Java Math Class

The Java Math class has a random() method that returns a pseudo-random double number between 0.0 (inclusive) to 1.0 (exclusive).

The random method is defined in the Math class as given below.

public static double random()

You can use the random() method to populate your array with random numbers. However, if you want integer numbers, you should cast the numbers explicitly to the integer data type.

Before casting make sure that you multiply the number with a large integer so that you can lower the probability of getting the repetitive numbers.

You can fill the integer array with random numbers using the Math class by following the given steps.

  • Declare and instantiate an integer array.
  • Iterate the array,
    • Generate a double number by invoking the Math.random() method.
    • Multiply the result with a large integer. The code given here multiplies the number with 1e6.
    • Cast the result to int data type and store it into the array.

Let us see the code.

package java2blog;

public class FillArrayExample {

    public static void main(String[] args) 
    {
        int [] rArr = new int[6];

        for(int i=0;i

Output:

Randomly filled array elements are:
797056 217515 694273 810260 308203 952512

Fill the Array With Random Numbers in Java in a Concurrent Environment

Java provides a special class to produce random numbers in the concurrent environment.

The ThreadLocalRandom class is a subclass of the Random class and can be performance effective in a concurrent environment.

The nextInt() method of this class is similar to the nextInt() method of the Random class. You can take the following steps to fill the array with random numbers.

  • Declare and instantiate the array.
  • Iterate the array,
    • Get the instance of the class for the current thread using the static current() method.
    • Invoke the nextInt() method and assign the number to the current array element.

Let us see the code.

package java2blog;

import java.util.concurrent.ThreadLocalRandom;

public class FillArrayExample {

    public static void main(String[] args) 
    {
        int [] rArr = new int[6];

        for(int i=0;i

Output:

Randomly filled array elements are:
1069164748 -622761547 1121608439 73889954 2082012432 493374267

You can read about more methods of this class here.

Conclusion

This article has shown you three different methods to fill the array with random numbers in Java.

Other methods are thread-safe but they can have degraded performance in a concurrent environment. Therefore, you should use the ThreadLocalRandom class in a concurrent environment.

Although all methods are useful, using ints() is simplest as it does the job in a single line of code.

If you need to generate numbers within a given range, you can read our other article here.

Hope you have enjoyed the article. Stay tuned for more articles. Happy Learning!

]]> https://java2blog.com/fill-array-with-random-numbers-java/feed/ 0 Random Number Between 1 and 100 in Java https://java2blog.com/generate-random-number-between-1-and-100-java/?utm_source=rss&utm_medium=rss&utm_campaign=generate-random-number-between-1-and-100-java https://java2blog.com/generate-random-number-between-1-and-100-java/#respond Mon, 07 Mar 2022 14:04:13 +0000 https://java2blog.com/?p=19595

TL;DR
To generate random number between 1 and 100 in java, you can use Math.random() method.

package java2blog;

public class RandomIntegerExample {

    public static void main(String[] args) 
    {
        int myRandInt = (int)(Math.random()*100+1);
        System.out.println("Random number between 1 and 100: "+myRandInt);
    }

}

Output:

Random number between 1 and 100: 26

Math.random Java between 1 and 100

Java provides the Math class to perform all sorts of mathematical operations.

The class also has a method named random() that produces pseudo-random numbers in uniform distribution.

The definition of the random() method is given below.

public static double random()

The random() method generates a double number between 0.0 (inclusive) and 1.0 (exclusive).

You can generate the number between 1 and 100 using the Math.random() method by following the steps given below.

  • Generate a random number by invoking the Math.random() method.
  • Multiply the number with 100.
  • Add 1 to the number.
  • If you want the integer result, explicitly cast the result to ‘int’.

Let us see the code.

package java2blog;

public class RandomIntegerExample {

    public static void main(String[] args) 
    {
        int myRandInt = (int)(Math.random()*100+1);
        System.out.println("Random number between 1 and 100: "+myRandInt);
    }

}

Output:

Random number between 1 and 100: 6

Here is generic formula to get random number between min and max value in Java.

int randomNumber = (int) (Math.random()*(max-min)) + min;

Let’s put min as 1 and max as 100 in the formula.

package java2blog;

public class RandomIntegerExample {

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

        int myRandInt = (int) (Math.random()*(max-min)) + min;
        System.out.println("Random number between 1 and 100: "+myRandInt);
    }

}

Output:

Random number between 1 and 100: 47

Using Java Util’s Random Class to Generate Random Number Between 1 and 100 in Java

The Random class of Java’s Utility library provides different methods to generate random numbers.

It provides methods to generate integer numbers, floating-point numbers, double numbers, and random sequences of bytes.

There are different polymorphic forms of methods that can generate an integer number within a given range as well as within the range of the integer data type.

However, this article focuses on generating number between 1 and 100.

You can also provide a seed value to the Random class using the constructor or the setSeed() method.

There are two methods to perform the task of generating the random integer between 1 and 100. Let us see each of them one by one.

The nextint() Method

The definition of the nextInt() method is given below.

public int nextInt(int bound)

This method returns a pseudo-random number between 0 and the ‘bound’ parameter. Note that 0 is inclusive and the ‘bound’ is exclusive.

To generate a number between 1 and 100, both inclusive, you can follow the steps given below.

  • Create an instance of the Random class.
  • Generate a random number by calling the nextInt() method and passing the upper bound (100) to the method as a parameter.
  • It will generate a number between 0 (inclusive) and 100 (exclusive).
  • To make it between 1(inclusive) and 100 (inclusive), add 1 to the number returned by the method.

Let us see the code implementing the above approach.

package java2blog;

import java.util.Random;

public class RandomIntegerExample {

    public static void main(String[] args) 
    {
        Random randI = new Random();
        int myRandInt = randI.nextInt(100);
        myRandInt = myRandInt+1;
        System.out.println("Random number between 1 and 100: "+myRandInt);
    }

}

Output:

Random number between 1 and 100: 87

The ints() Method

The ints() method is also defined in the Random class. It has several different polymorphic forms.

You can use this method to generate a stream of random numbers in a range. The ints() method is defined as given below.

public IntStream ints(int randomNumberOrigin,
                      int randomNumberBound)

You can note that this method returns a stream of integers rather than a single integer. You can retrieve the integers from the stream.

Let us see the steps to generate a random number using the ints() method.

  • Create an instance of the Random class.
  • Invoke the ints() method by passing 1 and 101 as the parameters.
  • This will generate the numbers in the range from 1(inclusive) and 101(exclusive). It means you will get numbers between 1 and 100.
  • Extract any random number from all the numbers by calling the findAny() and the getAsInt() method.

Let us see the example code.

package java2blog;

import java.util.Random;

public class RandomIntegerExample {

    public static void main(String[] args) 
    {
        Random randI = new Random();
        int myRandInt = randI.ints(1, 101).findAny().getAsInt();
        System.out.println("Random number between 1 and 100: "+myRandInt);
    }

}

Output:

Random number between 1 and 100: 71

Using Apache Commons Library to Generate Random Number Between 1 and 100 in Java

Apache Commons is a popular third-party library in Java developed by Apache.

The library defines a RandomUtils class that contains several methods to produce random numbers of different data types.

The RandomUtils class contains two polymorphic forms of the nextInt() method that you can use to generate random integers.

One of these forms generates the numbers between a given range. Let us see the definition of the nextInt() method.

public static int nextInt(int startInclusive,
                          int endExclusive)

The method generates a pseudo-random number between the first argument (inclusive) and the second argument (exclusive).

Note that this method throws the IllegalArgumentsException if you provide negative arguments of if the startInclusive is greater than the endExclusive argument.

To generate a number between 1 and 100,

  • Invoke the nextInt() method by passing 0 and 100 as parameters.
  • Add 1 to the result returned by the method.

Note that you do not need an instance of the class as the method is a static method.

Let us see the code.

package java2blog;

import org.apache.commons.lang3.RandomUtils;

public class RandomIntegerExample {

    public static void main(String[] args) 
    {   
        int myRandInt = RandomUtils.nextInt(0, 100);
        myRandInt = myRandInt+1;
        System.out.println("Random number between 1 and 100: "+myRandInt);
    }
}

Output:

Random number between 1 and 100: 95

Note that you can alternatively pass 1 and 101 as parameters to the method. It will generate the same results.

Using ThreadLocalRandom Library to Generate Random Number Between 1 and 100 in Java in a Concurrent Environment

Although we can use Java Utility’s Random class as well as Math class to generate random numbers in threads, they can degrade the performance.

It is therefore recommended to use the ThreadLocalRandom to generate the random numbers while working with threads.

The ThreadLocalRandom class is a subclass of Java Utility’s Random class. You can use the nextInt() method of this subclass to generate the random integer number in a thread.

You can pass two parameters to the nextInt() method. The number is generated between the first parameter (inclusive) and the second parameter (exclusive).

You can follow the given steps to generate a random number between 1 and 100.

  • Invoke the static current() method of the ThreadLocalRandom class using the class name. It returns the ThreadLocalRandom of the current thread.
  • Invoke the nextInt() method with 1 and 101 as parameters.
  • It will generate a random number between 1 (inclusive) and 100 (inclusive).

Let us see the code.

package java2blog;

import java.util.concurrent.ThreadLocalRandom;

public class RandomIntegerExample {

    public static void main(String[] args) 
    {   
        int myRandInt = ThreadLocalRandom.current().nextInt(1, 101);

        System.out.println("Random number between 1 and 100: "+myRandInt);

    }

}

Output:

Random number between 1 and 100: 20

Conclusion

This article has discussed four different ways to generate the random number between 1 and 100.

You can generate the random number between any given range of numbers by simply varying the parameters to the methods as discussed in the article.

You can also produce numbers with other data types using similar methods.

Hope you enjoyed reading the article. Stay tuned for more articles. Happy learning!

References

That’s all about how to get Random Number Between 1 and 100.

]]>
https://java2blog.com/generate-random-number-between-1-and-100-java/feed/ 0
Get Random Number between 0 and 1 in Java https://java2blog.com/random-number-between-0-1-java/?utm_source=rss&utm_medium=rss&utm_campaign=random-number-between-0-1-java https://java2blog.com/random-number-between-0-1-java/#respond Sat, 05 Oct 2019 10:55:36 +0000 https://java2blog.com/?p=7836 In this post, we will see how to get random number between 0 to 1 in java. We have already seen random number generator in java.

Get Random Number between 0 and 1 in Java

We can simply use Math.random() method to get random number between 0 to 1.

Math.random method returns double value between o(inclusive) to 1(exclusive).

package org.arpit.java2blog;

public class RandomNumber0To1Main {

    public static void main(String args[])
    {
        System.out.println("Random number 1 : "+Math.random());
        System.out.println("Random number 2 : "+Math.random());
        System.out.println("Random number 3 : "+Math.random());
        System.out.println("Random number 4 : "+Math.random());
    }
}

When you run above program, you will get below output

Random number 1 : 0.7411678523235552
Random number 2 : 0.2933148166792703
Random number 3 : 0.48691199704439214
Random number 4 : 0.6151816544734755

Get Random Number 0 or 1 in Java

If you need to get random number as 0 or 1 and not floating points between 0 and 1, you can use following code.

package org.arpit.java2blog;

public class GenerateRandomMain {

        public static void main( String args[] ) {
            int min = 0; // Min value
            int max = 1; // Max value

            int randomInt = (int)Math.floor(Math.random() * (max - min + 1) + min);
            // Random number 0 or 1
            System.out.println("Random number 0 or 1: "+randomInt);
        }
}
Random number 0 or 1: 0

This code is applicable to get any random numbers between range. You can change min and max value based on your requirements.

That’s all about how to get random number between 0 and 1 in java.

]]>
https://java2blog.com/random-number-between-0-1-java/feed/ 0
java random number between 1 and 10 https://java2blog.com/java-random-number-1-10/?utm_source=rss&utm_medium=rss&utm_campaign=java-random-number-1-10 https://java2blog.com/java-random-number-1-10/#comments Fri, 29 Mar 2019 18:56:19 +0000 https://java2blog.com/?p=7233 We have already seen random number generator in java.In this post, we will address specific query on how to generate random number between 1 to 10.

Using random.nextInt() to generate random number between 1 and 10

We can simply use Random class’s nextInt() method to achieve this.

As the documentation says, this method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)", so this means if you call nextInt(10), it will generate random numbers from 0 to 9 and that’s the reason you need to add 1 to it.
Here is generic formula to generate random number in the range.

randomGenerator.nextInt((maximum – minimum) + 1) + minimum
In our case,
minimum = 1
maximum = 10so it will be
randomGenerator.nextInt((10 – 1) + 1) + 1
randomGenerator.nextInt(10) + 1

So here is the program to generate random number between 1 and 10 in java.

package org.arpit.java2blog;

import java.util.Random;

public class GenerateRandomInRangeMain {

    public static void main(String[] args) {

        System.out.println("============================");
        System.out.println("Generating 10 random integer in range of 1 to 10 using Random");
        System.out.println("============================");
        Random randomGenerator=new Random();
        for (int i = 0; i < 10; i++) {
            System.out.println(randomGenerator.nextInt(10) + 1);
        }

    }
}

When you run above program, you will get below output:

==============================
Generating 10 random integer in range of 1 to 10 using Random
==============================
1
9
5
10
2
3
2
5
8
1

Using Math.random() to generate random number between 1 and 10

You can also use Math.random() method to random number between 1 and 10. You can iterate from min to max and use Math.ran
Here is formula for the same:

int randomNumber = (int) (Math.random()*(max-min)) + min;

Let’s see with the help of example:

public class MathRandomExample
{
    public static void main(String[] args) {
        int min = 1;
        int max = 10;
        System.out.println("============================");
        System.out.println("Generating 10 random integer in range of 1 to 10 using Math.random");
        System.out.println("============================");
        for(int i = 0; i < 5; i++) {
            int randomNumber = (int) (Math.random()*(max-min)) + min;
            System.out.println(randomNumber);
        }

    }
}
============================
Generating 10 random integer in range of 1 to 10 using Math.random
============================
9
6
5
6
2

Using ThreadLocalRandom.current.nextInt() to generate random number between 1 and 10

If you want to generate random number in current thread, you can use ThreadLocalRandom.current.nextInt() to generate random number between 1 and 10.

ThreadLocalRandom was introducted in JDK 7 for managing multiple threads.

Let’s see with the help of example:

import java.util.concurrent.ThreadLocalRandom;
public class ThreadLocalRandomNextIntMain
{
    public static void main(String[] args) {
        int min = 1;
        int max = 10;
        System.out.println("============================");
        System.out.println("Generating 10 random integer in range of 1 to 10 using Math.random");
        System.out.println("============================");
        for(int i = 0; i < 5; i++) {
            int randomNumber =  ThreadLocalRandom.current().nextInt(min, max) + min;
            System.out.println(randomNumber);
        }

    }
}
============================
Generating 10 random integer in range of 1 to 10 using Math.random
============================
7
7
4
10
4

That’s all about java random number between 1 and 10.

]]>
https://java2blog.com/java-random-number-1-10/feed/ 1
Java Random nextDouble https://java2blog.com/java-random-nextdouble/?utm_source=rss&utm_medium=rss&utm_campaign=java-random-nextdouble https://java2blog.com/java-random-nextdouble/#respond Wed, 13 Dec 2017 18:27:55 +0000 https://java2blog.com/?p=4959 In this tutorial, we will see Java Random nextDouble method.It is used to generate random double. It returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator’s sequence.

Syntax

random.nextDouble()

Here random is object of the java.util.Random class.

Return

returns random double.

Example

Let’s understand with the help of simple example

package org.arpit.java2blog;

import java.util.Random;

public class RandomNextDoubleMain {

    public static void main(String[] args) {
        Random random=new Random();
        System.out.println("Random Double: "+random.nextDouble());
        System.out.println("Random Double: "+random.nextDouble());
        System.out.println("Random Double: "+random.nextDouble());
    }
}

Output:

Random Double: 0.00885533336458566
Random Double: 0.5098436969133946
Random Double: 0.685286317774665

Generate double in the range

You can use below code to generate double in the range.

package org.arpit.java2blog;

import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

public class RandomNextDoubleMain {

    public static void main(String[] args) {
        Random random=new Random();

        int rangeMin=10;
        int rangeMax=20;

        System.out.println("===========================================");
        System.out.println("Generating random numbers in range of 10 to 20");
        System.out.println("===========================================");

        for (int i = 0; i < 5; i++) {
            double randomDouble = rangeMin + (rangeMax - rangeMin) * random.nextDouble();
            System.out.println(randomDouble);
        }

        System.out.println("===========================================");
        System.out.println("Using ThreadLocalRandom to generate double in range of 10 to 20:");
        System.out.println("===========================================");

        for (int i = 0; i < 5; i++) {
            double randomNumber = ThreadLocalRandom.current().nextDouble(rangeMin, rangeMax);
            System.out.println(randomNumber);
        }

    }
}

Output:

Generating random numbers in range of 10 to 20
===========================================
Generating random numbers in range of 10 to 20
===========================================
17.185913130079236
10.599693774176135
19.737211130483843
19.779771283014075
11.083440540484645
===========================================
Using ThreadLocalRandom to generate double in range of 10 to 20:
===========================================
14.490580004505432
15.959990499785127
18.44256504725257
14.841549130119944
13.015851077182596

That’s all about Java Random nextDouble method.

]]>
https://java2blog.com/java-random-nextdouble/feed/ 0
Java Random nextInt https://java2blog.com/java-random-nextint/?utm_source=rss&utm_medium=rss&utm_campaign=java-random-nextint https://java2blog.com/java-random-nextint/#respond Wed, 13 Dec 2017 18:10:34 +0000 https://java2blog.com/?p=4955 In this tutorial, we will see Java Random nextInt method.It is used to generate random integer.
There are two overloaded versions for Random nextInt method.

nextInt()

Syntax

random.nextInt()

Here random is object of the java.util.Random class.

Return

returns random integer.

Example

Let’s see a very simple example:

package org.arpit.java2blog;

import java.util.Random;

public class RandomNextIntMain {

    public static void main(String[] args) {
        Random random=new Random();
        System.out.println("Random Integer: "+random.nextInt());
        System.out.println("Random Integer: "+random.nextInt());
        System.out.println("Random Integer: "+random.nextInt());
    }
}

Output:

Random Integer: 1326186546
Random Integer: 203489674
Random Integer: -472910065

nextInt(int bound)

Syntax

random.nextInt(bound)

Here random is object of the java.util.Random class and bound is integer upto which you want to generate random integer.
Random’s nextInt method will generate integer from 0(inclusive) to bound(exclusive)
If bound is negative then it will throw IllegalArgumentException

Return

returns random integer in range of 0 to bound(exclusive)

Example

Let’s see a very simple example:

package org.arpit.java2blog;

import java.util.Random;

public class RandomNextIntMain {

    public static void main(String[] args) {
        Random random=new Random();
        System.out.println("Generating 10 random integer from range of 0 to 100:");
        for (int i = 0; i < 10; i++) {
            System.out.println(random.nextInt(101));
        }

    }
}

As bound is exclusive, hence we have use random.nextInt(101) to generate integer from 0 to 100.
Output:

Generating 10 random integer from range of 0 to 100
72
100
98
69
62
90
88
16
16
61
]]>
https://java2blog.com/java-random-nextint/feed/ 0
Java – generate random String https://java2blog.com/java-generate-random-string/?utm_source=rss&utm_medium=rss&utm_campaign=java-generate-random-string https://java2blog.com/java-generate-random-string/#respond Wed, 13 Dec 2017 17:38:46 +0000 https://java2blog.com/?p=4952 In this tutorial, we will see how to generate random String in java.
There are many ways to generate random String.Let’s explore some of ways to generate random String.

Using simple java code with Random

You can use SecureRandom class to generate random String for you.
Let’s understand with the help of example.

package org.arpit.java2blog;

import java.security.SecureRandom;

public class RandomStringGeneratorMain {

    private static final String CHAR_LIST = 
            "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    /**
     * This method generates random string
     * @return
     */
    public String generateRandomStringUsingSecureRandom(int length){
        StringBuffer randStr = new StringBuffer(length);
        SecureRandom secureRandom = new SecureRandom();
        for( int i = 0; i < length; i++ ) 
            randStr.append( CHAR_LIST.charAt( secureRandom.nextInt(CHAR_LIST.length()) ) );
        return randStr.toString();
    }

    public static void main(String a[]){
        RandomStringGeneratorMain rsgm = new RandomStringGeneratorMain();
        System.out.println("Generating String of length 10: "+rsgm.generateRandomStringUsingSecureRandom(10));
        System.out.println("Generating String of length 10: "+rsgm.generateRandomStringUsingSecureRandom(10));
        System.out.println("Generating String of length 10: "+rsgm.generateRandomStringUsingSecureRandom(10));
        System.out.println("Generating String of length 8: "+rsgm.generateRandomStringUsingSecureRandom(8));
        System.out.println("Generating String of length 8: "+rsgm.generateRandomStringUsingSecureRandom(8));
        System.out.println("Generating String of length 8: "+rsgm.generateRandomStringUsingSecureRandom(8));
        System.out.println("Generating String of length 7: "+rsgm.generateRandomStringUsingSecureRandom(7));
        System.out.println("Generating String of length 7: "+rsgm.generateRandomStringUsingSecureRandom(7));
        System.out.println("Generating String of length 7: "+rsgm.generateRandomStringUsingSecureRandom(7));
    }
}

Output:

Generating String of length 10: Hz0hHRcO6X
Generating String of length 10: wSnjx6HNlv
Generating String of length 10: 4Wg9Iww0Is
Generating String of length 8: EdJmSrfC
Generating String of length 8: dAifHyQG
Generating String of length 8: HNnxieWg
Generating String of length 7: hQrqQ2L
Generating String of length 7: 0BWBtYI
Generating String of length 7: 3WStHON

Using Apache Common lang

You can use Apache Common lang to generate random String. It is quite easy to generate random String as you can use straight forward APIs to create random String.

Create AlphaNumericString

You can use RandomStringUtils.randomAlphanumeric method to generate alphanumeric random strn=ing.

package org.arpit.java2blog;

import org.apache.commons.lang3.RandomStringUtils;

public class ApacheRandomStringMain {

    public static void main(String[] args) {
        System.out.println("Generating String of length 10: "+RandomStringUtils.randomAlphanumeric(10));
        System.out.println("Generating String of length 10: "+RandomStringUtils.randomAlphanumeric(10));
        System.out.println("Generating String of length 10: "+RandomStringUtils.randomAlphanumeric(10));
    }
}

Output:

Generating String of length 10: Wvxj2x385N
Generating String of length 10: urUnMHgAq9
Generating String of length 10: 8TddXvnDOV

Create random Alphabetic String

You can use RandomStringUtils.randomAlphabetic method to generate alphanumeric random strn=ing.

package org.arpit.java2blog;

import org.apache.commons.lang3.RandomStringUtils;

public class ApacheRandomStringMain {

    public static void main(String[] args) {
        System.out.println("Generating String of length 10: "+RandomStringUtils.randomAlphabetic(10));
        System.out.println("Generating String of length 10: "+RandomStringUtils.randomAlphabetic(10));
        System.out.println("Generating String of length 10: "+RandomStringUtils.randomAlphabetic(10));
    }
}

Output:

Generating String of length 10: zebRkGDuNd
Generating String of length 10: RWQlXuGbTk
Generating String of length 10: mmXRopdapr

That’s all about generating Random String in java.

]]>
https://java2blog.com/java-generate-random-string/feed/ 0
Random number generator in java https://java2blog.com/random-number-generator-java/?utm_source=rss&utm_medium=rss&utm_campaign=random-number-generator-java https://java2blog.com/random-number-generator-java/#respond Tue, 12 Dec 2017 19:23:31 +0000 https://java2blog.com/?p=4941 In this tutorial, we will see about random number generators.You might have requirement where you want to generate random numbers to perform some operation.

For example:

Let’s say you are creating a game which uses dice for each player’s turn. You can put logic to generate random number whenever the player uses dice.

There are many ways to generate random numbers in java.Let’s see each with the help of example.

Using Random class

You can use java.util.Random to generate random numbers in java.You can generate integers, float, double, boolean etc using Random class.

Let’s understand with the help of example:

package org.arpit.java2blog;

import java.util.Random;

public class RandomClassGeneratorMain {

    public static void main(String[] args) {
        Random randomGenerator=new Random();

        System.out.println("============================");
        System.out.println("Generating 5 random integers");
        System.out.println("============================");
        for (int i = 0; i < 5; i++) {
            System.out.println(randomGenerator.nextInt());
        }

        System.out.println("============================");
        System.out.println("Generating 5 random double");
        System.out.println("============================");
        for (int i = 0; i < 5; i++) {
            System.out.println(randomGenerator.nextDouble());
        }

        System.out.println("============================");
        System.out.println("Generating 5 random floats");
        System.out.println("============================");
        for (int i = 0; i < 5; i++) {
            System.out.println(randomGenerator.nextFloat());
        }

        System.out.println("============================");
        System.out.println("Generating 5 random booleans");
        System.out.println("============================");
        for (int i = 0; i < 5; i++) {
            System.out.println(randomGenerator.nextBoolean());
        }
    }
}

Output:

============================
Generating 5 random integers
============================
1342618771
-1849662552
1719085329
2141641685
-819134727
============================
Generating 5 random doubles
============================
0.1825454639005325
0.5331492085899436
0.830900901839756
0.8490109501015005
0.7968080535091425
============================
Generating 5 random floats
============================
0.9831014
0.24019146
0.11383718
0.42760438
0.019532561
============================
Generating 5 random booleans
============================
false
false
true
true
false

Using ThreadLocalRandom class

You can use ThreadLocalRandom class to generate random numbers.This class got introduced in Java 7.Although java.util.Random is thread safe but multiple threads tries to access same object, there will be lot of contention and performance issue.In case of ThreadLocalRandom, each thread will generate their own random numbers and there won’t be any contention.
Let’s understand with the help of example:

package org.arpit.java2blog;

import java.util.concurrent.ThreadLocalRandom;

public class ThreadLocalRandomMain {

    public static void main(String[] args) {

        System.out.println("============================");
        System.out.println("Generating 5 random integers");
        System.out.println("============================");
        for (int i = 0; i < 5; i++) {
            System.out.println(ThreadLocalRandom.current().nextInt());
        }

        System.out.println("============================");
        System.out.println("Generating 5 random doubles");
        System.out.println("============================");
        for (int i = 0; i < 5; i++) {
            System.out.println(ThreadLocalRandom.current().nextDouble());
        }

        System.out.println("============================");
        System.out.println("Generating 5 random floats");
        System.out.println("============================");
        for (int i = 0; i < 5; i++) {
            System.out.println(ThreadLocalRandom.current().nextFloat());
        }

        System.out.println("============================");
        System.out.println("Generating 5 random booleans");
        System.out.println("============================");
        for (int i = 0; i < 5; i++) {
            System.out.println(ThreadLocalRandom.current().nextBoolean());
        }
    }
}

Output:

============================
Generating 5 random integers
============================
-315342453
-1922639586
-19084346
-615337866
-1075097641
============================
Generating 5 random doubles
============================
0.9074981945011997
0.7626761438609163
0.4439078754038527
0.8663565773294881
0.8133933685024771
============================
Generating 5 random floats
============================
0.50696343
0.4109127
0.4284398
0.37340754
0.28446126
============================
Generating 5 random booleans
============================
false
true
false
false
true

Using Math.random method

You can use Math.random’s method to generate random doubles.

package org.arpit.java2blog;

public class MathRandomMain {

    public static void main(String[] args) {

        System.out.println("============================");
        System.out.println("Generating 5 random doubles");
        System.out.println("============================");
        for (int i = 0; i < 5; i++) {
            System.out.println(Math.random());
        }
    }
}

Output:

============================
Generating 5 random doubles
============================
0.3644159931296438
0.07011727069753859
0.7602271011682066
0.914594143579762
0.6506514073704143

Generate random numbers between range

If you want to generate random numbers between certain range, you can use Random and ThreadLocalRandom to do it.

package org.arpit.java2blog;

import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

public class GenerateRandomInRangeMain {

    public static void main(String[] args) {

        int minimum=10;
        int maximum=20;

        System.out.println("============================");
        System.out.println("Generating 5 random integer in range of 10 to 20 using Random");
        System.out.println("============================");
        Random randomGenerator=new Random();
        for (int i = 0; i < 5; i++) {
            System.out.println(randomGenerator.nextInt((maximum - minimum) + 1) + minimum);
        }
        System.out.println("============================");
        System.out.println("Generating 5 random integer in range of 10 to 20 using ThreadLocalRandom");
        System.out.println("============================");
        for (int i = 0; i < 5; i++) {
            System.out.println(ThreadLocalRandom.current().nextInt(minimum,maximum+1));
        }

        System.out.println("============================");
        System.out.println("Generating 5 random integer in range of 10 to 20 using Math.random");
        System.out.println("============================");
        for (int i = 0; i < 5; i++) {
            System.out.println(minimum + (int)(Math.random() * ((maximum - minimum) + 1)));
        }
    }
}

Output:

============================
Generating 5 random integer in range of 10 to 20 using Random
============================
11
18
14
13
15
============================
Generating 5 random integer in range of 10 to 20 using ThreadLocalRandom
============================
10
12
13
13
16
============================
Generating 5 random integer in range of 10 to 20 using Math.random
============================
14
10
16
20
15

That’s all about generating random numbers in java.

]]>
https://java2blog.com/random-number-generator-java/feed/ 0