Generate random hex color code in Java

In this tutorial, we will see how to generate random hexadecimal color code in Java. Colors are specified using hexadecimal values. It is in the form of a hex triplet, which represents three separate values specifying the levels of the component colors(RGB).

  • It starts with a pound sign(#)
  • There are only six digits.
  • The digits comprise 0-9 and a-f.

For exampe, #ADC674 is a valid hexadecimal code.

It is generally used in HTML and websites and this code refers to the RGB color space.

Java program to generate Random Hex color code

In this program, we will use Random class to generate code.

  • java.util package contains Random class.
  • An instance of Random class is used to generate random numbers.
  • If two instances have the same seed value, then they will generate the same sequence of random numbers.

Therefore, we call nextInt() method on that instance to generate random number. The parameter passed to this function is the maximum permissible value of the generated number(Excluding the limit). The maximum value in our case is ffffff.

Java Code:

import java.util.Random;
public class Main {

public static void main(String[] args) {

// create object of Random class
Random obj = new Random();
int rand_num = obj.nextInt(0xffffff + 1);

// format it as hexadecimal string and print
String colorCode = String.format("#%06x", rand_num);
System.out.println(colorCode);
}
}

An important point to remember:

  • If a number starts with 0x, it means the rest of the digits are interpreted as hex.

Further, I have used String.format() method to format the generated number into hexadecimal color code. Firstly, the String begins with “%” and the number specifies the minimum length of the string. For padding, we use the character “0“. By default, left padding is used.

Moreover, x indicates hexadecimal value.

Hence, we have satisfied all our requirements for hexadecimal color code.

Output:

#a3f688

Also read,

How to draw various shapes in Java Swing

Generate random hex CSS color code in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *