Random class:
- It is belongs to util package.
- It is used to work with System generated random integer values
nextInt():
- Non static method belongs to Random class.
- Random values will be generated in integer limits.
- Random value can be either positive or negative
Generate random value:
import java.util.Random;
class RandomNumbers
{
public static void main(String[] args)
{
Random rand = new Random();
int val = rand.nextInt();
System.out.println("Random value is : " + val);
}
}
Display multiple random values:
import java.util.Random;
class RandomNumbers
{
public static void main(String[] args)
{
Random rand = new Random();
for(int i=1 ; i<=10 ; i++)
{
int val = rand.nextInt();
System.out.println(val);
}
}
}
Mod(%) operator returns the remainder when we divide with any value
Program Generate Positive or Negative values from 0 to 50:
import java.util.Random;
class RandomNumbers
{
public static void main(String[] args)
{
Random rand = new Random();
for(int i=1 ; i<=10 ; i++)
{
int val = rand.nextInt();
System.out.println(val%50);
}
}
}
nextInt(int upperBound): Generate random values between 0 and specified bound
import java.util.Random;
class RandomNumbers
{
public static void main(String[] args)
{
Random rand = new Random();
for(int i=1 ; i<=10 ; i++)
{
int val = rand.nextInt(50);
System.out.println(val);
}
}
}
Generate 20 random numbers of 2 digits:
import java.util.Random;
class RandomNumbers
{
public static void main(String[] args)
{
Random rand = new Random();
int count=0;
while(count<20)
{
int val = rand.nextInt(100);
if(val>9){
System.out.println(val);
++count;
}
}
}
}