Generate Random String in Java

Random String Generation in Java

Yet another example on generating a random string in Java taking characters randomly from first and last names and attaching a random number <1000 at the end.


// For Scanner and Random classes
import java.util.*;
class GenerateRandomName
public static void main(String args[])

// Create a java.util.Scanner object for taking input from cmd
Scanner s=new Scanner(;

// Take first name
String fname=s.nextLine();

// Take last name
String lname=s.nextLine();

// Create java.util.Random object
Random r=new Random();

// Generate random name
String rname=fname.substring(0,r.nextInt(fname.length()-1))+lname.substring(0,r.nextInt(lname.length()-1))+r.nextInt(10000);

// Print random name
System.out.println("Random name: "+rname);



Random name: GowGut2446

The theme of generation is explained above. For further doubts, feel free to drop a comment.

Also see Generating Random numbers in Java

Posted by at on

Tags: Java Utilities,