Java UUID fromString() Method



Description

The Java UUID fromString(String name) method is used to create a UUID from the string standard representation as described in the toString() method.

Declaration

Following is the declaration for java.util.UUID.fromString() method.

public static UUID fromString(String name)

Parameters

name − This is a string that specifies a UUID.

Return Value

The method call returns a UUID with the specified value.

Exception

IllegalArgumentException − This exception is thrown if the name does not confirm to the string representation as described in toString().

Getting a UUID generated using Standard Formatted String Example

The following example shows usage of Java UUID fromString() method to get a UUID object from standard formatted string. We've created a UUID object using fromString() method and uid is printed.

package com.tutorialspoint;

import java.util.UUID;

public class UUIDDemo {
   public static void main(String[] args) {

      // creating UUID      
      UUID uid = UUID.fromString("38400000-8cf0-11bd-b23e-10b96e4ef00d");     

      // checking UUID value
      System.out.println("UUID value is: "+uid);    
   }    
}

Output

Let us compile and run the above program, this will produce the following result.

UUID value is: 38400000-8cf0-11bd-b23e-10b96e4ef00d

Getting Exception While Generating a UUID using Invalid Formatted String Example

The following example shows usage of Java UUID fromString() method to get a UUID object from standard formatted string. We've created a UUID object using fromString() method and uid is printed.

package com.tutorialspoint;

import java.util.UUID;

public class UUIDDemo {
   public static void main(String[] args) {

      try {
         // getting a UUID
         UUID uid = UUID.fromString("38400000-8cf0-11bd-b23e");     

         // checking UUID value
         System.out.println("UUID value is: "+uid); 
      } catch(Exception e) {
         e.printStackTrace();
      }   
   }    
}

Output

Let us compile and run the above program, this will produce the following result.

java.lang.IllegalArgumentException: Invalid UUID string: 38400000-8cf0-11bd-b23e
	at java.base/java.util.UUID.fromString(UUID.java:215)
	at com.tutorialspoint.UUIDDemo.main(UUIDDemo.java:10)
java_util_uuid.htm
Advertisements