Explore Java Hacks and Tutorials
Be Social. Be Updated.

Java Random Number Generator


Java Random Number Generator

Here is a sample tutorial for generating random numbers in Java using java.util.Random class.

Random int number Java - Range Unspecified


import java.util.Random;
class JavaRandomNumber
{
public static void main(String args[])
{
// Create Random object
Random r=new Random();

// Generate 10 random integers

for(int i=0;i<10;i++)
{
int randomint=r.nextInt();
System.out.println("Random Integer : "+randomint);
}
}
}

r.nextInt(): Returns random number.

Random Java int number Generator - Range Specified


import java.util.Random;
class JavaRandomNumberRange
{
public static void main(String args[])
{
// Create Random object
Random r=new Random();
// Generate 10 random integers between 0 - 100

for(int i=0;i<10;i++)
{
int randomint=r.nextInt(100);
System.out.println("Random Integer : "+randomint);
}
}
}

r.nextInt(100): Returns random number from 0 - 100.


Random Java Long Number Generator



import java.util.Random;
class JavaRandomNumberLong
{
public static void main(String args[])
{
// Create Random object
Random r=new Random();
// Generate 10 random long values

for(int i=0;i<10;i++)
{
long randomlong=r.nextLong();
System.out.println("Random Integer : "+randomlong);
}
}
}


r.nextLong(): Generate random long number.


Java Random Boolean Value Generator


import java.util.Random;
class JavaRandomBoolean
{
public static void main(String args[])
{
// Create Random object
Random r=new Random();
// Generate random boolean - 10 times

for(int i=0;i<10;i++)
{
boolean randomboolean=r.nextBoolean();
System.out.println("Random Boolean : "+randomboolean);
}
}
}

r.nextBoolean(): Generates random boolean value (true/false).


Java Random Float Number Generator


import java.util.Random;
class JavaRandomFloat
{
public static void main(String args[])
{
// Create Random object
Random r=new Random();
// Generate random float - 10 times

for(int i=0;i<10;i++)
{
float randomfloat=r.nextFloat();
System.out.println("Random Float : "+randomfloat);
}
}
}

r.nextFloat(): Generates random float value.


Java Random Double Number Generator


import java.util.Random;
class JavaRandomDouble
{
public static void main(String args[])
{
// Create Random object
Random r=new Random();
// Generate random double - 10 times

for(int i=0;i<10;i++)
{
double randomdouble=r.nextDouble();
System.out.println("Random Double : "+randomdouble);
}
}
}


r.nextDouble(): Generates random double value.


Java Random Byte Numbers


import java.util.Random;
class JavaRandomBytes
{
public static void main(String args[])
{
// Create Random object
Random r=new Random();
// Generate 10 random byte values, store in byte array
byte[] b=new byte[10];

r.nextBytes(b);

for(byte t:b)
{
System.out.println(t);
}

}
}


r.nextBytes(b): Generates 'b' array length sized byte values & store them in b.

Note: Outputs vary.



Posted by at on

Tags: Java Utilities