Generate random numbers using Javafaker API – Java

Introduction

We may require to generate random numbers in programming languages for multiple purposes like test data creation or numeric IDs for employees etc. We have multiple libraries available to generate random numbers in Java but I personally feel Javafaker APIs are easier to use compared to others.

We will learn to generate random whole numbers, decimal numbers, and also within a range in this post.

I have covered an introductory post on Javafaker API here.

Maven Dependency

I have used below Javafaker API dependency:-



    com.github.javafaker
    javafaker
    1.0.2

Generate random numbers

Faker class in Javafaker library provides utility methods for generating fake strings, such as names, phone numbers, addresses. generate random strings with given patterns.

Generate a random digit

package FakerClassExamples;

import com.github.javafaker.Faker;

public class RandomNumberExample {
	
	public static void main(String[] args) {
		
		Faker faker = new Faker();
		// Generate random digit between 0 - 9 both inclusive
		System.out.println(faker.number().digit());
		System.out.println(faker.number().randomDigit());
		
		// Generate random digit between 1 - 9 both inclusive
		System.out.println(faker.number().randomDigitNotZero());
		
		// Generate digit of specific length
		System.out.println(faker.number().digits(3));
		System.out.println(faker.number().digits(5));
	}

}
Output
5
3
6
608
72863

Generate number within a range

Generating a random number within a range is required at many times and I think Javafaker provides the easiest way to do so.

package FakerClassExamples;

import com.github.javafaker.Faker;

public class RandomNumberWithinRange {
	
	public static void main(String[] args) {
		
		Faker faker = new Faker();
		// Generate a number between 1(inclusive) to 999 (exclusive)
		System.out.println(faker.number().numberBetween(1, 999));
		
		// Generate a decimal random number within range
		System.out.println(faker.number().randomDouble(4, 10, 100));
	}

}
Output
726
89.193

There are many useful methods provided by the Javafaker library which you can explore and learn about.

You can clone above Git Repo from here.

You can subscribe to my YouTube channel RetargetCommon to learn from video tutorials.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappyLearning

Find all Selenium related posts here, all API manual and automation related posts here, and find frequently asked Java Programs here.

1 thought on “Generate random numbers using Javafaker API – Java”

Leave a Reply

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