TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Generate Random Number in Java – 10 Ways
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Java BasicJava Tutorials

Generate Random Number in Java – 10 Ways

Last updated: Feb 04, 2024 12:36 am
By Harsh S.
Share
8 Min Read
How to generate number in Java - 10 Ways
SHARE

Welcome to our comprehensive guide on random number generation in Java! In this post, we will discuss 10 different ways to generate random numbers in Java. We will also provide working code snippets for each method. By the end of this post, you will be familiar with a variety of techniques for generating random numbers in Java and be able to choose the best method for your needs.

Whether you’re a programmer or a tester looking to enhance your skills, these coding snippets will unlock the secrets to seamless random number generation in your Java applications. Let’s dive in and discover the world of randomness in Java!

Let’s Get Started with Randon Number Generation in Java!

Here are the working Java programs for each of the 10 techniques to generate random numbers:

1. Using Math.random() Method

The Math.random() method returns a pseudo-random double value between 0.0 and 1.0. By scaling and adding an offset, you can generate random integers within a specified range.

public class MathRandomExample {
  public static void main(String[] args) {
    int range = 100;
    int minValue = 1;

    double randomValue = Math.random();
    int randomNumber = (int)(randomValue * range) + minValue;

    System.out.println("Random Number (Math.random()): " + randomNumber);
  }
}

Also Read:  1-10 Random Number Generator

2. Java Random Class for Random Number Generation

The Random class provides a more flexible way to generate random numbers. It offers various methods like nextInt(), nextLong(), and nextDouble() to generate integers, longs, and doubles, respectively.

import java.util.Random;

public class RandomClassExample {
  public static void main(String[] args) {
    int range = 100;
    int minValue = 1;

    Random random = new Random();
    int randomNumber = random.nextInt(range) + minValue;

    System.out.println("Random Number (Random class): " + randomNumber);
  }
}

3. Using ThreadLocalRandom (Java 7+)

The ThreadLocalRandom class is a high-performance random number generator introduced in Java 7. It provides thread-local instances of Random, making it ideal for concurrent applications.

import java.util.concurrent.ThreadLocalRandom;

public class ThreadLocalRandomExample {
  public static void main(String[] args) {
    int range = 100;
    int minValue = 1;

    int randomNumber = ThreadLocalRandom.current().nextInt(minValue, range + 1);

    System.out.println("Random Number (ThreadLocalRandom): " + randomNumber);
  }
}

Also Read:  Generate Random Images

4. Use SecureRandom for Random Number Generation in Java

The SecureRandom class is designed for generating cryptographically strong random numbers. It is crucial for sensitive applications like cryptography and secure communications.

import java.security.SecureRandom;

public class SecureRandomExample {
  public static void main(String[] args) {
    int range = 100;
    int minValue = 1;

    SecureRandom secureRandom = new SecureRandom();
    int randomNumber = secureRandom.nextInt(range) + minValue;

    System.out.println("Random Number (SecureRandom): " + randomNumber);
  }
}

5. Using Random.nextInt() (Java 8)

Java 8 introduced streams, and you can use Random.nextInt() within a stream to generate a random number from a specified range. This allows for a more concise and expressive coding style.

import java.util.Random;
import java.util.stream.IntStream;

public class RandomIntStreamExample {
  public static void main(String[] args) {
    int range = 100;
    int minValue = 1;

    Random random = new Random();
    int randomNumber = random.ints(minValue, range + 1)
      .findFirst()
      .getAsInt();

    System.out.println("Random Number (Java 8 Streams): " + randomNumber);
  }
}

6. Random.ints() for Random Number Generation in Java 9

Java 9 further simplified random number generation with the introduction of Random.ints(), which directly returns a stream of random integers within a specified range.

import java.util.Random;

public class RandomIntsExample {
  public static void main(String[] args) {
    int range = 100;
    int minValue = 1;

    Random random = new Random();
    int randomNumber = random.ints(minValue, range + 1)
      .findFirst()
      .getAsInt();

    System.out.println("Random Number (Java 9 Random.ints()): " + randomNumber);
  }
}

7. Using Math.random() and Thread.sleep() for added randomness

By introducing a Thread.sleep() delay, you can add an element of time-based randomness to the random number generation process. This approach can be helpful in specific scenarios.

public class RandomWithSleepExample {
  public static void main(String[] args) throws InterruptedException {
    int range = 100;
    int minValue = 1;

    double randomValue = Math.random();
    int randomNumber = (int)(randomValue * range) + minValue;

    Thread.sleep(randomValue * 1000); // Add delay for added randomness

    System.out.println("Random Number (with added sleep): " + randomNumber);
  }
}

8. Using java.util.BitSet (Unique random numbers)

The BitSet class helps ensure that the generated random numbers are unique. This is useful when you need to create a unique set of random values without repetitions.

import java.util.BitSet;
import java.util.Random;

public class BitSetExample {
  public static void main(String[] args) {
    int range = 100;
    int minValue = 1;

    Random random = new Random();
    BitSet bitSet = new BitSet(range);

    int randomNumber = random.nextInt(range);
    while (bitSet.get(randomNumber)) {
      randomNumber = random.nextInt(range);
    }
    bitSet.set(randomNumber);

    randomNumber += minValue;

    System.out.println("Random Number (BitSet): " + randomNumber);
  }
}

9. Using Collections.shuffle() with a List of numbers

By populating a list with a range of numbers and then shuffling it using Collections.shuffle(), you can achieve random ordering of elements in the list.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectionsShuffleExample {
  public static void main(String[] args) {
    int range = 100;
    int minValue = 1;

    List < Integer > numbers = new ArrayList < > ();
    for (int i = minValue; i <= range; i++) {
      numbers.add(i);
    }
    Collections.shuffle(numbers);

    int randomNumber = numbers.get(0);

    System.out.println("Random Number (Collections.shuffle()): " + randomNumber);
  }
}

10. Using UUID.randomUUID() to generate a random UUID

Though originally intended for generating unique identifiers, you can leverage UUID.randomUUID() to obtain random integer values by hashing the UUID.

import java.util.UUID;

public class RandomUUIDExample {
  public static void main(String[] args) {
    int range = 100;
    int minValue = 1;

    UUID uuid = UUID.randomUUID();
    int randomNumber = uuid.hashCode();

    System.out.println("Random Number (UUID): " + randomNumber);
  }
}

You can run each of these Java programs to see the output for generating random numbers using different methods.

By the way, if you love coding in Python, then you should also know how to generate a list of random numbers in Python.

Now that you have an overview of the ten different ways to generate random numbers in Java, feel free to explore each method and choose the one that best suits your needs. Whether you’re working on simulations, games, or test automation, mastering the art of random number generation is a valuable skill for any Java programmer or tester.

Happy coding!

You Might Also Like

Postman Random APIs to Generate Unique Test Inputs

A Simple Guide to Exception Handling in Java

Difference Between Spring and Spring Boot

How to Generate Random Numbers in R

Online Tool to Generate Random Letters Or List of Letters

TAGGED:Random Data Generation Made Easy
Harsh S. Avatar
By Harsh S.
Follow:
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale projects. My skills include coding in multiple programming languages, application development, unit testing, automation, supporting CI/CD, and doing DevOps. I value Knowledge sharing and want to help others with my tutorials, quizzes, and exercises. I love to read about emerging technologies like AI and Data Science.
Previous Article Programming exercises for beginners in python 40 Exercises for Beginners to Learn Python Quickly
Next Article Linux Commands Cheat Sheet for Daily Reference Linux Commands Cheat Sheet for Geeks

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x