You are currently viewing UUID in Java

UUID in Java

  • Post author:
  • Post category:Java
  • Post comments:0 Comments
  • Post last modified:July 21, 2024

UUID (Universally Unique Identifier) is a fundamental concept in Java, providing a 128-bit identifier that ensures uniqueness across all devices and time. In Java, the java.util.UUID class facilitates working with UUIDs. These identifiers find extensive use in diverse applications, serving as database primary keys, aiding in distributed system coordination, and uniquely identifying resources.

In Java, you can create UUIDs using the java.util.UUID class. There are different methods to generate UUIDs, including random-based, time-based, and name-based UUIDs.


import java.util.UUID;

public class helloworld {

		public static void main(String[] args) {
	       UUID uuid=UUID.randomUUID();
	       System.out.println(uuid); //6f89feb8-61c1-49be-a090-26a53dd55d15
	       
	       UUID uuid2=UUID.fromString("6f89feb8-61c1-49be-a090-26a53dd55d15");
	       System.out.println(uuid.version());
	       System.out.println(uuid2.variant());
	       System.out.println(uuid2.node());
		}
}

Use Cases for UUIDs

  1. Database Primary Keys: UUIDs are often used as primary keys in databases to ensure uniqueness in distributed systems.
  2. Distributed Systems: In distributed systems, UUIDs can be used to identify resources or transactions uniquely.
  3. Session Management: UUIDs can be used to manage sessions and user authentication.
  4. Data Deduplication: In data processing pipelines, UUIDs are used to deduplicate data records.
  5. URL Shortening Services: Some URL shortening services use UUIDs to generate short and unique URLs.

Leave a Reply