📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this guide, you will learn about the UUID fromString() method in Java programming and how to use it with an example.
1. UUID fromString() Method Overview
Definition:
The fromString() method of the UUID class in Java is a static method that creates a UUID object from the specified string. The string must represent a UUID and be in the format of 8-4-4-4-12 hex digits, separated by dashes.
Syntax:
public static UUID fromString(String name)
Parameters:
- name: The string from which the UUID is to be created. It must be in the format of 8-4-4-4-12 hexadecimal digits, separated by dashes.
Key Points:
- The UUID class is part of the java.util package.
- The fromString() method throws IllegalArgumentException if the provided string does not conform to the specified format.
- It’s useful for converting a string representation of UUID back to a UUID object.
- The method is typically used when a UUID is serialized to a string using toString() method and later needs to be deserialized.
2. UUID fromString() Method Example
import java.util.UUID;
public class UUIDExample {
public static void main(String[] args) {
// The string representing the UUID
String uuidString = "f47ac10b-58cc-4372-a567-0e02b2c3d479";
// Creating a UUID object from the string
UUID uuid = UUID.fromString(uuidString);
// Printing the UUID object
System.out.println("UUID from String: " + uuid);
// Attempting to create a UUID from an invalid string
try {
UUID invalidUUID = UUID.fromString("invalid-uuid-string");
System.out.println("Invalid UUID: " + invalidUUID);
} catch (IllegalArgumentException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}
Output:
UUID from String: f47ac10b-58cc-4372-a567-0e02b2c3d479 Exception: Invalid UUID string: invalid-uuid-string
Explanation:
In this example, we successfully created a UUID object from a valid string representing a UUID and printed it. We also attempted to create a UUID from an invalid string, which resulted in an IllegalArgumentException, demonstrating that the input string must conform to the UUID format.
Comments
Post a Comment
Leave Comment