Languages
[Edit]
EN

Java - pick random string from array of strings

8 points
Created by:
rmlocerd
302

1. Random string from array of strings

We need to generate random index of an array.
As nextInt function is called we pass int bound to have results within array size.

import java.util.concurrent.ThreadLocalRandom;

public class JavaRandomStringFromArray {
    
    public static String randomStringFromArr() {
        String[] arr = {"A", "B", "C", "D", "E", "F"};
        int randIdx = ThreadLocalRandom.current().nextInt(arr.length);
        String randomElem = arr[randIdx];
        return randomElem;
    }

    public static void main(String[] args) {
        System.out.println(randomStringFromArr()); // F
        System.out.println(randomStringFromArr()); // B
        System.out.println(randomStringFromArr()); // A
    }
}
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - pick random string from array of strings

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join