How to Validate UUID Strings in Java

06 May 2023 Balmiki Mandal 0 Core Java

Validate UUID String In Java

A UUID or universally unique identifier is a standard of generating identifiers, popularly used for software components. A valid UUID string has to adhere to the following rules:

  • It should be composed of 32 hexadecimal characters.
  • It should contain four hyphens (included in the character count).
  • It should have certain predictable structure.

In Java, the java.util.UUID class provides several static utility methods for working with UUID. One of them, i.e. isValidUUID(String) method helps us to validate a string against the UUID standard.

The isValidUUID() Method returns a boolean value based on whether the given string is a valid UUID or not. It checks the length of the UUID string, the presence of hyphens and the specific arrangement of them. Here’s an example of using this method to validate a string:

String uuid1 = "4d93693a-2804-4a31-8e09-3c3db2df3182";
boolean validUUID1 = UUID.isValidUUID(uuid1);

if (validUUID1) {
  System.out.println("Valid UUID");
}
else {
  System.out.println("Invalid UUID");
}

In this example, the output will be “Valid UUID” as the given string follows all the rules of a UUID string and hence is considered valid.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.