4 November 2013

How to generate random character of alphabet in java?

Java has method for random int ,but it doesn't have method for random character,but it is not a problem.

SOLUTION:

You just need below snippet:
private static String getRandomCharacter() {
String alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int character=(int)(Math.random()*alphabet.toCharArray().length);
return alphabet.substring(character, character+1);
}


  • for small character simply replace with ABCDEFGHIJKLMNOPQRSTUVWXYZ with abcdefghijklmnopqrstuvwxyz or if you need small and capital letter then replace with ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz   
  • if you alphabet contains other characters ,just add them to alphabet :)