Last active
July 31, 2023 11:13
-
-
Save itsdonnix/cacc8315083b002f0b58738580b6c48c to your computer and use it in GitHub Desktop.
Generate UUID in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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