How to Pick a Random Character in Java

The following Java program can be used to generate a random character in Java. There are three functions in the program.

  • getRandomCharacter() returns a random character in the ASCII printable character set.
  • getRandomAlphabet() returns a random alphabet in english (a – z).
  • getRandomAlphaNum() returns a random alphanumeric character (0 – 9 & a – z).
import java.util.Random;

// Example - Java class to generate random characters
public class RandomCharDemo {
    
    public static final String ALPHANUMERIC_CHARACTERS = "0123456789abcdefghijklmnopqrstuvwxyz";
    
    public static void main(String[] args) {
        System.out.println("Random character:"+getRandomCharacter());
        System.out.println("Random Alphabet:"+getRandomAlphabet());
        System.out.println("Random Alphanumeric:"+getRandomAlphaNum());
        
    }

    // Create a random alphanumeric character in Java
    // Random alphanumeric generator function in Java
    // Only lowercase letters
    private static String getRandomAlphaNum() {
        Random r = new Random();
        int offset = r.nextInt(ALPHANUMERIC_CHARACTERS.length());
        return ALPHANUMERIC_CHARACTERS.substring(offset, offset+1);
    }

    // Create a random alphabet in Java
    // Only lowercase letters
    private static String getRandomAlphabet() {
        Random r = new Random();
        return String.valueOf((char)(r.nextInt(26)+'a'));
    }

    // Create a random ASCII printable character in Java
    // Returns both lowercase and uppercase letters
    private static String getRandomCharacter() {
        Random r = new Random();
        return String.valueOf((char)(r.nextInt(95)+32));
    }
}

There are number of uses for these functions. These can be used for generating random passwords or for generating random words in a program.

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution! Please email us.

Leave a Reply