[Java] two methods for obtaining random strings

Source: Internet
Author: User
ArticleDirectory
  • Method 1
  • Method 2
  • Comparison of advantages and disadvantages

In SQL testing or other cases, we often need to obtain random strings.

Here we provide two methods to obtain random strings.

Method 1 parameter is the length of the string.
/** Generate a random string */public static string randomstring (INT length) {string STR = "random"; random = new random (); stringbuffer Buf = new stringbuffer (); For (INT I = 0; I <length; I ++) {int num = random. nextint (62); Buf. append (Str. charat (Num);} return Buf. tostring ();}

Method 2 [note] is only applicable to JDK 1.7. The parameter is also the length of the string.

/** Generate a random string, applicable to JDK 1.7 */public static string random (INT length) {stringbuilder builder = new stringbuilder (length); For (INT I = 0; I <length; I ++) {builder. append (char) (threadlocalrandom. current (). nextint (33,128);} return builder. tostring ();}

Comparison of advantages and disadvantages method 1 can generate characters that can appear in a given string, but only these characters can appear. The method of method 2 is simple and has many types of Characters in the generated random string. The disadvantage is that it is only applicable to JDK 1.7.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.