Math and Random for the Java Foundations Junior Associate exam

 

Thinking about using our OCA 8 book to study for the Java Foundations Junior Associate exam? It covers most of the topics. See what other topics you need to learn and where to read about that. One of those topics is the Math and Random classes both of which are covered in this post.

Disclaimer: I’m assuming you have already an intro to Java book and just covering what you should know when studying for the exam. This is not intended to be a complete reference for the classes; this is a basic exam. If you are looking for documentation see the JavaDoc for Random and Math.

Random

Overview of Random

The Random class is used to create a list of mostly random numbers. It’s random enough for most purposes and for the exam. When you get up to writing code that has to with security, it is no longer random enough and you’ll need to use another class such as SecureRandom. Using the Random class is easy. You create an instance of it and call methods to get random values. For example:

import java.util.*;
public class PlayTest {
   public static void main(String[] args) throws Exception {
      Random random = new Random();
      System.out.println(random.nextInt());
      System.out.println(random.nextDouble());
      System.out.println(random.nextLong());
   }
}

When I run this, I get:
-944250601
0.8115233936833056
-8514335293554058162

Running again gives:
1307999651
0.4324686951998048
1958536137379003933

Notice how they are different results. When you run it, you’ll get different numbers. That’s because they are random!

How to get random values in a smaller range

Wait a minute. It’s great to be able to generate giant random numbers. But all I want to do is simulate rolling a single die which gives me a number between 1 and 6 inclusive. Luckily, there is another method available on the Random class that we can use.

nextInt(x) returns a random number between 0 and x-1. If we called random.nextInt(6), we’d get a random number from 0-5. That’s almost what we want. Since we want to start with 1, we have to add 1 to the result. Which means we can write:

int dieRoll = random.nextInt(6) + 1);

How to get the same “random” values each time you run the program

Usually, you want to get different random values each time you run the program. However, sometimes you want to test your program so that it runs the same way every time. If your program doesn’t work the way you want it to, having it work differently each time makes troubleshooting tough! Luckily, there is a way around this problem. You can pass a “seed” to the constructor. This tells Java to always return the same sequence of “random” values for the same seed.

import java.util.*;

public class PlayTest {
   public static void main(String[] args) throws Exception {
      Random random = new Random(111);
      System.out.println(random.nextInt(6) + 1);
      System.out.println(random.nextInt(6) + 1);
      System.out.println(random.nextInt(6) + 1);
   }
}

Every time I run this program, it outputs:
2
3
2

If I pass a different seed, I get different “random” values each time. Cool, right?

Math

Unlike Random, the Math class is not instantiated. All methods in Math are static. This class is for common operations you might want to do. For example:

  • Math.abs(x) gives you the absolute value of x (removes the sign if it is negative)
  • Math.round(x) rounds x to the nearest int
  • Math.sqrt(x) gives you the square root of x
  • Math.random() gives you a random double that is >= 0 and < 1.

Wait. Say what? Didn’t we just go over a whole class about random numbers? Yes. We did. The Math class’ one doesn’t require you to instantiate it class. It’s good if you just need a quick random number. It doesn’t give as much control as Random.

You can get an int random number out of this by mutliplying and casting to an int. For example, this prints an int between 0 and 4 inclusive:

System.out.println((int) (Math.random() * 5));

Summary

What are the key takeaways for the exam in all this?

  1. The Math class has static methods
  2. Math.random() returns a double between 0 and 1 including 0 and not including 1.
  3. The Random class has instance methods.
  4. The Random class can return an int random number.
  5. If you instantiate two classes with the same random seed, they will return the same “random” numbers for the same sequence of calls.

Practice Questions

And yes, you can figure out the answers to some by looking at others. The key is to understand and remember the information.

Question 1

Which of the following fill in the blanks to make this code compile?

double num1 = _____________.random();
int num2 = ____________.nextInt();

A: Math, Random

B: Math, new Random()

C: new Math(), Random

D: new Math(), new Random()

E: None of the above

Question 2

What are possible values for Math.random() to return? (Choose all that apply)

A: 0

B: .5

C: 1

D: 5

E: None of the above

Question 3

What are possible values for new Random.nextInt(5) to return? (Choose all that apply)

A: 0

B: .5

C: 1

D: 5

E: None of the above

Question 4

Will of these statements are true? (Choose all that apply)

A: Math.random() will return the same number if called twice.

B: new Random().nextInt() will return the same number if called twice.

C: new Random(6).nextInt() will return the same number if called twice.

D: Random.nextInt() will return the same number if called twice.

E: None of the above

 

The answers are posted here.

How to Study for the Java Foundations Junior Associate exam

Oracle’s Java Foundations Junior Associate exam is brand new (in beta at the time of this post). Since this isn’t an upgraded version of an existing exam, it’s going to take time for books to come out on the topic. [Update: If they do at all. This isn’t a popular exam]

I took the beta today to see if Scott and my OCA 8 (or 11) book could be used to study. The answer is yes supplemented by a few other things. (In the interest of disclosure, this is true of any OCA book you might have access to as well.)

Before you read any further, see my other post on why I think you shouldn’t take the Junior Associate exam.

Still reading? Ok. If you have your mind set on taking the Junior Associate exam, here’s what you need to know.

Objectives Mapping

This cross references the objectives between the OCA 8 and Junior Associate exam. As you can see, reading an OCA book will put you in good shape. Then there are the “new” objectives. See the table at the bottom of our Java Foundations page for links to blog posts with sample questions.