Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Generating random numbers and strings in Java

In almost every project there is a need to generate some Random strings or numbers. What I see very often is that people use some custom implementation around Math.random() and other methods capable of Generating Random Strings. Depending on the implementation they behave like expected. Sometimes they don’t.

I wanted to point to a class that should be used as a replacement and offers most of the features you’ll need. RandomStringUtils from apache.commons.
Why? Because it’s simple, easy to read and well tested.

You need a random string using alphabet letters having a certain length?

RandomStringUtils.randomAlphabetic(42);
// sample output: yWmMtdxLcrqymTywwLlaEpAvYjItfDIGbrXLLCXSLE

Or maybe just numbers?

RandomStringUtils.randomNumeric(42);
// sample output: 617707242748093324842846603534472927492284

Or some “weird” input to see if you can break something?

RandomStringUtils.random(10);
// sample output: 䴴迒눁굘ヰ혡曁柩媠㰏

Hexadecimal is also often asked for, which line is more readable?

RandomStringUtils.random(16, "0123456789abcdef")
// compared to "what google found"
Long.toHexString(Double.doubleToLongBits(Math.random()));

I think you get my point. It’s got all the comfort you asked for.
Give it a try.

The post Generating Random Numbers and strings in Java appeared first on united-coders.com.



This post first appeared on United Coders, please read the originial post: here

Share the post

Generating random numbers and strings in Java

×

Subscribe to United Coders

Get updates delivered right to your inbox!

Thank you for your subscription

×