Search code examples
javastringrandomfinal

How to randomly pick a string from multiple finals strings in Java?


As the question says, I've got multiple finals strings in a final class like this:

public final class MyStrings {

    public static final String stringOne = "this is string one";
    public static final String stringTwo = "this is string two";
    public static final String stringThree = "this is string three";
    public static final String stringFour = "this is string four";
    public static final String stringFive = "this is string five";

}

I know it could be easier to put them in a list or an array, but I would like to avoid runtime filling of those structures. Is it possible? What is the simplest way to choose randomly a string from that class? Thank you.


Solution

  • Your Strings seem very related, since you have a use case that needs to randomly choose one among them. Therefore, they should probably be gathered in an array anyway (on a semantic point of view).

    There won't be more "runtime filling" than with your current multiple fields:

    public final class MyStrings {
    
        public static final String[] strings = {
            "this is string one",
            "this is string two",
            "this is string three",
            "this is string four",
            "this is string five"
        };
    }
    

    Then you can pick one String randomly this way:

    Random random = new Random();
    String randomString = strings[random.nextInt(strings.length)]);