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.

Jeanne’s impressions of the Java Foundations Certified Junior Associate

Update: I’ve created a new version of this blog post comparing the Java Foundations exam to the Java 11 OCP.

I took the Java Foundations Certified Junior Associate exam to see how it relates the “regular” OCA (Oracle Certified Associate) exam. The objectives show an interesting mix of conceptual and hands on knowledge. Mostly hands on.

My beta exam was 101 questions in 3 hours. I finished in an hour. I spent another 40 minutes doing a review and fixed one incorrect answer. There were a few questions where the question was wrong, but it is a beta. And they let you report such issues to make the test better.

I’m an experienced Java developer. Why did I take a basic exam you ask? Two reasons.

  1. I was curious who the exam was designed for. This post answers this question.
  2. I wanted to see if Scott and my OCA 8 book could be used by people studying for this exam. The answer is yes with a tiny bit of supplemental material. See this post for details.

I went to a testing center I had disliked in the past because they had a free slot and I figured this test was so easy I wouldn’t need to concentrate. I’m happy to report that the testing center (Horizon of Flushing) fixed its problems. The room was quiet and well ventilated. They still wanted me to empty the tissues from my pockets, but at least had lockers.

The three exams

There are three intro exams right now. Here’s a comparison:

Exam Number Exam Name Allowed as Pre-req to OCP (professional exam) My comments on intended audience
1Z0-850 Java 5 or 6 Associate No This exam was meant for managers to show a working vocabulary and grasp of Java. There was a tiny bit of code, but it was mostly concepts and pseudocode.
1Z0-803 Java 7 OCAJP (associate) Yes, for OCPJP 7 This is the entry level exam for Java 7 to the developer track. It involves lots of code.
1Z0-808 Java 8 OCAJP (associate) Yes, for OCPJP 8 This is the entry level exam for Java 8 to the developer track. It involves lots of code.
1Z0-811 Junior Associate/Java Foundations No Oracle says it is meant for interns or entry level folks. I think they would be better served by taking the actual OCA. It’s within grasp with no experience, shows more knowledge of Java, sounds better and allows an upgrade to the OCP when the candidate is ready.

Quotes from Oracle

According to the Java Foundations Certified Junior Associate exam description, the exam is:

Position yourself to enter the workforce, or get the internship of your dreams with marketable Java skills.

Earning the Java Foundations Certified Junior Associate credential arms you withthe fundamentalsof Java programming,enabling you to demonstrate both conceptual knowledge and skills. Certification alsovalidates your capabilities to a future employer, showing your potential to become an increasingly valuable asset to any company as you progress into OCA level during your early stage of employment, and later to OCP.

This Junior Associate certification is focused on students in secondary schools, two-year colleges and four year colleges and universities who have participated in the Oracle Academy program and/or are studying computer science including relevant Java curricula and faculty members who teach foundational Java and computer science classes.

Though the exam does not assume any hands-on professional experience with Java, tobe successful you will need a basic understanding of Java programming language and concepts and have mathematical, logical, and analytical problem-solving skills. In addition, you must know how to write and execute a Java program and work with the Java Development kit (JDK) and the Java Runtime Environment (JRE).

Earning this certificationdemonstrates fluency in and a solid understanding of Java SE and the Java programming language, including: data types; operators and strings; decision and looping statements; classes, constructors, and methods; exceptions, ArrayLists and the Math class.

The problem is that the Regular Oracle Certified Associate Java Programmer certification says:

The Java SE 8 Oracle Certified Associate (OCA) certification helps you build a foundational understanding of Java, while expanding your knowledge of general programming.

The ideal candidate who would earn this certification typically has a technical background and wants to improve programming skills, or may be new to object-oriented programming and Java.

And the old Java 5/6 Associate exam says:

The Oracle Certified Associate, Java SE 5/SE 6 certification provides an ideal entry into an application development or a software project management career using Java technologies. This worldwide credential validates basic knowledge of Object-Oriented Concepts, UML representation of OO concepts, the Java programming language, and general knowledge of Java Platforms and Technologies. Candidates for this exam include: entry level Java programmers, students studying to become Java programmers, project or program managers working with Java technology in the software development industry.

The old Java 5/6 associate exam didn’t involve much code so this made sense.

when did we write the OCA SE 8 book

Did you write the second book before or after your exam of OCA SE 8.

I got this question from a reader of our OCA book and thought it would make a nice blog post describing the timeline.

In February 2014, Wiley/Sybex approached me about writing this book. Scott and I had discussed writing a book together “one day” so immediately asked him to co-author. Even though the publisher approached me, I still had to write a proposal which was accepted in March 2014. We then signed the contract.

We wrote a draft of all the chapters over the following months. At this point, the OCA 8 objectives hadn’t been announced. Scott held the SCJP 6 certification and I held the OCA/OCP 7 certifications. We used the OCA 7 objectives plus our expectations about changes to the language as a guide for those drafts.

Then the objectives came out. We had some rework and additions at that point. I was surprised basic lambdas were covered on the exam and Java 8 dates were also new. Then in October, I took the beta exam. At this point, the book was already written.

There was an unclear exam objective. After taking the beta exam, I learned what this meant. Which was a minor addition to the book. Other than that, it was written before the exam. Some editing was done after the exam; just in terms of timeline.

Then in December 2014, the e-book came out and it printed in February 2015.

For our upcoming OCP book, more of the book is being written after the beta exam. Just in terms of timeline, we didn’t have as much of a head start.