Search code examples
javastringrandomchar

Java: Generate random letter, return as a String


I need to create a method to geneate random (single) letter and return it as String, not as a char.
I saw solutions like this creating random char. But I need my method to return a String type.
I managed to build the following method:

public static String randomLetter(){
    int num = intInRange(0, 26) + 97;
    char [] temp = new char[1];
    temp[0] = (char) num;
    return new String(temp);
}

Based on already existing method in our project

public static int intInRange(int min, int max) {
    Random rnd = new Random();
    return rnd.nextInt(max - min) + min;
}

But I do not like what I currently have since I'm creating too many temporary variables to achieve the goal.
Is there a way to get similar result in a shorter way to avoid usage of char [] temp ?


Solution

  • Try it like this. First cast the returned int as a char and then append "" to convert to a String.

    public static String randomLetter() { 
       return (char)(intInRange('a', 'z'+1)) +"";
    }
    

    Since String.valueOf() first boxes the char to Character and then calls String.valueOf() on that object, I would just call Character.toString() directly and avoid the extra overhead.

    public static String randomLetter() {
        return  Character.toString(intInRange('a', 'z'+1));
    }