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.

decibel measuring iPhone apps

I was curious how loud my apartment is. I live on a busy street. I waited until there was little to no traffic noise to do the test. I tried two iPhone apps.

 

Category Expected result The free Decibel Meter app The 99 cent DbVolume Meter
Inside my apartment 35-45 55-60 44-46
On my terrace (mild honking) 50-60 75-80 50-60
My normal speaking voice back inside 50-60 75-85 50-55
My voice when projecting back inside (like giving a speech or on the phone) 60-70 90-100 57-60

Guess the free one is free for a reason. It’s highly inaccurate! All in all, an interesting experiment.

eclipse mars (4.5) for the mac

First of all, happy birthday. This is Eclipse’s tenth annual release train.

When I went to eclipse.org, I saw a nice picture of Mars. I have a choice of downloads including Java EE, Java and Spring Tool Suite. The matrix comparing the packages is still clear. I chose the Java EE version. The download page had a warning that “Eclipse requires Mac OS X 10.5 (Leopard) or greater.” No problem. I’m on the latest version. I’m also on the latest version of Java 8.

marsThe “tar” file (native app)

The first thing to notice is that Eclipse provides a tar file. Ok so that’s not new. What is new is that the tar file cannot be opened by the tar command because it contains absolute path names. And that Eclipse is now a native Mac app. This took me by surprise because I installed before looking at the docs.

More memory

Eclipse Mars uses more memory by default. Make sure you have enough before launching. I don’t expect to have problems with this.

To improve the “out of the box” user experience on today’s modern hardware, the default maximum heap size (-Xmx VM argument) has been increased from 512M to 1024M. And the initial heap size (-Xms) has been increased from 40M to 256M.

Initial launch

When launching my workspace, I got the warning:

Warning: Workspace ‘/myWorkspace’ was written with an older version of the product and will be updated. Updating the workspace can make it incompatible with older versions of the product. Are you sure you want to continue with this workspace.

Which is fine. I’m not going backward. And all the important code is in Subversion or Git anyway.

Installing the plugins

Like last year, I decided to install the plugins I need for Eclipse Marketplace so I can shed the plugins I tried out and don’t actually want. Cleaning plugin house once a year is nice.

The significant plugins I use are listed in this table. A number of plugins were beta for Luna or I had to use the Kepler version. I don’t remember that problem in previous years.

Last year, I tried out the Code Recommenders plugin. I didn’t install it this year as I hardly used it. I added Contrast and Bytecode Analyzer as plugins I installed in the past 12 months that I like. I also added ADT and tried out Optimizer for Eclipse by Zero Turn Around.

 

Plugin Purpose
Mongrel Tomcat integration supporting recent versions of Tomcat.
Ecl Emma Code coverage
PMD and FindBugs Static analysis. For PMD, I had to use the update site. An install “happened” through Eclipse Marketplace, but I didn’t any of the PMD settings I was expecting. Using the update site gave me what I expected
Subversive To access Subversion repositories
Groovy/Grails Tool Suite (didn’t install) Groovy project/editor and console. At this time only the Luna version is available. But more Groovy/Grails support is native to Mars so it probably isn’t needed anymore as a separate plugin.
Eclipse Memory Analyzer For finding memory leaks. Last year it was in Eclipse MarketPlace. The year before I needed to use the update site. This year we are back to using the update site.
Freemarker IDE Freemarker syntax highlighting and macro assistance.  Note that it is listed under the JBoss Tool Project. You pick that plugin and then unselect everything except “Freemarker IDE”. The JBoss Tool plugin was in beta on Mars release day. I installed this beta.
Python Python plugin/perspective
Contrast In the past 12 months, I installed the Contrast plugin for security. I like this one so re-installed it. See my impressions of the Contrast plugin.
Bytecode Outline I’ve been looking at bytecode a good fit for the book to make sure I understand why things are happening. This plugin makes it easy. I first tried Bytecode Visualizer but install failed. (The website says there were 25 failed installs with the same dependency problem in the last 7 days). After installing Bytecode Outline, I realized this was the one I had installed for Luna anyway.
Android Development Tools I have ADT as a separate install. It will be nice to be able to use my “main” Eclipse for that.
Optimizer for Eclipse This is like a freeware ad for JRebel. I tried it out and it told me a couple things of interest like the heap size. And offered to clear my indexes which had been collecting for over a year.

What excites me

  1. The JUnit view as a button to view only skipped tests. Awesome!
  2. The JUnit view now lets you re-run just one test in a parameterized test suite.
  3. The ability to close all tabs to the left or right of a current tab is cool.
  4. Search is faster on multi-core machines. I did notice a marginal improvement. I can’t tell if it was from this or from cleaning out my indexes.
  5. Quick assists between lambdas and method references
  6. When copying a file the new file is X2 instead of CopyOfX. Saves a few keystrokes per copy.

What I didn’t like

  1. I had troubles setting up Subversion connectivity, but did eventually get it to work.
  2. Since this install is on my home machine, I chose to enable error reporting. Eclipse asks me each time there is an error if I want to report it. I turned it off after reporting one error. It popped up to frequently and I have trouble imagining the dump has value to anyone. I was also annoyed they included my email in the HTML in the incident.
  3. I have a few launch configurations to run JUnit tests that I use regularly. When I ran each for the first itme, I got prompted for whether I wanted to use the Android JUnit or Java JUnit launchers. Not a big deal, but unexpected.
  4. I’m not thrilled about the native Mac application thing. The features/plugins directories are now in /Applications/Eclipse.app/Contents/Eclipse instead of a directory of my choosing. I’m also concerned about whether I’ll be able to have 4.4 and 4.5 on my machine concurrently in a year. Bear says you can have multiple versions installed.

Other interesting features

  1. Ctrl-Alt-B shortcut to skip all breakpoints. I don’t use breakpoints often so I don’t need a shortcut for this. It’s cool they created one though.
  2. There are said to be Maven updates including better autocomplete. I didn’t notice anything.
  3. Oomph for deploying Eclipse sounds like it has potential in a workspace environment
  4. A Java 9 experimental plugin It assumes have you have downloaded Java 9 which I haven’t already. I’m glad I won’t need to install a beta Eclipse when I’m ready to try out Java 9 though.