Skip to content
Related Articles

Related Articles

Java Program to Generate Random Hexadecimal Bytes

Improve Article
Save Article
  • Last Updated : 02 Dec, 2020
Improve Article
Save Article

To generate Random Hexadecimal Bytes, first, a random byte can be generated in decimal form using Java.util.Random.nextInt() and then it can be converted to hexadecimal form using Integer.toHexString() method.

1. Java.util.Random.nextInt()

The nextInt() method is used to obtain the next integer from this random number generator’s sequence. Here the range can also be specified which will return a number between 0 inclusive and the specified number exclusive.


public int nextInt()

Return Value: The method call returns the next integer number from the random number generator sequence


// Here printing n is a random integer.
int n = ran.nextInt();

2. Integer.toHexString() 

toHexString() is a built-in method in Java which returns a string representation of the integer argument as an unsigned integer in base 16. The function takes a single parameter as an argument in Integer data-type.


public static String toHexString(int num)

Return value: It returns string representation of the integer argument as an unsigned int in base 16






// Java Program to Generate Random Hexadecimal Bytes
import java.util.Random;
class GFG {
    public static void main(String[] args)
          // Random instance
        Random r = new Random();
        int n = r.nextInt();
        // n stores the random integer in defcimal form
        String Hexadecimal = Integer.toHexString(n);
        // toHexString(n) converts n to hexadecimal form
        System.out.println("Random Hexadecimal Byte: "
                           + Hexadecimal);


Random Hexadecimal Byte: 61fdc065
My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!