Android How to - Generate a random string








Question

We would like to know how to generate a random string.

Answer

import java.util.Random;
//from  ww  w . j  a v a  2s .co  m

public class Main{
  //
  static  public String getRandomHexString(int numchars){
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        while(sb.length() < numchars){
            sb.append(Integer.toHexString(r.nextInt()));
        }
        return sb.toString().substring(0, numchars);
    }
}