RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Tip: Creating the Hash for Short URLs

Learn to use the hashing function to generate random strings of six characters that can be numbers or upper and lowercase letters.


The hashing function is used to generate random strings of six characters, which can be numbers or upper and lowercase letters. We need to make sure that a string is not already used, but, choosing from 62 characters, we can make about ten billions strings. If we are getting repeated strings, we will output some warnings, and in this case, the solution would be to use longer codes or just start reusing them.

In the sample of code below, we generate the short code of six characters:

public class HystqioUtils {
             private static final String CHARSET = 
             public static String generateShortCode() {
                  StringBuilder buffer = new StringBuilder();
                  for (int i-0; i                        int r = random.nextInt(CHARSET.length());
             return buffer.toString();


Visit the DevX Tip Bank


Octavia Andreea Anghel is a senior PHP developer currently working as a primary trainer for programming teams that participate at national and international software-development contests. She consults on developing educational projects at a national level. She is a coauthor of the book "XML Technologies--XML in Java" (Albastra, ISBN 978-973-650-210-1), for which she wrote the XML portions. In addition to PHP and XML, she's interested in software architecture, web services, UML, and high-performance unit tests.
Email AuthorEmail Author
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date