16 September, 2013

Random Numbers in Java

Previously I posted  about Generate Random Passwords in Oracle that was using PLSQL.
Today I will post about java randoms.

Java provides two classes to generate random numbers: Random and SecureRandom.
Random is faster than SecureRandom, but it uses a 48 bits seeds which is not enough for the long type.
Moreover, it is not 'random enough' for cryptography. SecureRandom, is slower than Random, but can be used for cryptography.

The following code example shows how to generate a random number within a range for int, long, float and double.

Note rangeStart , rangeEnd is range period of generated numbers .

        int rangeStart = 50;
        int rangeEnd = 100;

        SecureRandom secRandom = new SecureRandom();
        int inclusive = rangeEnd - rangeStart + 1;
        int exclusive = rangeEnd - rangeStart;


        int randomIntInclusive = secRandom.nextInt(inclusive) + rangeStart;
        int randomIntExclusive = secRandom.nextInt(exclusive) + rangeStart;

        System.out.println("randomIntInclusive : " + randomIntInclusive);
        System.out.println("randomIntExclusive : " + randomIntExclusive);

        long randomLongInclusive =
            (secRandom.nextLong() % inclusive) + rangeStart;
        long randomLongExclusive =
            (secRandom.nextLong() % exclusive) + rangeStart;

        System.out.println("randomLongInclusive : " + randomLongInclusive);
        System.out.println("randomLongExclusive : " + randomLongExclusive);

        float randomFloat = (secRandom.nextFloat() * exclusive) + rangeStart;
        System.out.println("randomFloat : " + randomFloat);

        double randomDouble =
            (secRandom.nextDouble() * exclusive) + rangeStart;
        System.out.println("randomDouble : " + randomDouble);

The output will be
randomIntInclusive : 60
randomIntExclusive : 73
randomLongInclusive : 11
randomLongExclusive : 63
randomFloat : 65.19333
randomDouble : 84.14220368726888



Thanks

No comments:

Post a Comment

ADF : Scope Variables

Oracle ADF uses many variables and each variable has a scope. There are five scopes in ADF (Application, Request, Session, View and PageFl...