Skip to content

Instantly share code, notes, and snippets.

@itsdonnix
Last active July 31, 2023 11:13
Show Gist options
  • Save itsdonnix/cacc8315083b002f0b58738580b6c48c to your computer and use it in GitHub Desktop.
Save itsdonnix/cacc8315083b002f0b58738580b6c48c to your computer and use it in GitHub Desktop.
Generate UUID in Java
public class Main {
/**
* Generates a random UUID (Universally Unique Identifier) in the format:
* xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx, where 'x' represents a random
* hexadecimal digit
* and 'y' represents a random hexadecimal digit with the 13th character set to
* '4' (version 4 UUID).
*
* @return The generated UUID as a string.
*/
public static String createUUID() {
String format = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
StringBuilder uuid = new StringBuilder(format);
for (int i = 0; i < format.length(); i++) {
if ((Character.compare(format.charAt(i), 'x') == 0) || (Character.compare(format.charAt(i), 'y') == 0)) {
uuid.setCharAt(i, getRandomHexDigit(format.charAt(i)));
}
}
return uuid.toString();
}
/**
* Generates a random hexadecimal digit between 0 and 15.
*
* @param character The character 'x' or 'y' from the UUID format.
* If 'x', the generated digit can be any hexadecimal digit
* (0-9, a-f).
* If 'y', the generated digit must have the 13th character set
* to '4' (version 4 UUID).
* @return The random hexadecimal digit as a char.
*/
private static char getRandomHexDigit(char character) {
int random = (int)(Math.random() * 16);
int value = character == 'x' ? random : (random & 0x3) | 0x8; // Ensure the 13th character is '4' (version 4 UUID)
return Integer.toHexString(value).charAt(0);
}
public static void main(String[] args) {
System.out.println(createUUID());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment