Thursday, October 23, 2025
HomeLanguagesJavaJava Program to Generate Random Hexadecimal Bytes

Java Program to Generate Random Hexadecimal Bytes

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.

Declaration

public int nextInt()

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

Example:

// 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.

Declaration

public static String toHexString(int num)

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

Example:

Input:13
Output:d

Input:14
Output:e

Example

Java




// Java Program to Generate Random Hexadecimal Bytes
  
import java.io.*;
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);
    }
}


Output

Random Hexadecimal Byte: 61fdc065
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS