Want to create a random color in Java? With a bit of math, plus Math.random(), it’s pretty easy.

Colors on the computer are made up of a red, green, blue triplet; typically called RGB. And each of the 3 pieces can be in the range from 0 to 255. Java also allows us to create a color using floats for the values in the range of 0.0 to 1.0, or from 0% to 100% of that color. We’re going to use the floats.

As an example, pure red will have an R value of 1.0, a G value of 0.0, and a B value of 0.0.

So we know what numbers we need, but we want ’em random.

## Math.random()

Let’s take a look at the Math.random() method built in to Java. It’s a pretty simple method that returns a double between 0.0 and up to, but not including, 1.0. So, somewhere in the range $0.0$ to $0.\overline{999}$

What we’re going to do is create 3 variables; one for each red, green, and blue.

float red = Math.random();
float green = Math.random();
float blue = Math.random(); 

We now have 3 random floats to fill in to the constructor in the Color class.

Then it’s just a matter of plugging in those values.

Color col = new Color(red, green, blue);

And we have this as the full set of code.

float red = Math.random();
float green = Math.random();
float blue = Math.random();

Color col = new Color(red, green, blue);

Or, you could just one line it.

Color col = new Color(Math.random(), Math.random(), Math.random());

## Or with ints

The Color constructor will also take integers in the range of 0 to 255. Like 0.0 to 1.0, 0 is as little of a color as possible and 255 is 100% of a color. So we can also create 3 random ints in that range for our colors.

int r = Math.round(Math.random() * 255));
int g = Math.round(Math.random() * 255));
int b = Math.round(Math.random() * 255));

Color col = new Color(r, g, b);

This does the same thing, but does a bit of math first. It multiplies the random number by 255 to get a random number in the range $0 – 254.\overline{999}$. Rounding that to the nearest int gives us a number between 0 and 255, inclusive.

Published inCoding

## One Comment

1. JM

wouldn’t be (Math.random() * 256)); because to get the upper bound you do the number that is being added to Math.random() [which is 0] and the number multiplying Math.random() subtracted by 1.