here is my recommendation for your code.
1) Use int instead of a double in the loop; the integer takes less memory than the double.
//[...]
char randchar;
for (int i = 0; i < length; i++) {
//[...]
}
2) Use a StringBuilder to accumulate the result, instead of a string + concatenation (randalphanum).
The StringBuilder is always a better choice when building string in a loop.
//[...]
String randalphanum = "";
3) Create one constant to hold the possible values, as a char array instead of using "charAt" on a string; the computation will be the same, but in my opinion, this will make the code shorter and more readable.
public static final char[] CHARSTRING = {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; //(3)
//[...]
public static String getRandomAlphaNum(final int length) {
final StringBuilder randalphanum = new StringBuilder(); //(2)
double randroll;
char randchar;
for (int i = 0; i < length; i++) { //(1)
randroll = Math.random();
randchar = '@';
for (int j = 1; j <= 36; j++) {
if (randroll <= (1.0 / 36.0 * j)) {
randchar = CHARSTRING[j - 1]; //(3)
break;
}
}
randalphanum.append(randchar);
}
return randalphanum.toString();
}
Potential refactor
A) Instead of using the for loop with index and not using it, I suggest that you use a "while" loop, and decrement the index in the loop.
while (length > 0) {
length--;
}
B) Instead of calculating the position, you can generate a random int, in the range [0, 26]; using the java.util.Random#nextInt(int)
method.
RANDOM.nextInt(CHARSTRING.length); // between 0 and 25
Complete example:
public static final char[] CHARSTRING = {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0',
'1', '2', '3', '4', '5', '6', '7', '8', '9' };
public static final Random RANDOM = new Random();
public static void main(final String[] args) {
System.out.println(getRandomAlphaNum(15));
}
public static String getRandomAlphaNum(int length) {
final StringBuilder accString = new StringBuilder();
while (length > 0) { //(A)
final int selectedPosition = RANDOM.nextInt(CHARSTRING.length); //(B)
accString.append(CHARSTRING[selectedPosition]);
length--; //(A)
}
return accString.toString();
}
```
double
as type of the counter variable is dangerous because primitive floating point numbers cannot be represented exactly (when they have fractions). Avoid primitive floating point types unless accuracy is less important the speed in your calculations. \$\endgroup\$