avatarLincoln W Daniel

Summary

The provided text discusses the importance and utility of random number generation in Java programming, detailing how to create and use random numbers and booleans to introduce unpredictability in code.

Abstract

The text begins by drawing a parallel between the use of dice in board games for randomness and the need for random number generators in computer programs. It explains that Java provides a Random class to facilitate the generation of random integers, longs, doubles, and booleans, which can be used to control the flow of a program. An example is given where a random number determines whether one should go out or stay in, illustrating the practical application of randomness in decision-making processes. The text then demonstrates how to generate random values with and without bounds, emphasizing the ease of integrating randomness into Java programs. It concludes by encouraging the reader to apply this knowledge to enhance the complexity and interest of their own programs.

Opinions

  • The author suggests that randomness can make games and programs more exciting and less predictable.
  • The use of Java's Random class is presented as a straightforward and effective way to generate random values.
  • The author implies that encapsulating the complexity of random number generation within the Random class is beneficial for developers, as it allows them to focus on the application of randomness rather than its underlying mathematics.
  • The text conveys that random number generation can be a powerful tool in making decisions within a program, as shown in the going out versus staying in example.
  • The author's choice to include both bounded and unbounded random number generation indicates a belief that understanding these concepts is fundamental for Java programmers.
  • The mention of the next chapter and the table of contents suggests that the text is part of a larger educational resource, highlighting the author's commitment to comprehensive learning.

As a kid, you may have played many games to fill your day with some fun and excitement. In some cases, the most exciting games may have been the ones that employed some bit of randomness and unpredictability. Board games like monopoly use a dice to create randomness in the outcome of the game. The series of random numbers you roll determine how successful you are in the game. Computer games, on the other hand, don’t have access to a physical dice, so there must be another way for them to create randomness. For that reason, Java and other programming languages have random number generators we can use to create randomness in our programs.

Why Random Numbers are Important & Useful

Random number generators allow us to generate random numbers that we can use to create randomness in our code. Java allows us to easily generate random whole (int or long) and floating point (double) numbers. We can also generator random boolean values. With the random numbers that we generate, we can decide when to execute some lines of code and when to execute the others.

A good example of when you may need a random number program is in deciding whether or not you should go out with friends or stay in and do your homework. You can build a program to generate a random number between zero (inclusive) and ten (exclusive). If you generate a random int between zero (inclusive) and five (exclusive), you can go out, but if it's between five (inclusive) and ten (exclusive), you must stay in.

Generating Random Numbers

By creating an instance of Java’s Random class in java, we can use it to generate random values:

Random randomNumberGenerator = new Random();

Whenever we call an instance method of the Random class, a new random number of the type you want is generated behind the scenes and returned to us. All of the complex math is encapsulated from us so we can get our random numbers or booleans and continue with our program.

Generating Random Values

Generating a random integer (int) is as simple as calling the nextInt() instance method on our instance of the Random class. We can generate other random values in similar ways:

//generate and save random int to a variable of type int
int randomInt = randomNumberGenerator.nextInt();

//generate and save random long to a variable of type long
long randomLong = randomNumberGenerator.nextLong();

//generate and save random double to a variable of type double
double randomDouble = randomNumberGenerator.nextDouble();

//generate and save random boolean to a variable of type boolean
boolean randomBoolean = randomNumberGenerator.nextBoolean();
//print out all of our random numbers
System.out.println("Random whole number as int: " + randomInt);
System.out.println("Random whole number as long: " + randomLong);
System.out.println("Random floating point number as double: " + randomDouble);
System.out.println("Random boolean: " + randomBoolean);
//generate another random int and print it inline
System.out.println("Another random whole number as int: " + randomNumberGenerator.nextInt());

As easy as that, we have three random numbers stored and a random boolean (true or false) stored in variables. Notice that at the end, we generated another random number as an int, but instead of storing it in a variable, we printed it out immediately after it was returned to us.

Generating Random Numbers With Bounds

When we generate random numbers, we can choose whether or not to do so with or without bounds. In our examples above, we generated random numbers without bounds because we did not provide a maximum bound argument to the instance methods we called. When we call the nextInt() instance method on a Random instance, we can expect to receive a random integer between and including zero and the maximum integer allowed in Java. The nextLong() and nextDouble() instance methods behave similarly.

If we want to generate random numbers with a bound, we must provide the maximum bound argument to the instance methods we call. The maximum bound argument tells the method what the last, maximum number in the range of random numbers that we expect should be. If we only want to generate random numbers between zero (inclusive) and ten (exclusive) to decide whether or not you should go out with friends or stay in and do homework, you can do the following:

int randomIntWithBound = randomNumberGenerator.nextInt(10);

Note that the maximum bound argument must be positive. Now, to check whether or not we should go out or stay in, we can do the following:

if(randomIntWithBound >= 0 && randomIntWithBound < 5) {
    //random int is between 0 (inclusive) and 5 (exclusive)
    System.out.println("I'm Going Out!");
} else if(randomIntWithBound >= 5 && randomIntWithBound < 10){
    //random int is between 5 (inclusive) and 10 (exclusive)
    System.out.println("I'm Staying in.");
}

A simpler way to do the above would be to use a random boolean value instead of a range of integers:

boolean randomBoolean = randomNumberGenerator.nextBoolean();
if(randomBoolean) {
    //random boolean is true
    System.out.println("I'm Going Out!");
} else {
    //random boolean is false
    System.out.println("I'm Staying in.");
}

That’s it. We now know how to generate random values with or without bounds as well as random booleans. Further, we have learned how to use random values to make decisions in our code with if statements. You can now employ your new knowledge to add randomness to your programs and make them that much more interesting.

Next Chapter

Table of Contents

Java
Programming
Coding
Recommended from ReadMedium