Get a random string - Android java.util

Android examples for java.util:Random String

Description

Get a random string

Demo Code

/*//from w  ww  .  j a v  a  2s  . c o m
 * Copyright (C) 2016 venshine.cn@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.util.Random;

public class Main{
    /**
     * Get a random string
     *
     * @param source
     * @param length
     * @return
     */
    public static String randomString(String source, int length) {
        return StringUtils.isEmpty(source) ? null : randomString(
                source.toCharArray(), length);
    }
    /**
     * Get a random string
     *
     * @param sourceChar
     * @param length
     * @return
     */
    public static String randomString(char[] sourceChar, int length) {
        if (sourceChar == null || sourceChar.length == 0 || length < 0) {
            return null;
        }
        StringBuilder builder = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            builder.append(sourceChar[randomInt(sourceChar.length)]);
        }
        return builder.toString();
    }
    /**
     * Returns a pseudo-random uniformly distributed {@code int}.
     *
     * @return
     */
    public static int randomInt() {
        Random random = new Random();
        return random.nextInt();
    }
    /**
     * Returns a pseudo-random uniformly distributed {@code int} in the half-open range [0, n).
     *
     * @param n
     * @return
     */
    public static int randomInt(int n) {
        Random random = new Random();
        return random.nextInt(n);
    }
    /**
     * Returns a pseudo-random uniformly distributed {@code int} in the half-open range [min, max].
     *
     * @param min
     * @param max
     * @return
     */
    public static int randomInt(int min, int max) {
        Random random = new Random();
        return random.nextInt(max) % (max - min + 1) + min;
    }
}

Related Tutorials