Site icon Learn Automation

Generate Random Number and String in Java

How to generate random number and String in java

In this post we will see different methods of generate random number and String in Java.

Generate Random Number in java

Logic 1- Using Random class

package demopkg;

import java.util.Random;

public class GenRandomNumber {
    
    
    public static void main(String[] args) {
        
        //Logic 1 - Using Random class
        
        Random rand = new Random();
        int random_num=rand.nextInt(100);
        System.out.println(random_num);
        
        
    }

}

Code Explanation:

Random is a class. nextInt () is a method by using we can generate random number.

Note:  There are so many methods in Random class likenextDouble(), nextFloat(), nextBoolean(), nextLong() etc.  to generate the random number.


Logic 2 – Using Math class

package demopkg;

import java.util.Random;

public class genRandomNumber2 {
    
public static void main(String[] args) {
        
        //Logic 2 - Using Math class
        
        System.out.println(Math.random());
        
        
    }


}

Code Explanation:

Math is a class. random()  is a static method by using we can generate double format random number.


Logic 3 – Generate random alphanumeric string in java

package demopkg;

import org.apache.commons.lang3.RandomStringUtils;

public class GenRandomAlphbeticString {
    
    public static void main(String[] args) {
        
        // Logic 3- Apache commons API
        // Generate random numeric 
        String randNum = RandomStringUtils.randomNumeric(4);
        System.out.println(randNum);
        
        
        // Generate random String
        String randStr = RandomStringUtils.randomAlphabetic(5);
        System.out.println(randStr);
        
    }

}

Code Explanation:

First we need to download Apache commons lang API jars from here – Then import into your project.

There is a RandomStringUtils class which have different methods like randomNumeric(), randomeAlphabetic() etc.


How to Generate Random Characters in Java

Read this link – Generate Random Characters

Exit mobile version