January 4 2017

Java generate random string

Java generate random string

The below example show you how to use the java.util.Random class to generate some random string data.

Example


package com.answersz;

import java.util.Random;

public class JavaGenerateRandomString {

public static void main(String[] args) {

// Java generate random string

// Allowed Characters Array
char[] allowedChars = "abcdefghijklmnopqrstuvwxyz".toCharArray();

// Length of required string
int stringLength = 10;

StringBuilder sb = new StringBuilder();

Random random = new Random();

for (int i = 0; i < stringLength; i++) {
char randomeChar = allowedChars[random.nextInt(allowedChars.length)];
sb.append(randomeChar);
}

String randomString = sb.toString();

System.out.println("Generated Random String : " + randomString);
}
}

Output(random strings)


Generated Random String : znvinypbkl
Generated Random String : edadhlktxg
Generated Random String : bbguzlcoyg
Generated Random String : hprpjspjza


Copyright © 2014. All rights reserved.

Posted January 4, 2017 by answersz in category Core Java

Leave a Comment

Your email address will not be published. Required fields are marked *

*