Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Generating Random Names in Java

Tech May 13 2

Selecting Random Elements from an Array

To randomly select a name from a predefined collection, begin by establishing an array containing potential name options.

// Define an array of sample names
String[] nameList = {"Alice", "Bob", "Charlie", "David", "Emily"};

Next, utilize Java's built-in Random class to generate a random index within the bounds of the array length.

import java.util.Random;

// Initialize random number generator
Random generator = new Random();

// Generate random index based on array size
int randomIndex = generator.nextInt(nameList.length);

// Retrieve name at the generated position
String selectedName = nameList[randomIndex];

Finally, display the chosen name through standard output.

// Print the randomly selected name
System.out.println("Selected name: " + selectedName);

Complete Impelmentation Example

import java.util.Random;

public class NameSelector {
    public static void main(String[] args) {
        // Available name options
        String[] candidates = {"Alice", "Bob", "Charlie", "David", "Emily"};
        
        // Setup random selection mechanism
        Random rng = new Random();
        
        // Determine random position
        int position = rng.nextInt(candidates.length);
        
        // Extract chosen element
        String result = candidates[position];
        
        // Display outcome
        System.out.println("Chosen name: " + result);
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.